SlideShare a Scribd company logo
1 of 15
Download to read offline
… 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

What's hot

Learn python in 20 minutes
Learn python in 20 minutesLearn python in 20 minutes
Learn python in 20 minutesSidharth Nadhan
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fuclimatewarrior
 
Lesson1 python an introduction
Lesson1 python an introductionLesson1 python an introduction
Lesson1 python an introductionArulalan T
 
How to avoid Go gotchas - Ivan Daniluk - Codemotion Milan 2016
How to avoid Go gotchas - Ivan Daniluk - Codemotion Milan 2016How to avoid Go gotchas - Ivan Daniluk - Codemotion Milan 2016
How to avoid Go gotchas - Ivan Daniluk - Codemotion Milan 2016Codemotion
 
Common mistakes in C programming
Common mistakes in C programmingCommon mistakes in C programming
Common mistakes in C programmingLarion
 
Python легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачиPython легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачиMaxim Kulsha
 
Introduction to Python (part 1/2)
Introduction to Python (part 1/2)Introduction to Python (part 1/2)
Introduction to Python (part 1/2)Silvia Tinena Coris
 
Introduction to Python Programming | InsideAIML
Introduction to Python Programming | InsideAIMLIntroduction to Python Programming | InsideAIML
Introduction to Python Programming | InsideAIMLVijaySharma802
 
Chapter 3 malik
Chapter 3 malikChapter 3 malik
Chapter 3 malikOshal Shah
 
An Intro to Python in 30 minutes
An Intro to Python in 30 minutesAn Intro to Python in 30 minutes
An Intro to Python in 30 minutesSumit Raj
 
Python language data types
Python language data typesPython language data types
Python language data typesHoang Nguyen
 

What's hot (18)

Learn python in 20 minutes
Learn python in 20 minutesLearn python in 20 minutes
Learn python in 20 minutes
 
Python
PythonPython
Python
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fu
 
Lesson1 python an introduction
Lesson1 python an introductionLesson1 python an introduction
Lesson1 python an introduction
 
How to avoid Go gotchas - Ivan Daniluk - Codemotion Milan 2016
How to avoid Go gotchas - Ivan Daniluk - Codemotion Milan 2016How to avoid Go gotchas - Ivan Daniluk - Codemotion Milan 2016
How to avoid Go gotchas - Ivan Daniluk - Codemotion Milan 2016
 
Common mistakes in C programming
Common mistakes in C programmingCommon mistakes in C programming
Common mistakes in C programming
 
Python легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачиPython легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачи
 
C# overview part 1
C# overview part 1C# overview part 1
C# overview part 1
 
Python : Data Types
Python : Data TypesPython : Data Types
Python : Data Types
 
Introduction to Python (part 1/2)
Introduction to Python (part 1/2)Introduction to Python (part 1/2)
Introduction to Python (part 1/2)
 
Python basics
Python basicsPython basics
Python basics
 
Python
PythonPython
Python
 
Introduction to Python Programming | InsideAIML
Introduction to Python Programming | InsideAIMLIntroduction to Python Programming | InsideAIML
Introduction to Python Programming | InsideAIML
 
Python basic
Python basicPython basic
Python basic
 
C Tutorials
C TutorialsC Tutorials
C Tutorials
 
Chapter 3 malik
Chapter 3 malikChapter 3 malik
Chapter 3 malik
 
An Intro to Python in 30 minutes
An Intro to Python in 30 minutesAn Intro to Python in 30 minutes
An Intro to Python in 30 minutes
 
Python language data types
Python language data typesPython language data types
Python language data types
 

Viewers also liked

Class 7a: Functions
Class 7a: FunctionsClass 7a: Functions
Class 7a: FunctionsMarc Gouw
 
Class 6: Lists & dictionaries
Class 6: Lists & dictionariesClass 6: Lists & dictionaries
Class 6: Lists & dictionariesMarc Gouw
 
