Python 2 While and For Loops and Functions
Python 2 While and For Loops and Functions
1 If Statements (https://www.w3schools.com/Python/python_conditions.asp )
Here are examples of logical conditions which are used to make decisions.
Equals: a == b
Not Equals: a != b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
a = 33
b = 200
if b > a:
print("b is greater than a")
Explain what was printed to the screen, explain why it printed this.
B is not equal to a
__________________________________
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
a and b are equal
Name: Lloyd 81s
count = 0
while (count < 9):
print ('The count is:', count)
count = count + 1
for i in range(1,10):
print(i)
for i in range(2,10,2):
print(i)
What does this code do?
This is an algorithm for working out times tables. Use this algorithm
to make a program which calculates times tables.
Explain how this code runs using words. This is called Pseudocode.
Step 1: The outer loop prints the first word “Red”, then it jumps to the inner loop and
prints
Step 2:
STEP 3:
A function is a block of code which only runs when you tell it to run.
Functions help break our program into smaller and modular chunks. As our
program grows larger and larger, functions make it more organized and
manageable.
Functions help to avoid repetition and makes code reusable.
Here is another example of a Function but there is a mistake. I’ll give you a hint, you need to
delete one character to get it to work.
def hello_function():
print("Hello World")
print("How are you?")
#hello_function()
Printscreen to show that you got it working.
Name: Lloyd 81s
Example Program: Guessing Game
import random
if guess == randomnumber:
print ("Hit!")
elif guess < randomnumber:
print ("Your guess is too low")
else:
print ("Your guess is too high")
Tasks:
1. Change the game so it doesn’t show the random number during the game.
Print screen it below.
2. Change the game so that it generates two random numbers and compares them
to each other. Print screen it below.
4. Change the program so it allows you to guess more than once until you get
it right. You will need a while loop to keep the game playing and you
will need a variable such as tries. Print screen it below.
Example Program: Create a Program that uses a FOR loop and paste it below. Explain
what each part of the code does.
Example Program: Create a Program that uses a WHILE loop and paste it below. Explain
what each part of the code does.
Example Program: Create a program that uses FUNCTIONS and print screen it below