Python training exercise 3
Contents
Introduction
Programs start to become more interesting if you can do different things depending on the input. For this, you have to use conditions, which we will discuss in this section.
Exercises
Booleans
First it's necessary to introduce two more data types: the booleans True and False, as well as the nothing value None.
Python returns booleans when comparing values:
myInteger = 5 print(myInteger == 6) # This means 'is myInteger equal to 6?' print(myInteger < 6) # This means 'is myInteger smaller than 6?' print(myInteger > 6) # This means 'is myInteger greater than 6?' print(myInteger <= 6) # This means 'is myInteger smaller or equal to 6?' print(myInteger >= 6) # This means 'is myInteger greater or equal to 6?' print(myInteger != 6) # This means 'is myInteger not equal to 6?'
You can also use is and not:
myInteger = 5 print(myInteger is 6) # Same as == print(myInteger is not 6) # Same as != print(not myInteger > 6) # Same as <=
It is also possible to use logic combinations with and and or:
x = 5 y = 6 print(x == 5 and y > 2) # Both have to be True for the result to be True print(x != 5 or y > 2) # Only one has to be True for the result to be True
If and indentation
The if condition allows you to only execute a bit of code if a (set of) condition(s) is satisfied. Python syntax requires that you put a colon : after the if, and that the block of code that is conditional is indented with the same amount of spaces (or tabs). For style and debugging reasons it is best that you always use spaces for the indented blocks, we will be using an indentation of 2 spaces. Now try this:
x = 5 if x == 5: print("x is five!") if x != 5: print("x is not five!")
you will see that only the block of code under x == 5 is printed out. You can of course make the conditions more complex and combine them with and and or:
x = 5 y = 10 if (y / x) == 2: print("y divided by x is 2!") if y == 10 or x == 2: print("x is two or y is ten") if y == 10 and x == 2: print("x is two and y is ten") print("The end")
Here you see that the blocks for the first two conditions (which are True) are executed, but not the third. The last line of code is always printed off - it's on the same level as the start of the code, and not conditional.
The level of indentation is crucial, and Python will immediately give an error if there are inconsistent levels of indentation in the code. Try this:
x = 5 y = 10 if (y / x) == 2: print("y divided by x is 2!") print ("And x is {}!".format(x))
You will immediately get IndentationError: unexpected indent.
Note that this can also happen if you start mixing space and tab characters!!!
Write a program where you ask the user for x and y, make sure that y is not zero, and print out x/y. [click on show more for answer) |
---|
xString = input("Give me x:") yString = input("Give me y:") x = float(xString) # Using float here so we'll get accurate division later on y = float(yString) if y != 0: result = x / y print("X divided by Y is {:.3f}".format(result)) |
elif
Once you have an if: condition, you can directly follow it up with an elif: (else if) condition. This is not the same as another if: statement as illustrated in the second example on this page; an elif: is only executed if the previous if: (and other preceding elif:s) are not True. Try this modification of the second example:
x = 5 y = 10 if (y / x) == 2: print("y divided by x is 2!") elif y == 10 or x == 2: print("x is two or y is ten") elif y == 10 and x == 2: print("x is two and y is ten") print("The end")
Now only the code under the first condition is executed, not the second (the third is not True and is in any case irrelevant). If we switch the conditions around a bit:
x = 5 y = 10 if y == 10 and x == 2: print("x is two and y is ten") elif y == 10 or x == 2: print("x is two or y is ten") elif (y / x) == 2: print("y divided by x is 2!") print("The end")
The first condition is not True, so the second is evaluated. This one is True, so it is executed, and the text x is two or y is ten is printed. For clarity it is often useful to leave some space before and after the (set of) condition(s) - it makes the code easier to 'read' afterwards.
Write a program where you ask the user for two words. Compare the words; if they are the same, print a message, if the first or second word is 'Stop', then also print a message. [click on show more for answer) |
---|
print ("Give two words.") myString1 = input("Give the first word:") myString2 = input("Give the second word:") if myString1 == myString2: print("These words are the same.") elif myString1 == 'Stop' or myString2 == 'Stop': print("One of these words is 'Stop'") |
else
You can also end an if (with or without elifs) with an else condition. The block of code following else is only executed if the previous (set of) conditions are all False. Try this:
x = 7 if not (x % 2): print("x is divisible by two!") elif not (x % 3): print("x is divisible by three!") else: print("x is not divisible by two or three...") print ("x is {}".format(x))
You can modify the value of x a bit to see what else can happen.
Can you spot a problem with this example? What will happen if x can be divided by both two and three? What can you do to solve this problem? [click on show more for answer) |
---|
If a value can be divided by two and three, only the block of code under the first condition will be executed, so you will not find out whether your value can be divided by three! There are several solutions to this, for example:
x = 7 if not (x % 2): print("x is divisible by two!") if not (x % 3): print("x is divisible by three!") elif not (x % 3): print("x is divisible by three!") else: print("x is not divisible by two or three...") print ("x is {}".format(x)) This is not a very elegant solution however, as you are repeating the same bit of code twice to find out whether the value can be divided by three. This one might be slightly better: x = 7 if not (x % 2): print("x is divisible by two!") if not (x % 3): print("x is divisible by three!") if (x % 2) and (x % 3): print("x is not divisible by two or three...") print ("x is {}".format(x)) However you still have to repeat the conditions, which would become very tedious (and error-prone) if you were to try division by many values. The next example is a bit more verbose but cleaner and more 'extendable' for other values: x = 7 xDivisible = False if not (x % 2): print("x is divisible by two!") xDivisible = True if not (x % 3): print("x is divisible by three!") xDivisible = True if not xDivisible: print("x is not divisible by two or three...") print ("x is {}".format(x))
|
The None variable
Finally, there is also a None data type, which is really nothing. Note that in comparisons Python will assume 0 and an empty string "" as being False in logic terms:
print(not True) print(not False) print(not 0) print(not "")
Really 0 is still an integer, "" a string, so None is really nothing:
print(not None) print(0 == None) print("" == None) # Also try this: if None: print "Hello1" if "": print "Hello2" if 0: print "Hello3" if "" != None: print "Hello4"