Class 1: Welcome to programming
Class 1: Welcome to programmingClass 1: Welcome to programming
Class 1: Welcome to programmingMarc Gouw
 
Class 7b: Files & File I/O
Class 7b: Files & File I/OClass 7b: Files & File I/O
Class 7b: Files & File I/OMarc Gouw
 
Class 8a: Modules and imports
Class 8a: Modules and importsClass 8a: Modules and imports
Class 8a: Modules and importsMarc Gouw
 
RESUME Jitendra Dixit - Copy
RESUME Jitendra Dixit - CopyRESUME Jitendra Dixit - Copy
RESUME Jitendra Dixit - CopyJitendra Dixit
 
문플 경진대회
문플 경진대회문플 경진대회
문플 경진대회승주 한
 

Viewers also liked (12)

Class 7a: Functions
Class 7a: FunctionsClass 7a: Functions
Class 7a: Functions
 
Class 6: Lists & dictionaries
Class 6: Lists & dictionariesClass 6: Lists & dictionaries
Class 6: Lists & dictionaries
 
Heimo&Jolkkonen
Heimo&JolkkonenHeimo&Jolkkonen
Heimo&Jolkkonen
 
Class 1: Welcome to programming
Class 1: Welcome to programmingClass 1: Welcome to programming
Class 1: Welcome to programming
 
Class 7b: Files & File I/O
Class 7b: Files & File I/OClass 7b: Files & File I/O
Class 7b: Files & File I/O
 
Class 8a: Modules and imports
Class 8a: Modules and importsClass 8a: Modules and imports
Class 8a: Modules and imports
 
HDPE Pipe
HDPE PipeHDPE Pipe
HDPE Pipe
 
Intelligenza creativa
Intelligenza creativaIntelligenza creativa
Intelligenza creativa
 
PR for FITBIT
PR for FITBITPR for FITBIT
PR for FITBIT
 
RESUME Jitendra Dixit - Copy
RESUME Jitendra Dixit - CopyRESUME Jitendra Dixit - Copy
RESUME Jitendra Dixit - Copy
 
문플 경진대회
문플 경진대회문플 경진대회
문플 경진대회
 
Renaissance
RenaissanceRenaissance
Renaissance
 

Similar to Class 4: For and while

Programming with python
Programming with pythonProgramming with python
Programming with pythonsarogarage
 
Python for scientific computing
Python for scientific computingPython for scientific computing
Python for scientific computingGo Asgard
 
Learn python
Learn pythonLearn python
Learn pythonmocninja
 
Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)Paige Bailey
 
02 Control Structures - Loops & Conditions
02 Control Structures - Loops & Conditions02 Control Structures - Loops & Conditions
02 Control Structures - Loops & ConditionsEbad ullah Qureshi
 
CoderDojo: Intermediate Python programming course
CoderDojo: Intermediate Python programming courseCoderDojo: Intermediate Python programming course
CoderDojo: Intermediate Python programming courseAlexander Galkin
 
This is all about control flow in python intruducing the Break and Continue.pptx
This is all about control flow in python intruducing the Break and Continue.pptxThis is all about control flow in python intruducing the Break and Continue.pptx
This is all about control flow in python intruducing the Break and Continue.pptxelezearrepil1
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...DRVaibhavmeshram1
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayUtkarsh Sengar
 
Python language data types
Python language data typesPython language data types
Python language data typesHarry Potter
 
Python language data types
Python language data typesPython language data types
Python language data typesFraboni Ec
 
Python language data types
Python language data typesPython language data types
Python language data typesJames Wong
 
Python language data types
Python language data typesPython language data types
Python language data typesYoung Alista
 
Python language data types
Python language data typesPython language data types
Python language data typesTony Nguyen
 
Python language data types
Python language data typesPython language data types
Python language data typesLuis Goldster
 
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
 

Similar to Class 4: For and while (20)

Programming with python
Programming with pythonProgramming with python
Programming with python
 
Pythonintro
PythonintroPythonintro
Pythonintro
 
Python for scientific computing
Python for scientific computingPython for scientific computing
Python for scientific computing
 
