SlideShare a Scribd company logo
1 of 26
www.teachingcomputing.com
Mastering Programming in Python
Lesson 3(b)
All you need to know about FOR LOOPS
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
• Introduction to the language, SEQUENCE variables, create a Chat bot
• Introduction SELECTION (if else statements)
• Introducing ITERATION (While loops)
• Introducing For Loops
• Use of Functions/Modular Programming
• Introducing Lists /Operations/List comprehension
• Use of Dictionaries
• String Manipulation
• File Handling – Reading and writing to CSV Files
• Importing and Exporting Files
• Transversing, Enumeration, Zip Merging
• Recursion
• Practical Programming
• 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, and more …
Series Overview
*Please note that each lesson is not bound to a specific time (so it can be taken at your own pace)
Information/Theory/Discuss
Task (Code provided)
Challenge (DIY!)
Suggested Project/HW
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
#1 Predict the output: (Simple Loop)
x i Output
0 0
1 1
2 2
3
3
*View the slideshow if you want flying animations to help with clarity!
Start by listing your variables (in the order they come)
#2 Predict the output: (two ‘for’ loops!)
x i Output
0 0
1 1
2 2
3
*View the slideshow if you want flying animations to help with clarity!
j
0
1
2
4
5
6 6
#3 Predict the output: (Nested Loop!)
x i Output
0
*View the slideshow if you want flying animations to help with clarity!
j
*
*
Note the
indentation!
This second for
loop is nested
INSIDE the first
one!
0
1
2
1
2
3
0
1
2
0
1
2
0
1
2
4
5
6
7
8
9
10
11
12 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!
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)
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!
Were your predictions right?Answers:
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.
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’ didn’t have a
starting value, the
computer would throw
up an error later on! It is
also necessary to re-set
values at the start.
Above: allows for a running total of the numbers
entered by the user (new_number)
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
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!
 Write an essay (or create an informational power point) on ‘DO WE LIVE IN A
BINARY UNIVERSE?”
 What were Konrad Zuse’s 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?
Gottfried Leibniz Konrad Zuse
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

What's hot

Notes1
Notes1Notes1
Notes1hccit
 
PYTHON NOTES
PYTHON NOTESPYTHON NOTES
PYTHON NOTESNi
 
Intro to Python Programming Language
Intro to Python Programming LanguageIntro to Python Programming Language
Intro to Python Programming LanguageDipankar Achinta
 
Basic Concepts in Python
Basic Concepts in PythonBasic Concepts in Python
Basic Concepts in PythonSumit Satam
 
Python Programming Language
Python Programming LanguagePython Programming Language
Python Programming LanguageDr.YNM
 
Python - Introduction
Python - IntroductionPython - Introduction
Python - Introductionstn_tkiller
 
Python Seminar PPT
Python Seminar PPTPython Seminar PPT
Python Seminar PPTShivam Gupta
 
Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python Jaganadh Gopinadhan
 
Python-01| Fundamentals
Python-01| FundamentalsPython-01| Fundamentals
Python-01| FundamentalsMohd Sajjad
 
Python interview questions for experience
Python interview questions for experiencePython interview questions for experience
Python interview questions for experienceMYTHILIKRISHNAN4
 
Lesson 03 python statement, indentation and comments
Lesson 03   python statement, indentation and commentsLesson 03   python statement, indentation and comments
Lesson 03 python statement, indentation and commentsNilimesh Halder
 
Moving to Python 3
Moving to Python 3Moving to Python 3
Moving to Python 3Nick Efford
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python amiable_indian
 

What's hot (20)

Notes1
Notes1Notes1
Notes1
 
PYTHON NOTES
PYTHON NOTESPYTHON NOTES
PYTHON NOTES
 
Intro to Python Programming Language
Intro to Python Programming LanguageIntro to Python Programming Language
Intro to Python Programming Language
 
Basic Concepts in Python
Basic Concepts in PythonBasic Concepts in Python
Basic Concepts in Python
 
Python made easy
Python made easy Python made easy
Python made easy
 
Python Programming Language
Python Programming LanguagePython Programming Language
Python Programming Language
 
