Week 1 - Section 2 - Controlling the flow v1

Site: ΕΛ/ΛΑΚ Moodle
Course: Python Lab - May 2017
Book: Week 1 - Section 2 - Controlling the flow v1
Printed by: Guest user
Date: Friday, 26 April 2024, 9:28 AM

Description

In this second section we will start to learn how to control the flow of the algorithm using the if statement 

Chapter 2.1 The if statement

How do we tell if a player has beat the high score? How can we tell if he has run out of lives? How can we tell if she has the key required to open the locked door?

What we need is the if statement. The if statement is also known as a conditional statement. (You can use the term “conditional statement” when you want to impress everyone how smart you are.) The if statement allows a computer to make a decision. Is it hot outside? Has the spaceship reached the edge of the screen? Has too much money been withdrawn from the account? A program can test for these conditions with the if statement.

Lets see an example code:

# Variables used in the example if statements 
a = 4
b = 5

# Basic comparisons
if a < b:
    print("a is less than b") 

if a > b:
    print("a is greater than b") 

print("Done")

What do you believe the code will send to the screen(output)?

Since a is less than b, the first statement will print out if this code is run. If the variables a and b were both equal to 4, then neither of the two if statements above would print anything out. The number 4 is not greater than 4, so the if statement would fail.

What other operators can we use for comparing?

# Equal
a = 5
b = 5
if a == b: # Remember that comparison is made using ==
     print ("a is equal to b")

# Not Equal
a = "Alice"
b = "Bob"
if a != b: # The exclamation mark ! stand for not
     print ("a is equal to b")


Chapter 2.2 - Identation

Indentation matters. Each line under the if statement that is indented will only be executed if the statement is true. After the intended block execution continues as normal.

# Indentation 
a = 2
if a == 1:
    print("If a is one, this will print.")
    print("So will this.")
    print("And this.")
print("This will always print because it is not indented.")

Indentation must be exactly the same. Following code doesn't work :

if a == 1:
  print("Indented two spaces.")
    print("Indented four. This will generate an error.")
   print("The computer will want you to make up your mind.")


Chapter 2.3 - And / Or

An if statement can check multiple conditions by chaining together comparisons with and and or. These are also considered to be operators just like + or - are.

# And 
if a < b and a < c:
    print("a is less than b and c")

# Non-exclusive or
if a < b or a < c:
    print("a is less than either b or c (or both)")

A common mistake is to omit a variable when checking it against multiple conditions. The code below does not work because the computer does not know what to check against the variable c. It will not assume to check it against a.

# This is not correct
if a < b or < c:
    print("a is less than b and c")

Chapter 2.4 - Variables again (Boolean this time)

Python supports Boolean variables. What are Boolean variables? Boolean variables can store either a True or a value of False. Boolean algebra was developed by George Boole back in 1854. If only he knew how important his work would become as the basis for modern computer logic!

An if statement needs an expression to evaluate to True or False. What may seem odd is that it does not actually need to do any comparisons if a variable already evaluates to True or False.

# Boolean data type. This is legal! 
a = True
if a:
    print("a is true")

Ok so a is (==) True. And what about not a. Is it also True? Of course not. If a is True then not a should be False and if a is False then not a should be True

How can we write this using code. It is very simple.

The following two examples are both correct.

# How to use the not function - example 1
a == False
if not(a):   #
What is not(a) ?
    print("a is false")

# How to use the not function -  example 2
if not a: # What is not a ?
    print("a is false")

Of course we can combine statements using and

a = True
b = False

if a and b:
    print("a and b are both true")

or or operands

a = True
b = False

if a and b:
    print("one or both of a and b are true")


Chapter 2.5 - If and more If - Else if?

Below is code that will get the temperature from the user and print if it is hot. 

temperature = int(input("What is the temperature in Celsius? ")) 
if temperature > 30:
    print("It is hot outside")
print("Done")

So you can in the first command we read the temperature from the keyboard and convert it to integer in one command instead of two :

temperature = input("What is the temperature in Celsius? ")
temperature = int(temperature)

What if we wanted to print that it is not hot outside? Of course we could insert another if statement but instead we can use the more advanced syntax of if command like the following example.

temperature = int(input("What is the temperature in Celsius? "))
if temperature > 30:
    print("It is hot outside")
else:
    print("It is not hot outside")
print("Done")

Or the even more advanced syntax using if, multiple else if and a final catch up all the rest else command like the following example.

temperature = int(input("What is the temperature in Celsius? "))
if temperature > 30:
    print("It is hot outside")
elif temperature < 12:
    print("It is cold outside")
else:
    print("It is not hot outside")
print("Done")

In the previous code , the program will output “It is hot outside” even if the user types in 50 degrees. Why? How can the code be fixed?