Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 27

Mastering Programming in Python

Lesson 4

All you need to know about FOR LOOPS

The full series and 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 loops, specifically the FOR LOOP


Predict the output (For Loop Task)
Adapt and change code involving For Loops
Compare while and for loops.
Use the break statement and see how it works
Learn about Nested Loops
Learn about the need for initialisation (set starting value)
Create your own For Loops
Create the beginnings of an Arithmetic quiz using a
random function and for loops
Big ideas: Is the universe digital? A program?
Introducing Gottfried Leibniz and Konrad Zuse

*For this series we


assume students
know how to open,
save and run a
python module.
Version: Python 3

Did you know?

Guido van Rossum, the creator of


Python

Guido van Rossum, the guy on the right, created python!


He is a Dutch computer programmer and completed his
degree in the university of Amsterdam
He was employed by Google from 2005 until December
2012, where much of his time was spent developing the
Python language. In 2013, Van Rossum started working
for Dropbox.
Python is intended to be a highly readable language. It
has a relatively uncluttered visual layout, frequently using
English keywords where other languages use punctuation.
An important goal of the Python developers is making Python fun to use. This is
reflected in the origin of the name which comes from Monty Python

The difference between While and For


For loops are used when the number of iterations are known
before hand.
Forloops are traditionally used when you have a piece of code
which you want to repeatnnumber of times. As an alternative,
there is theWhileLoop, however,whileis used when a condition
is to be met, or if you want a piece of code to repeat forever,
for example The name for-loop
comes from the
English word for,
which is used as the
keyword in most
languages. The term

For Loops and game design


It would be hard to come across a programmed game that has
not utilised a for loop of some kind in its code.
Take, for example, the game Super
Mario. For loops can be used to
create a timed interval recall loop for
each animation. See if you can spot
the for loop in the code below.

The anatomy of a For Loop


The For Loop can step through the items in any
ordered sequence list, i.e. string, lists, tuples, the
keys of dictionaries and other iterables. It starts
with the keyword "for" followed by an arbitrary
variable name. This will hold the values of the
following sequence object, which is stepped
through. Generally, the syntax looks like this:

for <variable> in <sequence>:


<statements>
else:
<statements>

Task 1: Predict the output (using For Loops)


Predict the output, then code it yourself to see if you
were right!
Look out for FORMAT SPECIFIERS: The%dspecifier refers specifically to a
decimal (base 10) integer. The%sspecifier refers to a Python string.

Both of these do the same thing. Note: 0 is the


starting point.

Answers
:

Were your predictions right?


This is the Fibonacci
sequence!

Nested Loops
A Nested loop is basically a loop within a loop. You can have a for
loop inside a while loop or vice versa. Lets start with something
simple. Use a for loop to print out the items in a list.

OUTPU
T
And now for a Nested Loop. This will break each word into its
constituent letters and print them out.

OUTPU
T

*View the slideshow if you want flying animations to help with cl

#1 Predict the output: (Simple Loop)

Start by listing your variables (in the order they come)


x

Output

3
3

*View the slideshow if you want flying animations to help with cl

#2 Predict the output: (two for loops!)


x

Output

3
4

*View the slideshow if you want flying animations to help with cl

#3 Predict the output: (Nested Loop!)


x
*

Note the
indentation!
This second for
loop is nested
INSIDE the first
one!

0
1
2
3
4
5
6

i
0
1
2

Output

0
1
2

7
8
9

0
1
2

10
11
12

0
1
2

12

Challenge 1: 3 and 4 times table up to 10


This bit of code produces the times tables for the numbers 1 and
2 (and only up to 5). Can you change it to produce the following?
(3 and 4 times table up to 10)
1. Type in the code below (nested loop
used)

2. Run it to see what it does


3. Now try and change the values in the
program to get it to do what is required.
4. Once done, play around with these values
and get it to produce more timestables!
You could go all the way up to 100!

Desired output

Solution1: 3 and 4 times table up to 10


The key is to understand the way the range works in Python.
Change the numbers to the following and it should work! Now
you can experiment with doing more!
Output

Change the above to .

The Break statement how it works!


Having no way out of a situation is never a good thing! In python
programming, you can use the Break statement to exit a loop
say for instance the conditions of the loop arent met.
found = False # initial assumption
for value in values_to_check() :
if
is_what_im_looking_for(value) :
found = True
break
#end if
#end for
# ... found is True on success,
False on failure

Note how break provides an early exit


Having no way out of a situation is never a good thing! In python
programming, you can use the Break statement to exit a loop say for
instance the conditions of the loop arent met.

