SlideShare a Scribd company logo
… loops…
… loops …
… loops …
… loops …
… loops …
The plan!
Basics: data types (and operations & calculations)
Basics: conditionals & iteration (+ recap)
Basics: lists, tuples, dictionaries
Basics: writing functions
Reading & writing files: opening, parsing & formats
Working with numbers: numpy & scipy
Making plots: matplotlib & pylab
… if you guys want more after all of that …
Writing better code: functions, pep8, classes
Working with numbers: Numpy & Scipy (advanced)
Other modules: Pandas & Scikit-learn
Interactive notebooks: ipython & jupyter
Advanced topics: virtual environments & version control
recap: ints, floats, strings & booleans
ints & floats:
+ addition
- subtraction
* multiplication
/ division
** exponent
% modulus
variable names:
… no spaces
… cannot begin with number: 1, 2 …
… cannot contain ?$@# (except _)
… cannot be a “built-in” name: and, or, int,
float, str, char, exec, file, open, object, print,
quit… (approx. 80 reserved names)
comparisons:
= = equal
! = not equal
> greater than
>= greater or equal than
< less than
<= less or equal than
basic data types:
integer, float, string, boolean
converting types :
int(), float(), str(), type()
the linux command line:
ls : list files & folders
cd directory : change directory
to run a python file:
python filename.py
user input:
a = raw_input(“write stuff:”)
strings:
+ concatenate
* copy
printing:
print “literal text”, var1, var2, “more text”
recap: if - else …
# basic “if - else” block
# indentation matters!!!
if boolean :
the “True” code goes here
else:
the “False” code goes here
# basic “if - else” block
if chairs < lions :
print “Run away!”
else:
print “You are OK!”
if chairs < lions :
print “There are”, lions, “lions.”
print “Run away!”
else:
print “You are OK”
print “That’s all for now folks!”
Indentation IS the logic of
your code!
non-logical and uneven
indentation makes python
angry
The first line at the same level as the “if” begins
the rest of the code (or program)
the “else” goes at the
same level as the “if”
(because they belong
together)
# “if - elif - else”
# blocks are tested in order
# only the first True “if” or “elif” is handled
if (boolean and/or boolean…) :
the “True” code goes here
elif (boolean and/or boolean…) :
next “True” code goes here
else:
the “False” code goes here
recap: if - else …
# “if - elif - else”
if chairs < lions :
print “Run away!”
elif chairs == lions ::
print “You got lucky this time.”
print “Buy more chairs!”
else:
print “Run away!”
# “if - elif - else”
# blocks are tested in order
# only the first True “if” or “elif” is handled
if (boolean and/or boolean…) :
the “True” code goes here
elif (boolean and/or boolean…) :
next “True” code goes here
else:
the “False” code goes here
recap: if - else …
# “if - elif - else”
if chairs < lions :
print “Run away!”
elif chairs == lions ::
print “You got lucky this time.”
print “Buy more chairs!”
else:
print “Run away!”
# “if...”
if chairs < lions :
print “Run away!”
elif chairs == lions ::
print “Buy chairs tomorrow!”
print “Program has finished!”
the “else” is not
required. Sometimes
there is just “nothing
else” to do :)
recap: if - else …
# combinatorial logic
if (boolean and/or boolean…) :
the “True” code goes here
else:
the “False” code goes here
# combinatorial logic
if (traps > bears) and (chairs > lions):
print “your are OK”
else:
print “Run away!”
recap: if - else …
# combinatorial logic
if (boolean and/or boolean…) :
the “True” code goes here
else:
the “False” code goes here
# combinatorial logic
if (traps > bears) and (chairs > lions):
print “your are OK”
else:
print “Run away!”
# nested if
if boolean:
if boolean:
“True True” code here
else:
“True False” code here
else:
“False” code here
# nested if
if lions > 0:
if chairs < lions :
print “Run away”
else:
print “You are OK”
else:
print “There are no lions”
“if else” exercises
- Write a script that asks the user 3 times to insert a single digit number. These will
represent the digit for Hundreds, Tens and Unit/Single (of a three digit number).
The script should output:
- Whether the number is larger than 500
- The number reversed
- Whether the reversed number is larger than 500
- Whether the number is a ‘palindrome’
- Write a scripts that asks the user for a number (between 0 and 999), and tells the
user whether:
- The number is larger than 100
- The number is even
- Lastly: If the number is larger than 200, but ONLY if the number is even (otherwise it prints
nothing)
loops and iteration
… for all numbers between 100 and 500…
… for each row in a table …
… for each image in collection of files …
… for each pixel in an image …
… while the total number is less than 1200 …
… until you find the first value bigger than 500 …
NOTE: this is c++ , not python ;)
the almighty “for … in … range”
---- file contents ----
# iterating over a range of numbers is VERY common
for i in range(10):
print i
# less trivial: 2 ** the first 10 numbers
for i in range(10):
print “2 to the power”, i, “is:”, 2 ** i
# optional parameters to “range”
for x in range(5, 10):
print x
for x in range(5, 10, 2):
print x
# going backwards…
for x in range(20, 15, -1):
print x
# the basic “for - in - range” loop
for x in range(stop):
code to repeat goes here…
again, indentation is
everything in python!
# the basic “for - in - range” loop
# “start” and “step” are optional
for x in range(start, stop, step):
code to repeat goes here…
0 → stop - 1
the almighty “for … in … range”
# sum of all numbers < 100
total = 0
for i in range(100):
total = total + i
print “The total is:”, total
# show all even numbers
# between 100 and 200
for i in range(100, 200):
if i % 2 == 0:
print i, “is even.”
# another way...
for i in range(100, 200, 2):
print i, “is even.”
# the basic “for - in - range” loop
for x in range(stop):
code to repeat goes here…
again, indentation is
everything in python!
# the basic “for - in - range” loop
# “start” and “step” are optional
for x in range(start, stop, step):
code to repeat goes here…
0 → stop - 1
the “while loop”
---- file contents ----
# adding numbers, until we reach 100
total = 0
while total <= 100:
n = int(raw_input(“Please write a number:”))
total = total + n
print “The total exceeded 100. It is:”, total
# adding numbers, until we reach 100
user_input = “”
while user_input != “stop”:
user_input = raw_input(“Type ‘stop’ to stop:”)
# the basic “while ” loop
while boolean:
code goes here
again, indentation!
NEVER use while loops!
okay… not “never”, but a “for loop” is
almost always better!
okay, some more exercises
Basic practice:
- Write a script that asks the user for two numbers and calculates:
- The sum of all numbers between the two.
- Write a script that asks the user for a single number and calculates:
- The sum of all even numbers between 0 and that number.
A little more complex:
- Write a script that asks the user for a single number and calculates whether or not
the number is prime.
- Write a script that asks the user for a single number and finds all prime numbers
less than that number.
Let’s write the following variants of the lion/chair/hungry program. They start as
above, but:
- If the ‘user’ does not write ‘yes’ or ‘no’ when answering ‘hungry?’, keeps on asking
them for some useful information.
Back to lions and bears
# the beginning of the lion / hungry program from last week…
chairs = int(raw_input(“How many chairs do you have?:”))
lions = int(raw_input(“How many lions are there?:”))
hungry = raw_input(“Are the lions hungry? (yes/no)?:”)
… etc…