Learn python
Learn pythonLearn python
Learn python
 
Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)
 
Python Math Concepts Book
Python Math Concepts BookPython Math Concepts Book
Python Math Concepts Book
 
02 Control Structures - Loops & Conditions
02 Control Structures - Loops & Conditions02 Control Structures - Loops & Conditions
02 Control Structures - Loops & Conditions
 
CoderDojo: Intermediate Python programming course
CoderDojo: Intermediate Python programming courseCoderDojo: Intermediate Python programming course
CoderDojo: Intermediate Python programming course
 
Computation Chapter 4
Computation Chapter 4Computation Chapter 4
Computation Chapter 4
 
This is all about control flow in python intruducing the Break and Continue.pptx
This is all about control flow in python intruducing the Break and Continue.pptxThis is all about control flow in python intruducing the Break and Continue.pptx
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...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
 
Python-Cheat-Sheet.pdf
Python-Cheat-Sheet.pdfPython-Cheat-Sheet.pdf
Python-Cheat-Sheet.pdf
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python language data types
Python language data typesPython language data types
Python language data types
 
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
 

Recently uploaded

Call Girls in Aiims Metro Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Aiims Metro Delhi 💯Call Us 🔝9953322196🔝 💯Escort.Call Girls in Aiims Metro Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Aiims Metro Delhi 💯Call Us 🔝9953322196🔝 💯Escort.aasikanpl
 
Call Us ≽ 9953322196 ≼ Call Girls In Mukherjee Nagar(Delhi) |
Call Us ≽ 9953322196 ≼ Call Girls In Mukherjee Nagar(Delhi) |Call Us ≽ 9953322196 ≼ Call Girls In Mukherjee Nagar(Delhi) |
Call Us ≽ 9953322196 ≼ Call Girls In Mukherjee Nagar(Delhi) |aasikanpl
 
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.aasikanpl
 
Evidences of Evolution General Biology 2
Evidences of Evolution General Biology 2Evidences of Evolution General Biology 2
Evidences of Evolution General Biology 2John Carlo Rollon
 
Gas_Laws_powerpoint_notes.ppt for grade 10
Gas_Laws_powerpoint_notes.ppt for grade 10Gas_Laws_powerpoint_notes.ppt for grade 10
Gas_Laws_powerpoint_notes.ppt for grade 10ROLANARIBATO3
 
Analytical Profile of Coleus Forskohlii | Forskolin .pptx
Analytical Profile of Coleus Forskohlii | Forskolin .pptxAnalytical Profile of Coleus Forskohlii | Forskolin .pptx
Analytical Profile of Coleus Forskohlii | Forskolin .pptxSwapnil Therkar
 
Call Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCR
Call Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCRCall Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCR
Call Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCRlizamodels9
 
Manassas R - Parkside Middle School 🌎🏫
Manassas R - Parkside Middle School 🌎🏫Manassas R - Parkside Middle School 🌎🏫
Manassas R - Parkside Middle School 🌎🏫qfactory1
 
Twin's paradox experiment is a meassurement of the extra dimensions.pptx
Twin's paradox experiment is a meassurement of the extra dimensions.pptxTwin's paradox experiment is a meassurement of the extra dimensions.pptx
Twin's paradox experiment is a meassurement of the extra dimensions.pptxEran Akiva Sinbar
 
Grafana in space: Monitoring Japan's SLIM moon lander in real time
Grafana in space: Monitoring Japan's SLIM moon lander  in real timeGrafana in space: Monitoring Japan's SLIM moon lander  in real time
Grafana in space: Monitoring Japan's SLIM moon lander in real timeSatoshi NAKAHIRA
 
Call Us ≽ 9953322196 ≼ Call Girls In Lajpat Nagar (Delhi) |
Call Us ≽ 9953322196 ≼ Call Girls In Lajpat Nagar (Delhi) |Call Us ≽ 9953322196 ≼ Call Girls In Lajpat Nagar (Delhi) |
Call Us ≽ 9953322196 ≼ Call Girls In Lajpat Nagar (Delhi) |aasikanpl
 
