SlideShare a Scribd company logo
www.teachingcomputing.com
For Loop
python programming
11 grade
All you need to know about FOR LOOPS
Overview
Information/Theory/Discuss
Task (Code provided)
Challenge (DIY!)
Extra reading
In this lesson you will …
 11.1.2.4 write program code using a For loop
 11.1.2.5 define a range of values for a loop
 11.1.2.6 debug a program
 11.4.3.2 solve applied problems from various
subject areas
Did you know?
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.
Guido van Rossum, the creator of Python
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 traditionally used when you have a piece of code which you want
to repeat n number of times. As an alternative, there is the WhileLoop,
however, while is used when a condition is to be met, or if you want a piece of
code to repeat forever, for example -
For loops are used when the number of iterations are known before hand.
The name for-loop comes
from the English word
“for”, which is used as the
keyword in most
languages. The term in
English dates to ALGOL 58
For Loops and game design …
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.
It would be hard to come across a programmed game that has not utilised a
for loop of some kind in its code.
The anatomy of a For Loop
for <variable> in <sequence>:
<statements>
else:
<statements>
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:
Task 1: Predict the output (using For Loops)
Predict the output, then code it yourself to see if you were right!
Both of these do the same thing. Note: 0 is the starting point.
Look out for FORMAT SPECIFIERS: The %d specifier refers specifically to a decimal (base 10) integer.
The %s specifier refers to a Python string.
Were your predictions right?
Answers:
This is the Fibonacci sequence!
Nested Loops
And now for a Nested Loop. This will break each word into its constituent letters
and print them out.
A Nested loop is basically a loop within a loop. You can have a for loop inside a
while loop or vice versa. Let’s start with something simple. Use a for loop to print
out the items in a list.
OUTPUT
OUTPUT
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!
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
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 aren’t met.
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 aren’t met.
OUTPUT
Note only 1,2,3,4 are printed from the range and once x = 5, the loop is exited!
OUTPUT?
Nothing! This is because the
loop finds ‘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
places = input("Enter Place:")
places_traveled.append(places)
print (("Here's a list of places you've been to: n"), places_traveled)
Challenge 3: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 using in this
Discussion: Is the universe Binary?
https://en.wikipedia.org/wiki/Digital_physics
You may find Wikipedia’s listing on digital universe possibilities an interesting read
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 is
therefore computable.
Some scientists say that the universe may in fact be a computer program.
Useful Videos to watch on covered topics
https://youtu.be/atMuFCpxnUQ https://youtu.be/9LgyKiq_hU0
What is the nature of the universe we live in? Recommended video on Python For Loops
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

More Related Content

Similar to ForLoops.pptx

Application development with Python - Desktop application
Application development with Python - Desktop applicationApplication development with Python - Desktop application
Application development with Python - Desktop application
Bao Long Nguyen Dang
 
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docxCMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
monicafrancis71118
 
Python for scientific computing
Python for scientific computingPython for scientific computing
Python for scientific computingGo Asgard
 
Loops in Python.pptx
Loops in Python.pptxLoops in Python.pptx
Lab 4 ,5 & 6 Submission (3) 14136_Mohsin Alvi.docx
Lab 4 ,5 & 6 Submission (3) 14136_Mohsin Alvi.docxLab 4 ,5 & 6 Submission (3) 14136_Mohsin Alvi.docx
Lab 4 ,5 & 6 Submission (3) 14136_Mohsin Alvi.docx
ABDULAHAD507571
 
Automation Testing theory notes.pptx
Automation Testing theory notes.pptxAutomation Testing theory notes.pptx
Automation Testing theory notes.pptx
NileshBorkar12
 
python introduction initial lecture unit1.pptx
python introduction initial lecture unit1.pptxpython introduction initial lecture unit1.pptx
python introduction initial lecture unit1.pptx
ChandraPrakash715640
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
RojaPriya
 
Control structures pyhton
Control structures  pyhtonControl structures  pyhton
Control structures pyhton
Prakash Jayaraman
 
python presentation
python presentationpython presentation
python presentation
VaibhavMawal
 
Python Introduction Week-1 Term-3.pptx
Python Introduction Week-1 Term-3.pptxPython Introduction Week-1 Term-3.pptx
Python Introduction Week-1 Term-3.pptx
Mohammad300758
 
python-160403194316.pdf
python-160403194316.pdfpython-160403194316.pdf
python-160403194316.pdf
gmadhu8
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
kavinilavuG
 
pythontraining-201jn026043638.pptx
pythontraining-201jn026043638.pptxpythontraining-201jn026043638.pptx
pythontraining-201jn026043638.pptx
RohitKumar639388
 
python into.pptx
python into.pptxpython into.pptx
python into.pptx
Punithavel Ramani
 
علم البيانات - Data Sience
علم البيانات - Data Sience علم البيانات - Data Sience
علم البيانات - Data Sience
App Ttrainers .com
 
Python Seminar PPT
Python Seminar PPTPython Seminar PPT
Python Seminar PPT
Shivam Gupta
 
Python
PythonPython
Python
Shivam Gupta
 
python.pdf
python.pdfpython.pdf
python.pdf
BurugollaRavi1
 

Similar to ForLoops.pptx (20)

Application development with Python - Desktop application
Application development with Python - Desktop applicationApplication development with Python - Desktop application
Application development with Python - Desktop application
 
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docxCMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
 
Python for scientific computing
Python for scientific computingPython for scientific computing
Python for scientific computing
 
Loops in Python.pptx
Loops in Python.pptxLoops in Python.pptx
Loops in Python.pptx
 