OUTPU
T
Note only 1,2,3,4 are printed from the range and once x = 5, the loop is
exited!
Nothing!
???????
This is
because the loop finds
OUTPUT?
1 and breaks before it
can do anything!

Challenge 2: Extend the code and get


someone to try out your program!
1. Copy the code on the right
and analyse how it works
(notice use of user input, lists
and for loops)
2. Extend the program to:
a) Ask the user how many more
holidays they are planning
for the coming year(s)
b) Allow them to enter the
places they would like to visit
c) Append these new values to
the list.
d) Print the new list.
e) If they enter a number over
10 or zero, exit the loop.

print ("**********Hello, welcome to the


program***********")
print ("This program will ask you to enter the names of
places you've been to")
print ("Before we get started, please enter the number of
places you want to enter")
number = int(input("How many holidays have you had this
year?: "))
print ("Thank you!")
print ("We'll now ask you to enter all the places you've
traveled to: ")
places_traveled = [] #Empty list created to hold entered
values
for i in range(number): #range(number) used because we
want to limit number of inputs to user choice

Task 2: Predict the output (using For Loops)


Predict the output, then code it yourself to see if you
were right!

Counting by numbers other than 1 (hint:


in this case 2)

Using incrementation (i+1) to achieve


something ..

You can also COUNT DOWN (as opposed


to counting up!)

Printing number out of a list is also a


useful thing to do!

Answers
:

Were your predictions right?

Challenge 3. Create a running total for the


number of merits achieved by a student.
1. Copy the code on the right
and analyse how it works
(notice use of random
function and for loops)
2.

Extend the program to:

totalmerits= 0
for i in range(5):
name = str(input("Enter
Student Name from the 'Red'
House: "))
new_number = int(input("Enter
a number: " ))
totalmerits += new_number

.allow the user to say which


house the student is in, and then
award merits for that house. Total
the merits for that house.

print("The total number of merits


for Red House today is: ",
totalmerits)

Challenge 4:The beginnings of an Arithmetic


Quiz Program. Can you extend it?
1. Copy the code on the right
and analyse how it works
(notice use of random function
and for loops)
2. Extend the program to:
a) Create more questions (what
would you need to change to
do this?)
b) Add a division operator to the
mix so that the questions also
extend to division.
c) Gifted and Talented: What
else could you add to make
this program more interesting?
How about a score variable
that increments each time an
answer is correct?

#------------------------------------------------------------------------------# Name:
Maths Quiz
# Purpose: Tutorial
# Author:
teachingcomputing.com
# Created:
23/02/2016
# Copyright: (c) teachingcomputing.com 2016
#------------------------------------------------------------------------------import random
#identifying the variables we will be using
score=0
answer=0
operators=("x", "+", "-")
#Randomly generate the numbers and operators we will be

Discussion: Is the universe Binary?


You may find Wikipedias listing on digital universe possibilities an
interesting
read
https://en.wikipedia.org/wiki/Digital_physics
In physics and
cosmology, digital
physics is a
collection of
theoretical
perspectives based
on the premise that
the universe is, at
heart, describable
by information and
Some scientists say that the universe may in fact be a computer
is therefore

Initialisation: Variables must have starting values


Total = 0 (below) is setting the variable Total to zero at the start of
the program!
The process of
creating a variable
and giving it a
starting value is
called initialisation.
If total didnt have
a starting value,
the computer
would throw up an
error later on! It is

Above: allows for a running total of the


numbers entered by the user

Useful Videos to watch on covered topics


What is the nature of the universe we live in?

https://youtu.be/atMuFCpxnUQ

Recommended video on Python For Loops

https://youtu.be/9LgyKiq_hU0

Suggested Project / HW / Research


Create a research information point on Gottfried Leibniz
Basic facts about him
Achievements
His interpretation and understanding of Binary
How Binary plays a role in computers today!
Gottfried Leibniz

Konrad Zuse

Write an essay (or create an informational power point) on DO WE LIVE IN A


BINARY UNIVERSE?
What were Konrad Zuses views on a Binary/ digital universe
Charles Babbage claimed that miracles were the master programmer at work
do you agree?
If there is a God (higher power) might he be a programmer?
What arguments (for and against) a Binary universe can you present?

Useful links and additional reading


https://wiki.python.org/moin/ForLoop
http://www.tutorialspoint.com/python/python_for_loop.htm
http://www.learnpython.org/en/Loops
https://en.wikipedia.org/wiki/Konrad_Zuse
http://www.victorianweb.org/science/science_texts/bridgewater/intro.htm

You might also like