Python training exercise 3

From BITS wiki
Jump to: navigation, search

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!!!


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.

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.

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"


Back to main page