More Related Content

PDF
Class 3: if/else
ODP
Introduction to Python - Training for Kids
PDF
Class 2: Welcome part 2
PDF
Class 5: If, while & lists
PDF
Python- strings
PPTX
PDF
basic of desicion control statement in python
PPT
Introduction to Python Language and Data Types
Class 3: if/else
Introduction to Python - Training for Kids
Class 2: Welcome part 2
Class 5: If, while & lists
Python- strings
basic of desicion control statement in python
Introduction to Python Language and Data Types

What's hot (18)

PPTX
Learn python in 20 minutes
PDF
Python
ODP
Python quickstart for programmers: Python Kung Fu
PDF
Lesson1 python an introduction
PDF
How to avoid Go gotchas - Ivan Daniluk - Codemotion Milan 2016
PDF
Common mistakes in C programming
PPT
Python легко и просто. Красиво решаем повседневные задачи
PPTX
C# overview part 1
PDF
Introduction to Python (part 1/2)
PPTX
Python
PDF
Introduction to Python Programming | InsideAIML
PDF
Python basic
PPT
C Tutorials
PPT
Chapter 3 malik
ODP
An Intro to Python in 30 minutes
PPTX
Python language data types
Learn python in 20 minutes
Python
Python quickstart for programmers: Python Kung Fu
Lesson1 python an introduction
How to avoid Go gotchas - Ivan Daniluk - Codemotion Milan 2016
Common mistakes in C programming
Python легко и просто. Красиво решаем повседневные задачи
C# overview part 1
Introduction to Python (part 1/2)
Python
Introduction to Python Programming | InsideAIML
Python basic
C Tutorials
Chapter 3 malik
An Intro to Python in 30 minutes
Python language data types
Ad