Python - Introduction
Python - IntroductionPython - Introduction
Python - Introduction
 
Python Workshop
Python WorkshopPython Workshop
Python Workshop
 
Python Seminar PPT
Python Seminar PPTPython Seminar PPT
Python Seminar PPT
 
Python
PythonPython
Python
 
Python Tutorial Part 1
Python Tutorial Part 1Python Tutorial Part 1
Python Tutorial Part 1
 
Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python
 
Python-01| Fundamentals
Python-01| FundamentalsPython-01| Fundamentals
Python-01| Fundamentals
 
Python interview questions for experience
Python interview questions for experiencePython interview questions for experience
Python interview questions for experience
 
Programming with Python
Programming with PythonProgramming with Python
Programming with Python
 
Lesson 03 python statement, indentation and comments
Lesson 03   python statement, indentation and commentsLesson 03   python statement, indentation and comments
Lesson 03 python statement, indentation and comments
 
Moving to Python 3
Moving to Python 3Moving to Python 3
Moving to Python 3
 
Python Presentation
Python PresentationPython Presentation
Python Presentation
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
 
Python basics
Python basicsPython basics
Python basics
 

Viewers also liked

Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesMatt Harrison
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonNowell Strite
 
Workshop on Programming in Python - day II
Workshop on Programming in Python - day IIWorkshop on Programming in Python - day II
Workshop on Programming in Python - day IISatyaki Sikdar
 
Introduction to python for Beginners
Introduction to python for Beginners Introduction to python for Beginners
Introduction to python for Beginners Sujith Kumar
 
Connect all your customers on one multichannel platform!
Connect all your customers on one multichannel platform!Connect all your customers on one multichannel platform!
Connect all your customers on one multichannel platform!Slawomir Kluczewski
 
20 C programs
20 C programs20 C programs
20 C programsnavjoth
 
Python in raspberry pi
Python in raspberry piPython in raspberry pi
Python in raspberry piSudar Muthu
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial javaTpoint s
 
Conditional Loops Python
Conditional Loops PythonConditional Loops Python
Conditional Loops Pythonprimeteacher32
 
Socket Programming In Python
Socket Programming In PythonSocket Programming In Python
Socket Programming In Pythondidip
 
Cloud Computing to Internet of Things
Cloud Computing to Internet of ThingsCloud Computing to Internet of Things
Cloud Computing to Internet of ThingsHermesDDS
 
Got Python I/O: IoT Develoment in Python via GPIO
Got Python I/O: IoT Develoment in Python via GPIOGot Python I/O: IoT Develoment in Python via GPIO
Got Python I/O: IoT Develoment in Python via GPIOAdam Englander
 
Internet of Things for Libraries
Internet of Things for LibrariesInternet of Things for Libraries
Internet of Things for LibrariesNicole Baratta
 
C programs
C programsC programs
C programsMinu S
 
Python programming lab2
Python programming lab2Python programming lab2
Python programming lab2profbnk
 
Python 3000
Python 3000Python 3000
Python 3000Bob Chao
 

Viewers also liked (20)

Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Workshop on Programming in Python - day II
Workshop on Programming in Python - day IIWorkshop on Programming in Python - day II
Workshop on Programming in Python - day II
 
Introduction to python for Beginners
Introduction to python for Beginners Introduction to python for Beginners
Introduction to python for Beginners
 
Connect all your customers on one multichannel platform!
Connect all your customers on one multichannel platform!Connect all your customers on one multichannel platform!
Connect all your customers on one multichannel platform!
 
20 C programs
20 C programs20 C programs
20 C programs
 
Computer Logic
Computer LogicComputer Logic
Computer Logic
 
Python in raspberry pi
Python in raspberry piPython in raspberry pi
Python in raspberry pi
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
 
Conditional Loops Python
Conditional Loops PythonConditional Loops Python
Conditional Loops Python
 
Loops in c
Loops in cLoops in c
Loops in c
 
Socket Programming In Python
Socket Programming In PythonSocket Programming In Python
Socket Programming In Python
 
Cloud Computing to Internet of Things
Cloud Computing to Internet of ThingsCloud Computing to Internet of Things
Cloud Computing to Internet of Things
 
