SlideShare a Scribd company logo
1 of 14
Creative Commons License
This work is licensed under a Creative Commons Attribution 4.0 International License.
BS GIS Instructor: Inzamam Baig
Lecture 5
Fundamentals of Programming
Iteration
Updating variables:
Updating a variable by adding 1 is called an increment
>>> x = x + 1
Subtracting 1 is called a decrement
>>> x = x - 1
The while statement
n = 5
while n > 0:
print(n)
n = n - 1
print('Blastoff!')
1. Evaluate the condition, yielding True or False.
2. If the condition is false, exit the while statement and continue
execution at the next statement.
3. If the condition is true, execute the body and then go back to step
1.
The body of the loop should change the value of one or more
variables so that eventually the condition becomes false and the
loop terminates
If there is no iteration variable, the loop will repeat forever,
resulting in an infinite loop
Infinite loops
n = 10
while True:
print(n, end=' ')
n = n - 1
print('Done!')
While this is a dysfunctional infinite loop, we can still use this
pattern to build useful loops
Break Statement
while True:
line = input('> ')
if line == 'done':
break print(line)
print('Done!')
Continue Statement
while True:
line = input('> ')
if line[0] == '#':
continue
if line == 'done':
break
print(line)
print('Done!')
For Loops
Sometimes we want to loop through a set of things such as a list
of words, the lines in a file, or a list of numbers
departments = ['BS', 'GIS', 'KIU']
for department in departments:
print('Department Name:', department)
print('Done!')
Loop Patterns
Often we use a for or while loop to go through a list of items or
the contents of a file
Or
looking for something such as the largest or smallest value of the
data we scan through
Loop Patterns
These loops are generally constructed by:
• Initializing one or more variables before the loop starts
• Performing some computation on each item in the loop body,
possibly changing the variables in the body of the loop
• Looking at the resulting variables when the loop completes
Counting Items
count = 0
for itervar in [3, 41, 12, 9, 74, 15]:
count = count + 1
print('Count: ', count)
Counting and summing loops
total = 0
for itervar in [3, 41, 12, 9, 74, 15]:
total = total + itervar
print('Total: ', total)
Maximum and Minimum
largest = None
print('Before:', largest)
for itervar in [3, 41, 12, 9, 74, 15]:
if largest is None or itervar > largest :
largest = itervar
print('Loop:', itervar, largest)
print('Largest:', largest)
Maximum and Minimum
smallest = None
print('Before:', smallest)
for itervar in [3, 41, 12, 9, 74, 15]:
if smallest is None or itervar < smallest:
smallest = itervar
print('Loop:', itervar, smallest)
print('Smallest:', smallest)

More Related Content

What's hot

1-2 Physics & Measurement
1-2 Physics & Measurement1-2 Physics & Measurement
1-2 Physics & Measurementrkelch
 
Applications of derivatives
Applications of derivativesApplications of derivatives
Applications of derivativessmj123
 
Angry birds maths
Angry birds mathsAngry birds maths
Angry birds mathscamelcars
 
2.2 Phy I - Acceleration
2.2 Phy I - Acceleration2.2 Phy I - Acceleration
2.2 Phy I - Accelerationmlong24
 
2.1 Phy I - Displacement and Velocity
2.1 Phy I - Displacement and Velocity2.1 Phy I - Displacement and Velocity
2.1 Phy I - Displacement and Velocitymlong24
 
Differentiation and Linearization
Differentiation and LinearizationDifferentiation and Linearization
Differentiation and LinearizationRAVI PRASAD K.J.
 
Units and measurements - Basic SI units
Units and measurements - Basic SI unitsUnits and measurements - Basic SI units
Units and measurements - Basic SI unitsBhagavathyP
 
Intro to Mechanics: The Sudy of Motion
Intro to Mechanics: The Sudy of MotionIntro to Mechanics: The Sudy of Motion
Intro to Mechanics: The Sudy of MotionI Wonder Why Science
 
Stats computing project_final
Stats computing project_finalStats computing project_final
Stats computing project_finalAyank Gupta
 
Units and measurements chapter 1 converted
Units and measurements chapter 1 convertedUnits and measurements chapter 1 converted
Units and measurements chapter 1 convertedAbhirajAshokPV
 
SAP ISU Validation Class : Comparison of n periods
SAP ISU Validation Class : Comparison of n periodsSAP ISU Validation Class : Comparison of n periods
SAP ISU Validation Class : Comparison of n periodsRakesh Dasgupta
 
Metric conversions 2010
Metric conversions 2010Metric conversions 2010
Metric conversions 2010sbarkanic
 

What's hot (20)

The speed
The speedThe speed
The speed
 