Viewers also liked (12)

PDF
Class 7a: Functions
PDF
Class 6: Lists & dictionaries
PDF
Heimo&Jolkkonen
PDF
Class 1: Welcome to programming
PDF
Class 7b: Files & File I/O
PDF
Class 8a: Modules and imports
PPTX
HDPE Pipe
PDF
Intelligenza creativa
PPTX
PR for FITBIT
DOCX
RESUME Jitendra Dixit - Copy
PPTX
문플 경진대회
PPTX
Renaissance
Class 7a: Functions
Class 6: Lists & dictionaries
Heimo&Jolkkonen
Class 1: Welcome to programming
Class 7b: Files & File I/O
Class 8a: Modules and imports
HDPE Pipe
Intelligenza creativa
PR for FITBIT
RESUME Jitendra Dixit - Copy
문플 경진대회
Renaissance
Ad

Similar to Class 4: For and while (20)

PPTX
industry coding practice unit-2 ppt.pptx
PPTX
Programming with python
PPTX
Lecture on Fundamentals of Python Programming-2
PPTX
module 3 BTECH FIRST YEAR ATP APJ KTU PYTHON
PDF
Pythonintro
PDF
Python for scientific computing
PPT
python fundamental for beginner course .ppt
PPT
Learn python
PPTX
Exploring Control Flow: Harnessing While Loops in Python
PPTX
Python 101: Python for Absolute Beginners (PyTexas 2014)
DOCX
Python Math Concepts Book
PDF
02 Control Structures - Loops & Conditions
PPTX
CoderDojo: Intermediate Python programming course
PPT
Computation Chapter 4
PPTX
Keep it Stupidly Simple Introduce Python
PPTX
This is all about control flow in python intruducing the Break and Continue.pptx
PPTX
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
PDF
2 Python Basics II meeting 2 tunghai university pdf
PDF
Python-Cheat-Sheet.pdf
PPTX
Python Workshop - Learn Python the Hard Way
industry coding practice unit-2 ppt.pptx
Programming with python
Lecture on Fundamentals of Python Programming-2
module 3 BTECH FIRST YEAR ATP APJ KTU PYTHON
Pythonintro
Python for scientific computing
python fundamental for beginner course .ppt
Learn python
Exploring Control Flow: Harnessing While Loops in Python
Python 101: Python for Absolute Beginners (PyTexas 2014)
Python Math Concepts Book
02 Control Structures - Loops & Conditions
CoderDojo: Intermediate Python programming course
Computation Chapter 4
Keep it Stupidly Simple Introduce Python
This is all about control flow in python intruducing the Break and Continue.pptx
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
2 Python Basics II meeting 2 tunghai university pdf
Python-Cheat-Sheet.pdf
Python Workshop - Learn Python the Hard Way

Recently uploaded (20)