Got Python I/O: IoT Develoment in Python via GPIO
Got Python I/O: IoT Develoment in Python via GPIOGot Python I/O: IoT Develoment in Python via GPIO
Got Python I/O: IoT Develoment in Python via GPIO
 
CS2309 JAVA LAB MANUAL
CS2309 JAVA LAB MANUALCS2309 JAVA LAB MANUAL
CS2309 JAVA LAB MANUAL
 
Internet of Things for Libraries
Internet of Things for LibrariesInternet of Things for Libraries
Internet of Things for Libraries
 
C programs
C programsC programs
C programs
 
Python programming lab2
Python programming lab2Python programming lab2
Python programming lab2
 
Python 3000
Python 3000Python 3000
Python 3000
 
Cc code cards
Cc code cardsCc code cards
Cc code cards
 

Similar to Mastering Python lesson3b_for_loops

python introduction initial lecture unit1.pptx
python introduction initial lecture unit1.pptxpython introduction initial lecture unit1.pptx
python introduction initial lecture unit1.pptxChandraPrakash715640
 
Python breakdown-workbook
Python breakdown-workbookPython breakdown-workbook
Python breakdown-workbookHARUN PEHLIVAN
 
python-160403194316.pdf
python-160403194316.pdfpython-160403194316.pdf
python-160403194316.pdfgmadhu8
 
علم البيانات - Data Sience
علم البيانات - Data Sience علم البيانات - Data Sience
علم البيانات - Data Sience App Ttrainers .com
 
python-online&offline-training-in-kphb-hyderabad (1) (1).pdf
python-online&offline-training-in-kphb-hyderabad (1) (1).pdfpython-online&offline-training-in-kphb-hyderabad (1) (1).pdf
python-online&offline-training-in-kphb-hyderabad (1) (1).pdfKosmikTech1
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answersRojaPriya
 
Basics of Programming - A Review Guide
Basics of Programming - A Review GuideBasics of Programming - A Review Guide
Basics of Programming - A Review GuideBenjamin Kissinger
 
pythontraining-201jn026043638.pptx
pythontraining-201jn026043638.pptxpythontraining-201jn026043638.pptx
pythontraining-201jn026043638.pptxRohitKumar639388
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answerskavinilavuG
 
Python for scientific computing
Python for scientific computingPython for scientific computing
Python for scientific computingGo Asgard
 
Python (3).pdf
Python (3).pdfPython (3).pdf
Python (3).pdfsamiwaris2
 
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.pptxMohammad300758
 
Help with Pyhon Programming Homework
Help with Pyhon Programming HomeworkHelp with Pyhon Programming Homework
Help with Pyhon Programming HomeworkHelpmeinhomework
 
Mastering Python : 100+ Solved and Commented Exercises to Accelerate Your Lea...
Mastering Python : 100+ Solved and Commented Exercises to Accelerate Your Lea...Mastering Python : 100+ Solved and Commented Exercises to Accelerate Your Lea...
Mastering Python : 100+ Solved and Commented Exercises to Accelerate Your Lea...Lucky Gods
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to pythonmckennadglyn
 

Similar to Mastering Python lesson3b_for_loops (20)

ForLoops.pptx
ForLoops.pptxForLoops.pptx
ForLoops.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 into.pptx
python into.pptxpython into.pptx
python into.pptx
 
Python breakdown-workbook
Python breakdown-workbookPython breakdown-workbook
Python breakdown-workbook
 
python-160403194316.pdf
python-160403194316.pdfpython-160403194316.pdf
python-160403194316.pdf
 
python.pdf
python.pdfpython.pdf
python.pdf
 
Python
PythonPython
Python
 
علم البيانات - Data Sience
علم البيانات - Data Sience علم البيانات - Data Sience
علم البيانات - Data Sience
 
python-online&offline-training-in-kphb-hyderabad (1) (1).pdf
python-online&offline-training-in-kphb-hyderabad (1) (1).pdfpython-online&offline-training-in-kphb-hyderabad (1) (1).pdf
python-online&offline-training-in-kphb-hyderabad (1) (1).pdf
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
 
