Week 2 - Section 1 - Controlling the flow v2

Site: ΕΛ/ΛΑΚ Moodle
Course: Python Lab - May 2017
Book: Week 2 - Section 1 - Controlling the flow v2
Printed by: Guest user
Date: Tuesday, 7 May 2024, 10:29 AM

Description

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

Chapter 3.1 - If and more If - Else if? or Else?

3.1 - Decision making

When we want to make a decision and from the outcome of the decision act then we use the if command.

Copy and paste the following code to the editor of Thonny

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


As you can see inside the code there are three cases. One when temperature is greater than 30, one when temperature is lower than 12 and one in every other case.

Try the code using different temperature more than 30, between 12 and 30 and less than 12.

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

If you want to see a solution click here.

Chapter 3.2 - Multiple cases in IF

3.2 - Multiple cases in if command

What is and inside the if command? and means that in order for the statement to be true both statements should be true.

print ("Check Up") weight = int(input("Insert your weight in kilos : ")) height = int(input("Insert your height in centimeters : ")) if weight >=100 and height <= 170: print ("You might consider to lose some weight") elif weight<= 50 and height > 175: print ("I think that you are very skinny") else: print ("You are just about right")


What is or inside the if command? or means that in order for the statement to be true one or both statements should be true.

print ("I know my friends") name = input("Please write your name : ") if name == "John" or name == "Jim" or name == "Justin": print ("Hello my friend", name) else: print ("Do you want to be my friend", name, "?")


In the programs above think which are the variables and what type are these variables.

We have now a new problem for you.

We want to create a program that asks for three numbers and then displays the greatest. 

As an example when we execute the program the output could be :

Hello! Please insert three different integer numbers and i will find the greatest.
The first number is :  13
The second number is :  19
The third number is :  8
Great! The greatest number of 13,19,8  is  19.

You can find a solution here


Chapter 3.3 - If inside an if = nested if?

3.3 - Nested if

Sometimes we want to check a condition inside another condition. 

If we want to issue a forecast for temperature and humidity we can write the simple code below. 

In order for the second condition (humidity) to be examined the first (temperature > 30) must be true. 

Copy and paste the following code to Thonny. You can view the steps of execution using the Debug button.

Thonny Debug Button

print ("This is my weather forecast") tempr = int(input("Please insert the Temperature in Celsius : ")) hum = int(input("Please insert the Humidity of the air : ")) if tempr > 30: if hum > 80: print ("It's hot and humid") else: print ("It's hot but not humid") else: print ("It's not hot")

Chapter 3.4 - Range

3.4 - Range

What is a loop in programming? In computer programming, a loop is a sequence of instructions that is continually repeated until a certain condition is reached.

What will we do to print 10 times our best friends name? We could write the following code 10 times:

print("My best friends name is Nick") print("My best friend's name is Nick") print("My best friend's name is Nick") print("My best friend's name is Nick") print("My best friend's name is Nick") print("My best friend's name is Nick") print("My best friend's name is Nick") print("My best friend's name is Nick") print("My best friend's name is Nick") print("My best friend's name is Nick")


Instead we can write do the first command 10 times.

First of all we have to learn the range command. When we write range(10), python generates a list of numbers, which is generally used to iterate over with for loops.

So range(5) contains 5 numbers [0, 1, 2, 3, 4]. In computer languages counting starts from 0 (zero).

If you want to view what is inside a range you can write the command  in CLI
>>>list(range(5))

Try also the following and try to understand what range does

>>>list(range(3,6))     # The result is [3, 4 , 5]

>>>list(range(9,16))   # The result is [9, 10 , 11, 12, 13, 14, 15]

So a list includes numbers starting from the first one until the last one without including the last one and increasing (stepping) them with 1.

If we omit the first number it is like writing 0

>>>list(range(5)) is the same as >>>list(range(0,5))

What else can we do with range? Write the step.

Try the following in CLI

>>> list(range(2,20,3))

The first item is 2, the next is 5 (2+3), the next is 8 (5+3) .... and the last one is 17, 20 is not included in the list)

As an exercise try the following code and before execution try to foresee the result :

>>>list(range(1,9,2))

>>>list(range(7))

>>>list(range(7,17,4))

As an exercise write a range command that has 10 numbers.
Of course the easiest is range(10). List it with the command
>>>list(range(10))

Chapter 3.5 - The For loop

3.5 - The For loop

When i use a loop? When i want to repeat a block of code. The for loop is used when i know how many times i wan the code to be executed. Copy the following code to Thonny's editor. To view the execution step by step you can press the Debug button, after that the Step into (F7) and finally Step over(F6). Take a closer look at the variable x in the right pane of Thonny.

for i in range(10): print("I will not chew gum in class.")


Also try the following

for i in range(5): print("Please,") print("Can I go to the mall?")


And changed to this

for i in range(5): print("Please,") print("Can I go to the mall?")


Try the following code and try to explain what is its purpose :

for x in range(10): print (i, "* 5 =", i*5)

Do you have an idea of how we can make it better? Try this one now :

for i in range(1,11): print (i, "* 5 =", i*5)


And now this one :

number = int(input("Please write a number for 1 to 10 : ")) for i in range(1,11): print (i, "* ",number," =", i*number)

Chapter 3.6 - Nested for loops

3.6 - Nested for loops


Try to predict what the code below will print. Then enter the code and see if you are correct.

# What does this print? Why? for i in range(3): print("a") for j in range(3): print("b")

This next block of code is almost identical to the one above. The second for loop has been indented one tab stop so that it is now nested inside of the first for loop. This changes how the code runs significantly. Try it and see.

# What does this print? Why? for i in range(3): print("a") for j in range(3): print("b") print("Done")


Now try to create a program that will output

Nested Loops Example
1
a
a
a
a
2
a
a
a
a
3
a
a
a

Here you can view a solution to the problem.

Chapter 3.7 - Calculating a sum

3.7 - Calculating a sum

A common operation in working with loops is to keep a running total. This “running total” code pattern is used a lot in this book. Keep a running total of a score, total a person's account transactions, use a total to find an average, etc. You might want to bookmark this code listing because we'll refer back to it several times. In the code below, the user enters five numbers and the code totals up their values.

print ("Calculation of the total of 5 numbers") total = 0 for i in range(5): new_number = int(input("Enter a number: " )) total = total + new_number # or you can write total += new_number print("The total is: ", total)


So how can we calculate this sum S=1+2+3+4+5+6+7+8+9+ ...... + 1000? What is the range of this numbers? Is it range(1000) or range (1,1001)? If you don't know try to find listing the range. Of course feel free to think something different 

The commands are
>>>list(range(1000))
and 
>>>list(range(1,1001))

A solution to the problem is :

print ("Calculation of the Sum of the 1000 first numbers") total = 0 for i in range(1,1001): # or you can use range(1000) and add (i+1) to the total total = total + i # or you can write total += i or total += i+1 print("The total is: ", total)


And what this program does?
print ("What this program does?") total = 0 for i in range(2,100,2): # print ("The temporary total is : ", total) # print ("The number i am going to add to the temporary total is :", i) total += i # print ("The temporary total after the addition of ",i, "is :", total) # print() print("The final total is: ", total)


Carefully remove the # signs and take care of indentation to see the program running and giving information about what is doing. This a form of debugging.

So this program calculated the sum of even numbers between 0 and 100. Can you modify it to calculate the odd numbers from 1 to 99? You need to change only one number, but you can find your own solution. The answer is 2500.