PDF
. Radiology Case Scenariosssssssssssssss
PDF
IFIT3 RNA-binding activity primores influenza A viruz infection and translati...
PPTX
Vitamins & Minerals: Complete Guide to Functions, Food Sources, Deficiency Si...
PDF
Phytochemical Investigation of Miliusa longipes.pdf
PDF
VARICELLA VACCINATION: A POTENTIAL STRATEGY FOR PREVENTING MULTIPLE SCLEROSIS
PPTX
INTRODUCTION TO EVS | Concept of sustainability
PDF
ELS_Q1_Module-11_Formation-of-Rock-Layers_v2.pdf
PPTX
G5Q1W8 PPT SCIENCE.pptx 2025-2026 GRADE 5
PDF
SEHH2274 Organic Chemistry Notes 1 Structure and Bonding.pdf
PDF
Cosmic Outliers: Low-spin Halos Explain the Abundance, Compactness, and Redsh...
PPTX
Microbiology with diagram medical studies .pptx
PPTX
cpcsea ppt.pptxssssssssssssssjjdjdndndddd
DOCX
Q1_LE_Mathematics 8_Lesson 5_Week 5.docx
PPTX
neck nodes and dissection types and lymph nodes levels
PPTX
2Systematics of Living Organisms t-.pptx
PPT
POSITIONING IN OPERATION THEATRE ROOM.ppt
PPTX
2. Earth - The Living Planet Module 2ELS
PDF
lecture 2026 of Sjogren's syndrome l .pdf
PDF
HPLC-PPT.docx high performance liquid chromatography
PDF
AlphaEarth Foundations and the Satellite Embedding dataset
. Radiology Case Scenariosssssssssssssss
IFIT3 RNA-binding activity primores influenza A viruz infection and translati...
Vitamins & Minerals: Complete Guide to Functions, Food Sources, Deficiency Si...
Phytochemical Investigation of Miliusa longipes.pdf
VARICELLA VACCINATION: A POTENTIAL STRATEGY FOR PREVENTING MULTIPLE SCLEROSIS
INTRODUCTION TO EVS | Concept of sustainability
ELS_Q1_Module-11_Formation-of-Rock-Layers_v2.pdf
G5Q1W8 PPT SCIENCE.pptx 2025-2026 GRADE 5
SEHH2274 Organic Chemistry Notes 1 Structure and Bonding.pdf
Cosmic Outliers: Low-spin Halos Explain the Abundance, Compactness, and Redsh...
Microbiology with diagram medical studies .pptx
cpcsea ppt.pptxssssssssssssssjjdjdndndddd
Q1_LE_Mathematics 8_Lesson 5_Week 5.docx
neck nodes and dissection types and lymph nodes levels
2Systematics of Living Organisms t-.pptx
POSITIONING IN OPERATION THEATRE ROOM.ppt
2. Earth - The Living Planet Module 2ELS
lecture 2026 of Sjogren's syndrome l .pdf
HPLC-PPT.docx high performance liquid chromatography
AlphaEarth Foundations and the Satellite Embedding dataset