Basics of Programming - A Review Guide
Basics of Programming - A Review GuideBasics of Programming - A Review Guide
Basics of Programming - A Review Guide
 
pythontraining-201jn026043638.pptx
pythontraining-201jn026043638.pptxpythontraining-201jn026043638.pptx
pythontraining-201jn026043638.pptx
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
 
ACM init() Spring 2015 Day 1
ACM init() Spring 2015 Day 1ACM init() Spring 2015 Day 1
ACM init() Spring 2015 Day 1
 
Python for scientific computing
Python for scientific computingPython for scientific computing
Python for scientific computing
 
Python (3).pdf
Python (3).pdfPython (3).pdf
Python (3).pdf
 
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
 
Help with Pyhon Programming Homework
Help with Pyhon Programming HomeworkHelp with Pyhon Programming Homework
Help with Pyhon Programming Homework
 
Mastering Python : 100+ Solved and Commented Exercises to Accelerate Your Lea...
Mastering Python : 100+ Solved and Commented Exercises to Accelerate Your Lea...Mastering Python : 100+ Solved and Commented Exercises to Accelerate Your Lea...
Mastering Python : 100+ Solved and Commented Exercises to Accelerate Your Lea...
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 

Recently uploaded

Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxPooja Bhuva
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17Celine George
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxmarlenawright1
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxJisc
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...Amil baba
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxPooja Bhuva
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 

Recently uploaded (20)

Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 

Mastering Python lesson3b_for_loops

  • 1. www.teachingcomputing.com Mastering Programming in Python Lesson 3(b) All you need to know about FOR LOOPS
  • 2. 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
  • 3. • Introduction to the language, SEQUENCE variables, create a Chat bot • Introduction SELECTION (if else statements) • Introducing ITERATION (While loops) • Introducing For Loops • Use of Functions/Modular Programming • Introducing Lists /Operations/List comprehension • Use of Dictionaries • String Manipulation • File Handling – Reading and writing to CSV Files • Importing and Exporting Files • Transversing, Enumeration, Zip Merging • Recursion • Practical Programming • 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, and more … Series Overview *Please note that each lesson is not bound to a specific time (so it can be taken at your own pace) Information/Theory/Discuss Task (Code provided) Challenge (DIY!) Suggested Project/HW
  • 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. #1 Predict the output: (Simple Loop) x i Output 0 0 1 1 2 2 3 3 *View the slideshow if you want flying animations to help with clarity! Start by listing your variables (in the order they come)
  • 12. #2 Predict the output: (two ‘for’ loops!) x i Output 0 0 1 1 2 2 3 *View the slideshow if you want flying animations to help with clarity! j 0 1 2 4 5 6 6
  • 13. #3 Predict the output: (Nested Loop!) x i Output 0 *View the slideshow if you want flying animations to help with clarity! j * * Note the indentation! This second for loop is nested INSIDE the first one! 0 1 2 1 2 3 0 1 2 0 1 2 0 1 2 4 5 6 7 8 9 10 11 12 12
  • 14. 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
  • 15. 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 ….
  • 16. 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.
  • 17. 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! ???????
  • 18. 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)
  • 19. 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!
  • 20. Were your predictions right?Answers:
  • 21. 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
  • 22. 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.
  • 23. 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’ didn’t have a starting value, the computer would throw up an error later on! It is also necessary to re-set values at the start. Above: allows for a running total of the numbers entered by the user (new_number)
  • 24. 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
  • 25. 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!  Write an essay (or create an informational power point) on ‘DO WE LIVE IN A BINARY UNIVERSE?”  What were Konrad Zuse’s 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? Gottfried Leibniz Konrad Zuse
  • 26. 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. Image source: http://www.peardeck.com
  3. Associated Resource: Python GUI Programming: See www.teachingcomputing.com (resources overview) for more information
  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. 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.
  11. *Teachers can delete this slide if using it to test students in a lesson.
  12. Source: www.7-themes.com
  13. Source: www.7-themes.com
  14. Image(s) source: Wikipedia
  15. Image(s) source: Wikipedia