zoogeography of pakistan.pptx fauna of Pakistan
zoogeography of pakistan.pptx fauna of Pakistanzoogeography of pakistan.pptx fauna of Pakistan
zoogeography of pakistan.pptx fauna of Pakistanzohaibmir069
 
Spermiogenesis or Spermateleosis or metamorphosis of spermatid
Spermiogenesis or Spermateleosis or metamorphosis of spermatidSpermiogenesis or Spermateleosis or metamorphosis of spermatid
Spermiogenesis or Spermateleosis or metamorphosis of spermatidSarthak Sekhar Mondal
 
Behavioral Disorder: Schizophrenia & it's Case Study.pdf
Behavioral Disorder: Schizophrenia & it's Case Study.pdfBehavioral Disorder: Schizophrenia & it's Case Study.pdf
Behavioral Disorder: Schizophrenia & it's Case Study.pdfSELF-EXPLANATORY
 
Call Girls in Mayapuri Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Mayapuri Delhi 💯Call Us 🔝9953322196🔝 💯Escort.Call Girls in Mayapuri Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Mayapuri Delhi 💯Call Us 🔝9953322196🔝 💯Escort.aasikanpl
 
LIGHT-PHENOMENA-BY-CABUALDIONALDOPANOGANCADIENTE-CONDEZA (1).pptx
LIGHT-PHENOMENA-BY-CABUALDIONALDOPANOGANCADIENTE-CONDEZA (1).pptxLIGHT-PHENOMENA-BY-CABUALDIONALDOPANOGANCADIENTE-CONDEZA (1).pptx
LIGHT-PHENOMENA-BY-CABUALDIONALDOPANOGANCADIENTE-CONDEZA (1).pptxmalonesandreagweneth
 
Microphone- characteristics,carbon microphone, dynamic microphone.pptx
Microphone- characteristics,carbon microphone, dynamic microphone.pptxMicrophone- characteristics,carbon microphone, dynamic microphone.pptx
Microphone- characteristics,carbon microphone, dynamic microphone.pptxpriyankatabhane
 
Dashanga agada a formulation of Agada tantra dealt in 3 Rd year bams agada tanta
Dashanga agada a formulation of Agada tantra dealt in 3 Rd year bams agada tantaDashanga agada a formulation of Agada tantra dealt in 3 Rd year bams agada tanta
Dashanga agada a formulation of Agada tantra dealt in 3 Rd year bams agada tantaPraksha3
 

Recently uploaded (20)

Call Girls in Aiims Metro Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Aiims Metro Delhi 💯Call Us 🔝9953322196🔝 💯Escort.Call Girls in Aiims Metro Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Aiims Metro Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
 
Hot Sexy call girls in Moti Nagar,🔝 9953056974 🔝 escort Service
Hot Sexy call girls in  Moti Nagar,🔝 9953056974 🔝 escort ServiceHot Sexy call girls in  Moti Nagar,🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Moti Nagar,🔝 9953056974 🔝 escort Service
 
Call Us ≽ 9953322196 ≼ Call Girls In Mukherjee Nagar(Delhi) |
Call Us ≽ 9953322196 ≼ Call Girls In Mukherjee Nagar(Delhi) |Call Us ≽ 9953322196 ≼ Call Girls In Mukherjee Nagar(Delhi) |
Call Us ≽ 9953322196 ≼ Call Girls In Mukherjee Nagar(Delhi) |
 
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
 
Evidences of Evolution General Biology 2
Evidences of Evolution General Biology 2Evidences of Evolution General Biology 2
Evidences of Evolution General Biology 2
 
Gas_Laws_powerpoint_notes.ppt for grade 10
Gas_Laws_powerpoint_notes.ppt for grade 10Gas_Laws_powerpoint_notes.ppt for grade 10
Gas_Laws_powerpoint_notes.ppt for grade 10
 