Class 4: For and while

  • 1. … loops… … loops … … loops … … loops … … loops …
  • 2. The plan! Basics: data types (and operations & calculations) Basics: conditionals & iteration (+ recap) Basics: lists, tuples, dictionaries Basics: writing functions Reading & writing files: opening, parsing & formats Working with numbers: numpy & scipy Making plots: matplotlib & pylab … if you guys want more after all of that … Writing better code: functions, pep8, classes Working with numbers: Numpy & Scipy (advanced) Other modules: Pandas & Scikit-learn Interactive notebooks: ipython & jupyter Advanced topics: virtual environments & version control
  • 3. recap: ints, floats, strings & booleans ints & floats: + addition - subtraction * multiplication / division ** exponent % modulus variable names: … no spaces … cannot begin with number: 1, 2 … … cannot contain ?$@# (except _) … cannot be a “built-in” name: and, or, int, float, str, char, exec, file, open, object, print, quit… (approx. 80 reserved names) comparisons: = = equal ! = not equal > greater than >= greater or equal than < less than <= less or equal than basic data types: integer, float, string, boolean converting types : int(), float(), str(), type() the linux command line: ls : list files & folders cd directory : change directory to run a python file: python filename.py user input: a = raw_input(“write stuff:”) strings: + concatenate * copy printing: print “literal text”, var1, var2, “more text”
  • 4. recap: if - else … # basic “if - else” block # indentation matters!!! if boolean : the “True” code goes here else: the “False” code goes here # basic “if - else” block if chairs < lions : print “Run away!” else: print “You are OK!” if chairs < lions : print “There are”, lions, “lions.” print “Run away!” else: print “You are OK” print “That’s all for now folks!” Indentation IS the logic of your code! non-logical and uneven indentation makes python angry The first line at the same level as the “if” begins the rest of the code (or program) the “else” goes at the same level as the “if” (because they belong together)
  • 5. # “if - elif - else” # blocks are tested in order # only the first True “if” or “elif” is handled if (boolean and/or boolean…) : the “True” code goes here elif (boolean and/or boolean…) : next “True” code goes here else: the “False” code goes here recap: if - else … # “if - elif - else” if chairs < lions : print “Run away!” elif chairs == lions :: print “You got lucky this time.” print “Buy more chairs!” else: print “Run away!”
  • 6. # “if - elif - else” # blocks are tested in order # only the first True “if” or “elif” is handled if (boolean and/or boolean…) : the “True” code goes here elif (boolean and/or boolean…) : next “True” code goes here else: the “False” code goes here recap: if - else … # “if - elif - else” if chairs < lions : print “Run away!” elif chairs == lions :: print “You got lucky this time.” print “Buy more chairs!” else: print “Run away!” # “if...” if chairs < lions : print “Run away!” elif chairs == lions :: print “Buy chairs tomorrow!” print “Program has finished!” the “else” is not required. Sometimes there is just “nothing else” to do :)
  • 7. recap: if - else … # combinatorial logic if (boolean and/or boolean…) : the “True” code goes here else: the “False” code goes here # combinatorial logic if (traps > bears) and (chairs > lions): print “your are OK” else: print “Run away!”
  • 8. recap: if - else … # combinatorial logic if (boolean and/or boolean…) : the “True” code goes here else: the “False” code goes here # combinatorial logic if (traps > bears) and (chairs > lions): print “your are OK” else: print “Run away!” # nested if if boolean: if boolean: “True True” code here else: “True False” code here else: “False” code here # nested if if lions > 0: if chairs < lions : print “Run away” else: print “You are OK” else: print “There are no lions”
  • 9. “if else” exercises - Write a script that asks the user 3 times to insert a single digit number. These will represent the digit for Hundreds, Tens and Unit/Single (of a three digit number). The script should output: - Whether the number is larger than 500 - The number reversed - Whether the reversed number is larger than 500 - Whether the number is a ‘palindrome’ - Write a scripts that asks the user for a number (between 0 and 999), and tells the user whether: - The number is larger than 100 - The number is even - Lastly: If the number is larger than 200, but ONLY if the number is even (otherwise it prints nothing)
  • 10. loops and iteration … for all numbers between 100 and 500… … for each row in a table … … for each image in collection of files … … for each pixel in an image … … while the total number is less than 1200 … … until you find the first value bigger than 500 … NOTE: this is c++ , not python ;)
  • 11. the almighty “for … in … range” ---- file contents ---- # iterating over a range of numbers is VERY common for i in range(10): print i # less trivial: 2 ** the first 10 numbers for i in range(10): print “2 to the power”, i, “is:”, 2 ** i # optional parameters to “range” for x in range(5, 10): print x for x in range(5, 10, 2): print x # going backwards… for x in range(20, 15, -1): print x # the basic “for - in - range” loop for x in range(stop): code to repeat goes here… again, indentation is everything in python! # the basic “for - in - range” loop # “start” and “step” are optional for x in range(start, stop, step): code to repeat goes here… 0 → stop - 1
  • 12. the almighty “for … in … range” # sum of all numbers < 100 total = 0 for i in range(100): total = total + i print “The total is:”, total # show all even numbers # between 100 and 200 for i in range(100, 200): if i % 2 == 0: print i, “is even.” # another way... for i in range(100, 200, 2): print i, “is even.” # the basic “for - in - range” loop for x in range(stop): code to repeat goes here… again, indentation is everything in python! # the basic “for - in - range” loop # “start” and “step” are optional for x in range(start, stop, step): code to repeat goes here… 0 → stop - 1
  • 13. the “while loop” ---- file contents ---- # adding numbers, until we reach 100 total = 0 while total <= 100: n = int(raw_input(“Please write a number:”)) total = total + n print “The total exceeded 100. It is:”, total # adding numbers, until we reach 100 user_input = “” while user_input != “stop”: user_input = raw_input(“Type ‘stop’ to stop:”) # the basic “while ” loop while boolean: code goes here again, indentation! NEVER use while loops! okay… not “never”, but a “for loop” is almost always better!
  • 14. okay, some more exercises Basic practice: - Write a script that asks the user for two numbers and calculates: - The sum of all numbers between the two. - Write a script that asks the user for a single number and calculates: - The sum of all even numbers between 0 and that number. A little more complex: - Write a script that asks the user for a single number and calculates whether or not the number is prime. - Write a script that asks the user for a single number and finds all prime numbers less than that number.
  • 15. Let’s write the following variants of the lion/chair/hungry program. They start as above, but: - If the ‘user’ does not write ‘yes’ or ‘no’ when answering ‘hungry?’, keeps on asking them for some useful information. Back to lions and bears # the beginning of the lion / hungry program from last week… chairs = int(raw_input(“How many chairs do you have?:”)) lions = int(raw_input(“How many lions are there?:”)) hungry = raw_input(“Are the lions hungry? (yes/no)?:”) … etc…