Lab 4 ,5 & 6 Submission (3) 14136_Mohsin Alvi.docx
Lab 4 ,5 & 6 Submission (3) 14136_Mohsin Alvi.docxLab 4 ,5 & 6 Submission (3) 14136_Mohsin Alvi.docx
Lab 4 ,5 & 6 Submission (3) 14136_Mohsin Alvi.docx
 
Automation Testing theory notes.pptx
Automation Testing theory notes.pptxAutomation Testing theory notes.pptx
Automation Testing theory notes.pptx
 
python introduction initial lecture unit1.pptx
python introduction initial lecture unit1.pptxpython introduction initial lecture unit1.pptx
python introduction initial lecture unit1.pptx
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
 
Control structures pyhton
Control structures  pyhtonControl structures  pyhton
Control structures pyhton
 
pyton Notes1
pyton Notes1pyton Notes1
pyton Notes1
 
python presentation
python presentationpython presentation
python presentation
 
Python Introduction Week-1 Term-3.pptx
Python Introduction Week-1 Term-3.pptxPython Introduction Week-1 Term-3.pptx
Python Introduction Week-1 Term-3.pptx
 
python-160403194316.pdf
python-160403194316.pdfpython-160403194316.pdf
python-160403194316.pdf
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
 
pythontraining-201jn026043638.pptx
pythontraining-201jn026043638.pptxpythontraining-201jn026043638.pptx
pythontraining-201jn026043638.pptx
 
python into.pptx
python into.pptxpython into.pptx
python into.pptx
 
علم البيانات - Data Sience
علم البيانات - Data Sience علم البيانات - Data Sience
علم البيانات - Data Sience
 
Python Seminar PPT
Python Seminar PPTPython Seminar PPT
Python Seminar PPT
 
Python
PythonPython
Python
 
python.pdf
python.pdfpython.pdf
python.pdf
 

Recently uploaded

The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
timhan337
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Atul Kumar Singh
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
EduSkills OECD
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 

Recently uploaded (20)

The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 

ForLoops.pptx

  • 1. www.teachingcomputing.com For Loop python programming 11 grade All you need to know about FOR LOOPS
  • 3. In this lesson you will …  11.1.2.4 write program code using a For loop  11.1.2.5 define a range of values for a loop  11.1.2.6 debug a program  11.4.3.2 solve applied problems from various subject areas
  • 4. Did you know? 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. Guido van Rossum, the creator of Python 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
  • 5. The difference between ‘While’ and ‘For’ For loops are traditionally used when you have a piece of code which you want to repeat n number of times. As an alternative, there is the WhileLoop, however, while is used when a condition is to be met, or if you want a piece of code to repeat forever, for example - For loops are used when the number of iterations are known before hand. The name for-loop comes from the English word “for”, which is used as the keyword in most languages. The term in English dates to ALGOL 58
  • 6. For Loops and game design … 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. It would be hard to come across a programmed game that has not utilised a for loop of some kind in its code.
  • 7. The anatomy of a For Loop for <variable> in <sequence>: <statements> else: <statements> 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:
  • 8. Task 1: Predict the output (using For Loops) Predict the output, then code it yourself to see if you were right! Both of these do the same thing. Note: 0 is the starting point. Look out for FORMAT SPECIFIERS: The %d specifier refers specifically to a decimal (base 10) integer. The %s specifier refers to a Python string.
  • 9. Were your predictions right? Answers: This is the Fibonacci sequence!
  • 10. Nested Loops And now for a Nested Loop. This will break each word into its constituent letters and print them out. A Nested loop is basically a loop within a loop. You can have a for loop inside a while loop or vice versa. Let’s start with something simple. Use a for loop to print out the items in a list. OUTPUT OUTPUT
  • 11. 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
  • 12. 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 ….
  • 13. The ‘Break’ statement – how it works! 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 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 aren’t met.
  • 14. 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 aren’t met. OUTPUT Note only 1,2,3,4 are printed from the range and once x = 5, the loop is exited! OUTPUT? Nothing! This is because the loop finds ‘1’ and breaks before it can do anything! ???????
  • 15. 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 places = input("Enter Place:") places_traveled.append(places) print (("Here's a list of places you've been to: n"), places_traveled)
  • 16. Challenge 3: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 using in this
  • 17. Discussion: Is the universe Binary? https://en.wikipedia.org/wiki/Digital_physics You may find Wikipedia’s listing on digital universe possibilities an interesting read 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 is therefore computable. Some scientists say that the universe may in fact be a computer program.
  • 18. Useful Videos to watch on covered topics https://youtu.be/atMuFCpxnUQ https://youtu.be/9LgyKiq_hU0 What is the nature of the universe we live in? Recommended video on Python For Loops
  • 19. 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

Editor's Notes

  1. Associated Resource: Python GUI Programming: See www.teachingcomputing.com (resources overview) for more information
  2. Associated Resource: Python GUI Programming: See www.teachingcomputing.com (resources overview) for more information
  3. Image source: http://www.peardeck.com
  4. Image(s) source: Wikipedia
  5. Image(s) source: cs.txstate.edu
  6. Source: http://www.codeproject.com/Articles/396959/Mario
  7. Teachers tip: To make this activity less dry, try and deliver it as a test/challenge – (who can do it first?). Get students to type the code in themselves and have the coded solutions ready. As an extension, students can try to write their own for loop based on the ones they have already seen.
  8. *Teachers can delete this slide if using it to test students in a lesson.
  9. Image source: www.funnyjunk.com
  10. Image source: www.funnyjunk.com
  11. Source: www.7-themes.com
  12. Image(s) source: Wikipedia