Analytical Profile of Coleus Forskohlii | Forskolin .pptx
Analytical Profile of Coleus Forskohlii | Forskolin .pptxAnalytical Profile of Coleus Forskohlii | Forskolin .pptx
Analytical Profile of Coleus Forskohlii | Forskolin .pptx
 
Call Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCR
Call Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCRCall Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCR
Call Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCR
 
Manassas R - Parkside Middle School 🌎🏫
Manassas R - Parkside Middle School 🌎🏫Manassas R - Parkside Middle School 🌎🏫
Manassas R - Parkside Middle School 🌎🏫
 
Twin's paradox experiment is a meassurement of the extra dimensions.pptx
Twin's paradox experiment is a meassurement of the extra dimensions.pptxTwin's paradox experiment is a meassurement of the extra dimensions.pptx
Twin's paradox experiment is a meassurement of the extra dimensions.pptx
 
Grafana in space: Monitoring Japan's SLIM moon lander in real time
Grafana in space: Monitoring Japan's SLIM moon lander  in real timeGrafana in space: Monitoring Japan's SLIM moon lander  in real time
Grafana in space: Monitoring Japan's SLIM moon lander in real time
 
Call Us ≽ 9953322196 ≼ Call Girls In Lajpat Nagar (Delhi) |
Call Us ≽ 9953322196 ≼ Call Girls In Lajpat Nagar (Delhi) |Call Us ≽ 9953322196 ≼ Call Girls In Lajpat Nagar (Delhi) |
Call Us ≽ 9953322196 ≼ Call Girls In Lajpat Nagar (Delhi) |
 
zoogeography of pakistan.pptx fauna of Pakistan
zoogeography of pakistan.pptx fauna of Pakistanzoogeography of pakistan.pptx fauna of Pakistan
zoogeography of pakistan.pptx fauna of Pakistan
 
Spermiogenesis or Spermateleosis or metamorphosis of spermatid
Spermiogenesis or Spermateleosis or metamorphosis of spermatidSpermiogenesis or Spermateleosis or metamorphosis of spermatid
Spermiogenesis or Spermateleosis or metamorphosis of spermatid
 
Behavioral Disorder: Schizophrenia & it's Case Study.pdf
Behavioral Disorder: Schizophrenia & it's Case Study.pdfBehavioral Disorder: Schizophrenia & it's Case Study.pdf
Behavioral Disorder: Schizophrenia & it's Case Study.pdf
 
Call Girls in Mayapuri Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Mayapuri Delhi 💯Call Us 🔝9953322196🔝 💯Escort.Call Girls in Mayapuri Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Mayapuri Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
 
LIGHT-PHENOMENA-BY-CABUALDIONALDOPANOGANCADIENTE-CONDEZA (1).pptx
LIGHT-PHENOMENA-BY-CABUALDIONALDOPANOGANCADIENTE-CONDEZA (1).pptxLIGHT-PHENOMENA-BY-CABUALDIONALDOPANOGANCADIENTE-CONDEZA (1).pptx
LIGHT-PHENOMENA-BY-CABUALDIONALDOPANOGANCADIENTE-CONDEZA (1).pptx
 
Microphone- characteristics,carbon microphone, dynamic microphone.pptx
Microphone- characteristics,carbon microphone, dynamic microphone.pptxMicrophone- characteristics,carbon microphone, dynamic microphone.pptx
Microphone- characteristics,carbon microphone, dynamic microphone.pptx
 
Dashanga agada a formulation of Agada tantra dealt in 3 Rd year bams agada tanta
Dashanga agada a formulation of Agada tantra dealt in 3 Rd year bams agada tantaDashanga agada a formulation of Agada tantra dealt in 3 Rd year bams agada tanta
Dashanga agada a formulation of Agada tantra dealt in 3 Rd year bams agada tanta
 
Volatile Oils Pharmacognosy And Phytochemistry -I
Volatile Oils Pharmacognosy And Phytochemistry -IVolatile Oils Pharmacognosy And Phytochemistry -I
Volatile Oils Pharmacognosy And Phytochemistry -I
 

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…