Linked list implementation of Stack
Linked list implementation of StackLinked list implementation of Stack
Linked list implementation of Stack
 
1-2 Physics & Measurement
1-2 Physics & Measurement1-2 Physics & Measurement
1-2 Physics & Measurement
 
Applications of derivatives
Applications of derivativesApplications of derivatives
Applications of derivatives
 
Angry birds maths
Angry birds mathsAngry birds maths
Angry birds maths
 
2.2 Phy I - Acceleration
2.2 Phy I - Acceleration2.2 Phy I - Acceleration
2.2 Phy I - Acceleration
 
Units and Measurement
Units and MeasurementUnits and Measurement
Units and Measurement
 
2.1 Phy I - Displacement and Velocity
2.1 Phy I - Displacement and Velocity2.1 Phy I - Displacement and Velocity
2.1 Phy I - Displacement and Velocity
 
MST
MSTMST
MST
 
Differentiation and Linearization
Differentiation and LinearizationDifferentiation and Linearization
Differentiation and Linearization
 
Units and measurements - Basic SI units
Units and measurements - Basic SI unitsUnits and measurements - Basic SI units
Units and measurements - Basic SI units
 
Intro to Mechanics: The Sudy of Motion
Intro to Mechanics: The Sudy of MotionIntro to Mechanics: The Sudy of Motion
Intro to Mechanics: The Sudy of Motion
 
Motion
MotionMotion
Motion
 
Stats computing project_final
Stats computing project_finalStats computing project_final
Stats computing project_final
 
S01-L03-SI Units
S01-L03-SI UnitsS01-L03-SI Units
S01-L03-SI Units
 
Units and measurements chapter 1 converted
Units and measurements chapter 1 convertedUnits and measurements chapter 1 converted
Units and measurements chapter 1 converted
 
Work
WorkWork
Work
 
SAP ISU Validation Class : Comparison of n periods
SAP ISU Validation Class : Comparison of n periodsSAP ISU Validation Class : Comparison of n periods
SAP ISU Validation Class : Comparison of n periods
 
Metric conversions 2010
Metric conversions 2010Metric conversions 2010
Metric conversions 2010
 
Vectorsandscalars
VectorsandscalarsVectorsandscalars
Vectorsandscalars
 

Similar to Python Lecture 5 (20)

Py4Inf-05-Iterations-Print.pdf
Py4Inf-05-Iterations-Print.pdfPy4Inf-05-Iterations-Print.pdf
Py4Inf-05-Iterations-Print.pdf
 
Python unit 3 and Unit 4
Python unit 3 and Unit 4Python unit 3 and Unit 4
Python unit 3 and Unit 4
 
Python_Module_2.pdf
Python_Module_2.pdfPython_Module_2.pdf
Python_Module_2.pdf
 
L06
L06L06
L06
 
Notes2
Notes2Notes2
Notes2
 
lab-8 (1).pptx
lab-8 (1).pptxlab-8 (1).pptx
lab-8 (1).pptx
 
Py4inf 05-iterations (1)
Py4inf 05-iterations (1)Py4inf 05-iterations (1)
Py4inf 05-iterations (1)
 
Py4inf 05-iterations (1)
Py4inf 05-iterations (1)Py4inf 05-iterations (1)
Py4inf 05-iterations (1)
 
Py4inf 05-iterations
Py4inf 05-iterationsPy4inf 05-iterations
Py4inf 05-iterations
 
While loop
While loopWhile loop
While loop
 
Iteration
IterationIteration
Iteration
 
Loop and while Loop
Loop and while LoopLoop and while Loop
Loop and while Loop
 
Chapter 13.1.5
Chapter 13.1.5Chapter 13.1.5
Chapter 13.1.5
 
03b loops
03b   loops03b   loops
03b loops
 
Looping
LoopingLooping
Looping
 
Loops
LoopsLoops
Loops
 
Python.pptx
Python.pptxPython.pptx
Python.pptx
 
C Language Lecture 6
C Language Lecture 6C Language Lecture 6
C Language Lecture 6
 
C# Loops
C# LoopsC# Loops
C# Loops
 
Iterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop workingIterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop working
 

More from Inzamam Baig

More from Inzamam Baig (13)

Python Lecture 8
Python Lecture 8Python Lecture 8
Python Lecture 8
 
Python Lecture 13
Python Lecture 13Python Lecture 13
Python Lecture 13
 
Python Lecture 12
Python Lecture 12Python Lecture 12
Python Lecture 12
 
Python Lecture 11
Python Lecture 11Python Lecture 11
Python Lecture 11
 
Python Lecture 10
Python Lecture 10Python Lecture 10
Python Lecture 10
 
