Join us
Python has a wonderfully simple syntax, deceptively so, however do not mistake its simplicity for lack of power, for Python is a powerful language, but there are a few rules and your author is a very opinionated developer, at first do things his way, then, as you gain experience, you can develop your own ways and become just as opinionated, but if nothing else informed about the opinions of other developers and you can be an informed, opinionated developer!
First thing any developer new to Python must know, spaces in Python is significant and indentation controls the flow of the program, four space indentation, or one tab, but always insert spaces.
Python has a wonderfully simple syntax, deceptively so, however do not mistake its simplicity for lack of power, for Python is a powerful language, but there are a few rules and your author is a very opinionated developer, at first do things his way, then, as you gain experience, you can develop your own ways and become just as opinionated, but if nothing else informed about the opinions of other developers and you can be an informed, opinionated developer!
First thing any developer new to Python must know, spaces in Python is significant and indentation controls the flow of the program, four space indentation, or one tab, but always insert spaces.
A lot of people who don’t use Python complain about this enforced style, the reality is you very quickly adapt to it and develop a readable code because of it.
As a beginner, you will find the syntax clean and readable and you should strive to keep your code as clean as possible. One thing your author has noticed when teaching others to code is that, in the beginning, the structure and aesthetics of code is difficult to master, but it’s something to pay attention to, because understanding what your code is doing is made easier when you can read it! Many companies will have a coding style which you would be expected to adhere to, even in your own personal projects, it is advised to find a style that works for you and stick with it.
Python is an interpreted language means there are two ways to run code, both utilize the `python` command line program, typically one can run python with a text file containing python code and the interpreter will run the code and exit. Another means by which to run python code is an interactive environment in which to experiment called the Python REPL, the Read-Evaluate-Print-Loop. If one chooses to run `python` at the terminal without passing it a file to run, the REPL will open up and allow you to type code into it directly.
If I want to experiment or quickly do something I often won’t bother to open a file and save code, I will often use the repl to experiment and test things. In this article samples that are to be explicitly interpreted in the repl will have lines that begin with ‘>>>’ as this is what the repl uses as a prompt.
You can exit the repl by either hitting ctrl+d or by typing ‘exit()’ at the prompt. Nothing is saved in the repl, so don’t worry if you get errors, it’s perfectly natural.
Every book has a Hello World example and I’m not one to break tradition, so there it is, frankly, it’s somewhat underwhelming, but that’s a good thing! Print takes a string, and displays it in the standard output,
>>> print(‘Hello World’)
The input function can also take an optional parameter which is what you will display as a prompt:
>>> user_input = input()
>>> user_input = input(‘please enter something, anything… ‘)
The return value of input is a string containing whatever the user input so we can store it in a variable for later use.
In programming, it’s often useful to leave notes to others (including your future self), these are called comments!
In Python single line comments being with the hash (or if you don’t speak British English the pound character) like so:
# This is a comment
If you wish for a comment to span multiple lines use the triple quote syntax:
“”” this is a comment
But it just so happens
That it spans
Many lines ”””
One exception to this rule however is that if you use a triple quote as the first statement of a function or class, it will be interpreted as a docstring.
Python has most of the same operators you’d expect from other programming languages, using them is as simple as ‘1 < 2’ much like in elementary school mathematics or other languages
Before we look at branching and looping, where the and/or keywords will be useful, it will be worth looking at exactly how they work as they may broadly do what you expect, but how they do it may not be!
And returns returns the first false value or the last true value.
Or returns the first true value or the last false value.
A small detour into something known as truthiness and falsiness is required, values that are not specifically Boolean types can behave like a Boolean.
For instance a numeric 0 is false and any other value is true, because 0 is nothing and anything else is something, even if it is a negative value.
An empty list [] is considered Boolean false for the same reason as it has no values, a list with even one value is considered true.
This is why the following works:
>>> 5 and [1]
>>> 1 or False
>>> 9 and []
Not is an operator that takes a value and returns a truthy or falsy value, casting to True/False if required.
>>> not 5
False
>>> not True
False
>>> not False
True
>>> not {} or []
True
That last one is a little tricky, but if we use the simple substitution rules learned previously with and/or and how empty objects are treated as truthy or falsey we can unpack it as follows.
not {} or []
Evaluate and substitute {} or [] first, which gives us simply [] since or gives us the first truthy value or the last falsey one, there’s two values, an empty dictionary so that’s skipped, not being true and all, and we get to the second one, which in this case it is also the last element so or doesn’t care if it is true or false, it’s all there is left so it is returned, which means the statement is simplified to
not []
With [] being falsey the inversion of a falsey value must be True.
Python allows you to assign variables with a simple equals sign, if a variable does not currently exist in the scope, it will be created:
>>> X = 5 # int
>>> X = 2.5 # float
>>> X = ‘something’ # string
Like all programming languages, Python supports a branching construct, the ‘if’, there is no ‘switch-case’ or ‘cond’. This is not an oversight, but a deliberate design choice.
If statements are very simple, unlike some other languages, there’s no need to wrap the condition in parenthesis either:
if condition:
action()
Anything indented below the if block will be the body of the if block. And/or/not can be used here to build up complex boolean logic if needed.
if 9 and 5:
action()
And this is where truthiness and falsiness come into play because ‘9 and 5’ evaluates to 5, the if statement will actually perform ‘if 5’ and since any number other than 0 is considered Boolean true, the body of the if block runs.
Likewise if you did something like the following, it would reduce to a simpler form:
>>> if [1] or 0:
… action()
>>> if [1]:
… action()
And following the truthiness of a non-empty list the if block body executes.
There is a concept of an else if, called elif in python, of which multiples can exist in am if block and also an else clause
>>> if a:
… something(a)
>>> elif b:
… something(b)
>>> elif c:
… something(c)
>>> else:
… something_else()
Python likewise has loops, a for loop (which really behaves more like a for-each loop) and a while loop, there’s no do-while. Once again, these omissions are not flaws, but deliberate choices. I’ll explain both loops and how to use functions to help make loops super easy and useful to work with.
Something to consider while working in Python is that since it’s primary for loop is implemented in terms of a for-each loop there’s no way to track how many times a loop has run. This leads developers new to Python to declare variables outside the loop and update the loop counter, this is entirely unnecessary!
The basic structure of a for loop is:
for var[, n, …] in iterable:
action()
If you wish for a loop to run X number of iterations but don’t actually care about the specific items in a list, you can use the range function!
>>> for X in range(10):
… print(X)
Range starts from 0 and yields ten sequential numbers, technically the loop has an iterable of items and for-eachs over the items but it serves the same function as a loop with a counter. In this specific example you would know how far the loop iteration you are because it is sequential numbers, but what if you have, for example a list of names?
>>> counter = 1
>>> for name in [‘Stanley’, ‘Okonkwo’, ‘Ebuka’, ‘Okeke’]:
… print(f’{counter}: {name}’)
… counter += 1
Many people go to this as an adequate solution, this is also a sign you’re reading someones code who isn’t a Pythonista, the more Pythonic way to write this would be as follows:
>>> for num, name in enumerate([‘Stanley’, ‘Okonkwo’, ‘Ebuka’, ‘Okeke’]):
… print(f’{num}: {name}’)
The enumerate function takes an iterable, in this case a list and an optional start index, and yields a two value tuple containing the index and item, which we can unpack in the loop. It is worth noting that the start index defaults to 0, so in the following code we do exactly the same as we did above but we passed in 1 as the start index.
>>> for num, name in enumerate([‘Stanley’, ‘Okonkwo’, ‘Ebuka’, ‘Okeke’], 1):
… print(f’{num}: {name}’)
The while loop construct follows very similar in structure to the for loop:
while condition:
action()
Unlike for however, while does deal with state rather than iterables. You can use any truthy or falsey expression, includes ands, ors, nots to your heart’s content, this means you can create an infinite loop very simply, I’m fact the following snipped I wrote on a big chocolate heart for an ex girlfriend of mine lol.
>>> while True:
… print(‘I ❤ U!’)
She left, proof that infinite loops can be broken!
Break and continue are common keywords in many programming languages and are used for loop control. If you have not encountered them before break allows you to exit (break out of) a loop early. Continue however allows you to skip to the next iteration of the loop, an optimization if you know this particular loop iteration has nothing left to do.
They can be combined in the same loop structure if so required.
>>> for x in range(10):
… if x % 2 == 0:
… continue
… print(x) # print only odd numbers
… if x == 7: # break on the lucky number
… break
There’s one final thing about loops that can be introduced here, loops, like if, can have an else clause, this is one of the weirder things to think about, but it is actually a useful and elegant piece of syntax to have under certain circumstances. The else clause attached to a loop executes if the loop completed without breaking. That is to say, a loop either breaks, else it runs to completion.
>>> a = 3
>>> while a:
… print(a)
… a -= 1
… else:
… print(‘Done’)
…
3
2
1
Done
>>> a = 3
>>> while a:
… print(a)
… a -= 1
… if a == 1:
… break
… else:
… print(‘Done’)
…
3
2
Done
Fun fact, while writing these examples out, I actually forgot to reset ‘a’ back to a number and found something out that I didn’t previously know and felt I simply had to include here! If the condition of the while loop begins as false, the else block immediately runs!
>>> a = 0
>>> while a:
… print(a)
… a -= 1
… if a == 1:
… break
… else:
… print(‘Exited without breaking’)
…
Exited without breaking
Which makes absolute total sense, I’d just never once thought about it and should hopefully assure you, reader, that we are all, always learning new things!
So guys I will stop here and next publications will be coming soon where I will explain about “Scope, Data Types, Functions, Classes etc.
Feel free to give a clap!! and follow me.
Join other developers and claim your FAUN account now!
Software Engineer, motionstudio.io
@jaguar48Influence
Total Hits
Posts
Only registered users can post comments. Please, login or signup.