Vous êtes sur la page 1sur 26

Mastering Programming in Python

Lesson 3

Introducing Iteration (Loops)

100s of other resources are available from

www.teachingcomputing.com

Series Overview

Introduction to the language, SEQUENCE variables, create a Chat bot


SELECTION (if else statements)
ITERATION (While loops)
Introducing For Loops
Challenges and tasks for Mastering Iteration
Use of Functions/Modular Programming
Introducing Lists /Operations/List comprehension
Tuples, sets, lists, dictionaries
Use of Dictionaries
Doing things with strings
File Handling Reading, writing, appending text files
Working with CSV files
Practical Programming (plenty of engaging scenarios, challenges
and tasks to get you thinking)
Consolidation of all your skills useful resources
Includes Computer Science theory and Exciting themes for every
lesson including: Quantum Computing, History of Computing,
Future of storage, Brain Processing, Systems life Cycle, Testing
and more

Information/Theory/Discuss
Task (Code provided)
Challenge (DIY!)
Suggested Project/HW

*Please note that each lesson is not bound to a specific time (so it can be taken at your own pace)

In this lesson you will

Learn about Iteration (loops)


How loops work and what they are
Create and adapt programs using loops
Intro to the random number generator
Learn about trace tabling (white box testing)
Wonders of the Fibonacci Sequence
Focus on: While Loops

Did you know?


Ada Lovelace is considered by many to be the first computer programmer!
She was the daughter of the poet Lord Byron and wrote
extensively on Charles Babbages analytical engine
Some historians note that the first instance of a software loop
was when Ada used them to calculate the Bernoulli numbers.
Joseph Jacquards mechanical
loom (1801)had a very early
application of a loop ordering a
machine to produce a repeated
outcome.
Charles Babbages analytical
engine also made use of loops!

Ada Lovelace, 1840

Examples of Iteration in Game design


ITERATION is referring to the use of loops. Loops are used all the
time in programming and in game design. A while loop below:
collision detection

Loops in Game design?


Each frame the game
displays is one time
through a loop. You may
have heard of the
frames-per-second (FPS)
statistic that games show.
The FPS represents the
number of times the
computer updates the
screen each second. The
higher the rate, the
smoother the game

Types of loops in Python


The Python language has a number of loops - our focus in this
session: WHILE

TYPE OF
LOOP

WHILE
LOOP

FOR LOOP
NESTED LOOP

DESCRIPTION OF LOOP
WHILE a given condition is TRUE, it repeats a statement or
group of statements. The stopping condition is found at the
START (tests it before looping)
A sequence of statements are executed multiple times. A for
loop is typically used when the amount iterations are known in
advance.
A loop of any kind can be used inside any other while, for or
dountil loop!

What is a loop?
Usually, statements are executed in sequence. This means the
second statement is run after the first statement and so on.
Sometimes you may need to execute a block of code or a
statement over and over again. This is where Loops are
particularly handy
A loop is a CONTROL
STRUCTURE that
allows for a statement
If condition is true
CONDITI
or group of
CONDITIONAL
ON
CODE
statements to be
Loops will need a
repeated
If condition is false
STOPPING CONDITION
(or starting condition)

Introducing the While Loop


In programming, a while loop is a control flow
statement that allows code to be executed repeatedly
based on a given Boolean condition.
You could also think of a while as a repeating if
statement.
In a while loop, because the condition is at the START, it

Task 1: Guess the number! (While loop)


1. Open a Python
Module
2. Copy and paste
the code on the
right into the
module
3. Analyse the code
and try the
program for
yourself!
4. Note the while
loop!