Python Lecture 9
Python Lecture 9Python Lecture 9
Python Lecture 9
 
Python Lecture 7
Python Lecture 7Python Lecture 7
Python Lecture 7
 
Python Lecture 6
Python Lecture 6Python Lecture 6
Python Lecture 6
 
Python Lecture 4
Python Lecture 4Python Lecture 4
Python Lecture 4
 
Python Lecture 3
Python Lecture 3Python Lecture 3
Python Lecture 3
 
Python Lecture 2
Python Lecture 2Python Lecture 2
Python Lecture 2
 
Python Lecture 1
Python Lecture 1Python Lecture 1
Python Lecture 1
 
Python Lecture 0
Python Lecture 0Python Lecture 0
Python Lecture 0
 

Recently uploaded

Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxAnaBeatriceAblay2
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 

Recently uploaded (20)

Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 

Python Lecture 5

  • 1. Creative Commons License This work is licensed under a Creative Commons Attribution 4.0 International License. BS GIS Instructor: Inzamam Baig Lecture 5 Fundamentals of Programming
  • 2. Iteration Updating variables: Updating a variable by adding 1 is called an increment >>> x = x + 1 Subtracting 1 is called a decrement >>> x = x - 1
  • 3. The while statement n = 5 while n > 0: print(n) n = n - 1 print('Blastoff!') 1. Evaluate the condition, yielding True or False. 2. If the condition is false, exit the while statement and continue execution at the next statement. 3. If the condition is true, execute the body and then go back to step 1.
  • 4. The body of the loop should change the value of one or more variables so that eventually the condition becomes false and the loop terminates If there is no iteration variable, the loop will repeat forever, resulting in an infinite loop
  • 5. Infinite loops n = 10 while True: print(n, end=' ') n = n - 1 print('Done!') While this is a dysfunctional infinite loop, we can still use this pattern to build useful loops
  • 6. Break Statement while True: line = input('> ') if line == 'done': break print(line) print('Done!')
  • 7. Continue Statement while True: line = input('> ') if line[0] == '#': continue if line == 'done': break print(line) print('Done!')
  • 8. For Loops Sometimes we want to loop through a set of things such as a list of words, the lines in a file, or a list of numbers departments = ['BS', 'GIS', 'KIU'] for department in departments: print('Department Name:', department) print('Done!')
  • 9. Loop Patterns Often we use a for or while loop to go through a list of items or the contents of a file Or looking for something such as the largest or smallest value of the data we scan through
  • 10. Loop Patterns These loops are generally constructed by: • Initializing one or more variables before the loop starts • Performing some computation on each item in the loop body, possibly changing the variables in the body of the loop • Looking at the resulting variables when the loop completes
  • 11. Counting Items count = 0 for itervar in [3, 41, 12, 9, 74, 15]: count = count + 1 print('Count: ', count)
  • 12. Counting and summing loops total = 0 for itervar in [3, 41, 12, 9, 74, 15]: total = total + itervar print('Total: ', total)
  • 13. Maximum and Minimum largest = None print('Before:', largest) for itervar in [3, 41, 12, 9, 74, 15]: if largest is None or itervar > largest : largest = itervar print('Loop:', itervar, largest) print('Largest:', largest)
  • 14. Maximum and Minimum smallest = None print('Before:', smallest) for itervar in [3, 41, 12, 9, 74, 15]: if smallest is None or itervar < smallest: smallest = itervar print('Loop:', itervar, smallest) print('Smallest:', smallest)

Editor's Notes

  1. This type of flow is called a loop because the third step loops back around to the top. For the above loop, we would say, “It had five iterations”, which means that the body of the loop was executed five times
  2. If you make the mistake and run this code, you will learn quickly how to stop a runaway Python process on your system or find where the power-off button is on your computer
  3. suppose you want to take input from the user until they type done, the loop runs repeatedly until it hits the break statement.
  4. you can use the continue statement to skip to the next iteration without finishing the body of the loop for the current iteration. All the lines are printed except the one that starts with the hash sign because when the continue is executed, it ends the current iteration and jumps back to the while statement to start the next iteration
  5. When we have a list of things to loop through, we can construct a definite loop using a for statement. We call the while statement an indefinite loop because it simply loops until some condition becomes False, whereas the for loop is looping through a known set of items so it runs through as many iterations as there are items in the set. department is the iteration variable for the for loop. The department friend changes for each iteration of the loop and controls when the for loop completes
  6. to count the number of items in a list
  7. there are built-in functions len() and sum() that compute the number of items in a list and the total of the items in the list respectively
  8. None is a special constant value which we can store in a variable to mark the variable as “empty”