import random
n = 10
guess_number = int(n * random.random()) + 1
guess = 0
print("****GUESSING THE RANDOMLY GENERATED
NUMBER*******")
while guess != guess_number:
guess = int(input("Enter Number: "))
if guess > 0:
if guess > guess_number:
print("Too high....try again")
elif guess < guess_number:
print("Too low...try a higher number")
else:
print("Ah...giving up so soon?")
break
else:

Challenge 1: Fix this: 3 tries login attempt!


1. Open a Python
Module
2. Copy and paste
the code on the
right into the
module
3. See if you can fix
the errors to get it
to work.
4. Remember to type
login() at the
prompt to run!

#this doesn't quite work. You'll notice that the tries, on each
go,
#stays at 1 (rather than counting up to 3). Can you fix it?
def login():
tries=0
while tries <1:
username="username1"
password="open123"
print('*********************************************')
print('Enter username')
answer1=input()
print('Enter password:')
answer2=input()
if answer1 == username and answer2 ==
password:
print("Access Granted")

function. In Python a function is defined with


the word: def (see below to call a function
and run the code)
def login():
username="username1"
print('Enter username')
answer1=input()
print('Enter password:')
if answer1 == username and
answer2 = password:
print("Access Granted")
else:
print("Sorry, Access
Denied")

Challenge 1: Solution
#A working solution - allowing a user to attempt login 3 times
def login():login()

The variable tries starts


at 1

tries=1
The While loop starts here. The stopping
while tries <4:
condition is: When tries is less than 4 (in other
username="username1"
words, stop the loop when the no. of tries
password="open123"
reaches 3)
print('*********************************************')
print('Enter username')
answer1=input()
print('Enter password:')
answer2=input()
if answer1 == username and answer2 == password:
print("Access Granted")
Incrementation: This tells the number of tries to
else:
keep going up by 1 for each loop.
print("Sorry, Access Denied")

Challenge 2: Get this counting from 1 to 10


1. Open a Python
Module
2. Copy and paste
the code on the
right.
3. The program
counts but you
need to change it
so that it goes
from 1 to 10.
4. Can you do it?

count = 3
while (count < 5):
print ('The count is:', count)
count = count + 1
print ("Good bye!")

Create a trace table to see whats going on!


count = 3
while (count < 5):
print ('The count is:',
count)
count = count + 1
print ("Good bye!)
OUTPUT

View slideshow to see the animations on this slide

1. First list all the variables and outputs you can


see in the program using columns.

Count

Output (Print)

The count is: 3

The count is: 4

The while loops condition is no


longer met (count <5) so it exits
the loop and stops there. Note
output!

Challenge 2: Solution
Challenge 2 Solution

count = 1
while (count < 11):
print ('The count is:', count)
count = count + 1
print ("Good bye!")

Introducing the Fibonacci sequence.


The Fibonacci sequence has fascinated scientists and
mathematicians for years.

It is a sequence that starts like this: Can you guess what comes
next?

1
3

Watch the following videos to find out more!


The mysterious Fibonacci sequence

1
/4VrcO6JaM
e
.b
u
t
u
o
/y
:/
s
p
htt
rM

Tlw7fNcO
/w
e
.b
u
t
u
o
/y
:/
s
http
-0

Notice the
pattern?
1+1 = 2
2+1 = 3
3+ 5 = 8
5+8 = 13
8+13 = ?

2
3

5
8
1
3 ?

Challenge 3: Fix the Fibonacci sequence!


Analyse the code below and think about why it is not producing the sequence correctly. You
only need to change TWO characters (a letter and a number) to get it to work! Use a trace table
to help you.

Note: To call this program,


enter Fib and a number of
your choice in the brackets.
The sequence should
execute up to that number.
e.g. (fib(60))

Challenge 3: Solution
Change this from 2 to 1

Change this
from a to b!

Task 2: Analyse the code line by line and


explain what it does.
Your explanation of the code here
?
?

Task 2: Analyse the code line by line and


explain what it does.
This defines the function fib. It can be called with any number n
Initialisation of variables: The variables a and b are assigned initial
(starting) values. A = 0 and b = 1
Start of While Loop. Condition is DO WHILE variable b is less than
the number n that you specified at the start
Output: Print b (first value will be 1) The end keyword
will print a string or whatever you specify after the
first variable. In this case, a space. You can read more
about this in the Python Doc:
http://www.python-course.eu/python3_print.php
Finally a is now assigned the value b. b is assigned
the value a+b.

The official Python Site (very useful!)


Make a note of it and check out the tutorial! You can find what youre looking for, in this
case, IF statements.

Useful Videos to watch on covered topics


Introduction to Iteration: Loops in programming

https://youtu.be/d7e48cYq7uc

Recommended video on Python WHILE Loops

https://youtu.be/xd_laXe17Ak

Suggested Project / HW / Research


Create a research information point on the Fibonacci sequence
What is the Fibonacci sequence?
What applications has it had in science and technology?
What are the different methods in which it can be coded (research and code!)
Extension: One method of coding the Fibonacci sequence involves recursion
what is recursion? How is it different from using a loop?
Compare and contrast the use of WHILE AND FOR LOOPS in Python
Give 3 examples of WHILE LOOPS in Python
Research For Loops (coming next) and give 3 examples of their use in Python
In which situations is it more advantageous to use a WHILE loop over a FOR?
Another type of loop is the Repeat.Until (or DoUntil). The stopping condition in
this loop is at the end. When is this more advantageous to use then the WHILE?

Useful links and additional reading


http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/index.html
http://www.pythonschool.net/basics/while-loops/
http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/whilestatements.html
http://www.pythonforbeginners.com/control-flow-2/python-for-and-while-loops

Vous aimerez peut-être aussi