SlideShare a Scribd company logo
An Introduction To Software
Development Using Python
Spring Semester, 2015
Class #8:
FOR Loop
Programming Challenge:
Print Each Character Of A String
• The user will enter their name
• Your program will then step through the string
that they entered and print out each character
by itself on a line listing their name vertically.
Image Credit: megmedina.com
Programming Challenge:
Print Each Character Of A String
userName = input(“Enter your name: ”)
i = 0
while i < len(userName) :
letter = userName[i]
print(letter)
i = i + 1
Image Credit: thegraphicsfairy.com
The For Statement
The for loop can be used to iterate over the contents of any container, which is an
object that contains or stores a collection of elements. Thus, a string is a container
that stores the collection of characters in the string.
Programming Challenge:
Print Each Character Of A String
userName = input(“Enter your name: ”)
for letter in userName :
print(letter)
Image Credit: thegraphicsfairy.com
What’s The Difference Between
While Loops and For Loops?
• In the for loop, the element variable is
assigned stateName[0] , stateName[1] , and so
on.
• In the while loop, the index variable i is
assigned 0, 1, and so on.
Image Credit: www.clipartpanda.com
The Range Function
• Count-controlled loops that iterate over a range of integer values are very
common.
• To simplify the creation of such loops, Python provides the range function
for generating a sequence of integers that can be used with the for loop.
• The loop code:
for i in range(1, 10) : # i = 1, 2, 3, ..., 9
print(i)
prints the sequential values from 1 to 9. The range function generates a
sequence of values based on its arguments.
• The first argument of the range function is the first value in the sequence.
• Values are included in the sequence while they are less than the second
argument
Image Credit: www.best-of-web.com
You Can Do The Same Thing With
While And For Loops
for i in range(1, 10) : # i = 1, 2, 3, ..., 9
print(i)
i = 1
while i < 10 :
print(i)
i = i + 1
Image Credit: www.rgbstock.com
Note that the ending value (the second argument to the range function) is not included
in the sequence, so the equivalent while loop stops before reaching that value, too.
Stepping Out…
• By default, the range function creates the
sequence in steps of 1. This can be changed
by including a step value as the third
argument to the function:
for i in range(1, 10, 2) : # i = 1, 3, 5, ..., 9
print(i)
Image Credit: megmedina.com
Loop Challenge #2!
• Create a program to print the sum of all odd
numbers between a and b (inclusive).
Image Credit: www.dreamstime.com
For Loop With One Argument
• You can use the range function with a single
argument.
• When you do, the range of values starts at
zero.
for i in range(10) : # i = 0, 1, 2, ..., 9
print("Hello") # Prints Hello ten times
Image Credit: www.canstockphoto.com
Review: The Many Different Forms
Of A Range
Describe The Steps Necessary For
Finding A Solution To A Problem
Problem:
You put $10,000 into a bank account that earns 5 percent interest per year.
How many years does it take for the account balance to be double the original?
Count Iterations
• Finding the correct lower and upper bounds for a loop can be
confusing.
– Should you start at 0 or at 1?
– Should you use <= b or < b as a termination condition?
• The following loops are executed b - a times:
• These asymmetric bounds are particularly
useful for traversing the characters in a string
int i = a
while i < b :
. . .
i = i + 1
for i in range(a, b) :
for i in range(0, len(str)) :
do something with i and str[i]
Image Credit: imgarcade.com
The +1 Problem
• How many times is the loop with symmetric bounds
executed?
int i = a
while i <= b :
. . .
i = i + 1
• b - a + 1 times. That “+1” is the source of many programming
errors.
• When a is 10 and b is 20, how many times does the loop
execute?
• In a Python for loop, the “+1” can be quite noticeable:
for year in range(1, numYears + 1) :
Image Credit: www.clipartbest.com
Loop Challenge #3!
• Read twelve temperature values (one for
each month), and display the number of the
month with the highest temperature. For
example the average maximum temperatures
for Death Valley are (in order by month, in
degrees Celsius):
18.2, 22.6, 26.4, 31.1, 36.6, 42.2, 45.7, 44.5, 40.2, 33.1, 24.2, 17.6
Image Credit: www.dreamstime.com
Secret Form Of print Statement
• Python provides a special form of the print function that
prevents it from starting a new line after its arguments are
displayed.
print(value1, value2, end="")
• By including end="" as the last argument to the first print
function, we indicate that an empty string is to be printed
after the last argument is printed instead of starting a new
line.
• The output of the next print function starts on the same line
where the previous one left off.
Image Credit: www.clipartpanda.com
Loop Challenge #4!
• Create a program to print the following table
that contains the first four power values for
the numbers 1-10.
Image Credit: www.rafainspirationhomedecor.com
Image Credit: www.dreamstime.com
Counting Matches In Strings
• Count the number of uppercase letters in a
string:
uppercase = 0
for char in string :
if char.isupper() :
uppercase = uppercase + 1
• Count the number of occurrences of multiple
characters within a string.
vowels = 0
for char in word :
if char.lower() in "aeiou" :
vowels = vowels + 1
Image Credit: www.clipartpanda.com
Finding All Matches In A String
• When you need to examine every character within a string,
independent of its position, you can use the for statement to
iterate over the individual characters.
• For example, suppose you are asked to print the position of
each uppercase letter in a sentence.
sentence = input("Enter a sentence: ")
for i in range(len(sentence)) :
if sentence[i].isupper() :
print(i)
Image Credit: www.clipartpanda.com
Finding the First or Last Match
In A String
• If your task is to find a match, then you can
stop as soon as the condition is fulfilled.
found = False
position = 0
while not found and position < len(string) :
if string[position].isdigit() :
found = True
else :
position = position + 1
if found :
print("First digit occurs at position", position)
else :
print("The string does not contain a digit.")
What’s In Your Python Toolbox?
print() math strings I/O IF/Else elif While For
What We Covered Today
1. For Loop
2. Range
3. Using loops to process
strings
Image Credit: http://www.tswdj.com/blog/2011/05/17/the-grooms-checklist/
What We’ll Be Covering Next Time
1. Lists, Part 1
Image Credit: http://merchantblog.thefind.com/2011/01/merchant-newsletter/resolve-to-take-advantage-of-these-5-e-commerce-trends/attachment/crystal-ball-fullsize/

More Related Content

PDF
Basic Operator, String and Characters in Swift.
PPTX
Computer Programming Utilities the subject of BE first year students, and thi...
PPTX
String in c programming
PDF
PDF
Introduction to r
PPTX
Computer programming 2 Lesson 10
PPTX
Python Programming | JNTUK | UNIT 1 | Lecture 4
PPT
Strings v.1.1
Basic Operator, String and Characters in Swift.
Computer Programming Utilities the subject of BE first year students, and thi...
String in c programming
Introduction to r
Computer programming 2 Lesson 10
Python Programming | JNTUK | UNIT 1 | Lecture 4
Strings v.1.1

What's hot (20)

PDF
Numpy string functions
PPTX
2CPP13 - Operator Overloading
PPT
Python
PPTX
String in python lecture (3)
PDF
Pythonintro
PPTX
Parts of python programming language
PPTX
Python Data-Types
PPTX
Whiteboarding Coding Challenges in Python
PPTX
Text and Numbers (Data Types)in PHP
PPT
07 Arrays
PDF
Approximation Data Structures for Streaming Applications
PPTX
Python programming –part 3
PPTX
Regular Expressions in Java
PDF
ACM init() Spring 2015 Day 1
PPTX
Manipulation strings in c++
PDF
SPL 12.1 | Multi Dimensional(Two) Array Practice Problems
PDF
Functional and Algebraic Domain Modeling
PPTX
FSTREAM,ASSERT LIBRARY & CTYPE LIBRARY.
PDF
Monad Transformers - Part 1
PDF
Class 3: if/else
Numpy string functions
2CPP13 - Operator Overloading
Python
String in python lecture (3)
Pythonintro
Parts of python programming language
Python Data-Types
Whiteboarding Coding Challenges in Python
Text and Numbers (Data Types)in PHP
07 Arrays
Approximation Data Structures for Streaming Applications
Python programming –part 3
Regular Expressions in Java
ACM init() Spring 2015 Day 1
Manipulation strings in c++
SPL 12.1 | Multi Dimensional(Two) Array Practice Problems
Functional and Algebraic Domain Modeling
FSTREAM,ASSERT LIBRARY & CTYPE LIBRARY.
Monad Transformers - Part 1
Class 3: if/else
Ad

Viewers also liked (16)

PPTX
An Introduction To Python - Lists, Part 1
PPTX
An Introduction To Python - Tables, List Algorithms
PPTX
An Introduction To Python - Dictionaries
PPTX
An Introduction To Python - WHILE Loop
PPTX
An Introduction To Python - Python, Print()
PPTX
An Introduction To Python - Files, Part 1
PPTX
An Introduction To Python - Lists, Part 2
PPTX
An Introduction To Python - Variables, Math
PPTX
An Introduction To Python - Graphics
PPTX
An Introduction To Python - Functions, Part 2
PPTX
An Introduction To Python - Working With Data
PPTX
An Introduction To Software Development - Software Support and Maintenance
PPTX
An Introduction To Python - Nested Branches, Multiple Alternatives
PPTX
An Introduction To Python - Python Midterm Review
PPTX
An Introduction To Software Development - Implementation
PPTX
An Introduction To Software Development - Architecture & Detailed Design
An Introduction To Python - Lists, Part 1
An Introduction To Python - Tables, List Algorithms
An Introduction To Python - Dictionaries
An Introduction To Python - WHILE Loop
An Introduction To Python - Python, Print()
An Introduction To Python - Files, Part 1
An Introduction To Python - Lists, Part 2
An Introduction To Python - Variables, Math
An Introduction To Python - Graphics
An Introduction To Python - Functions, Part 2
An Introduction To Python - Working With Data
An Introduction To Software Development - Software Support and Maintenance
An Introduction To Python - Nested Branches, Multiple Alternatives
An Introduction To Python - Python Midterm Review
An Introduction To Software Development - Implementation
An Introduction To Software Development - Architecture & Detailed Design
Ad

Similar to An Introduction To Python - FOR Loop (20)

PDF
2 Python Basics II meeting 2 tunghai university pdf
PPTX
Python basics
PPTX
Python basics
PPTX
Python basics
PPTX
Python basics
PPTX
Python basics
PPTX
Python basics
PPTX
Python basics
PPTX
Mastering Python lesson3b_for_loops
PPTX
While_for_loop presententationin first year students
PDF
While-For-loop in python used in college
PPTX
ForLoops.pptx
PPTX
Loops in python including control statements and various test cases
PPT
python fundamental for beginner course .ppt
PPTX
Introduction to python programming ( part-3 )
PDF
Notes2
PPT
Py4inf 05-iterations (1)
PPT
Py4inf 05-iterations (1)
PPT
Py4inf 05-iterations
2 Python Basics II meeting 2 tunghai university pdf
Python basics
Python basics
Python basics
Python basics
Python basics
Python basics
Python basics
Mastering Python lesson3b_for_loops
While_for_loop presententationin first year students
While-For-loop in python used in college
ForLoops.pptx
Loops in python including control statements and various test cases
python fundamental for beginner course .ppt
Introduction to python programming ( part-3 )
Notes2
Py4inf 05-iterations (1)
Py4inf 05-iterations (1)
Py4inf 05-iterations

Recently uploaded (20)

PPTX
master seminar digital applications in india
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PDF
Classroom Observation Tools for Teachers
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
Cell Types and Its function , kingdom of life
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
Presentation on HIE in infants and its manifestations
PPTX
Pharma ospi slides which help in ospi learning
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
master seminar digital applications in india
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
Classroom Observation Tools for Teachers
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Chinmaya Tiranga quiz Grand Finale.pdf
Anesthesia in Laparoscopic Surgery in India
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Cell Types and Its function , kingdom of life
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Presentation on HIE in infants and its manifestations
Pharma ospi slides which help in ospi learning
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
STATICS OF THE RIGID BODIES Hibbelers.pdf
O7-L3 Supply Chain Operations - ICLT Program
202450812 BayCHI UCSC-SV 20250812 v17.pptx
Supply Chain Operations Speaking Notes -ICLT Program
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
102 student loan defaulters named and shamed – Is someone you know on the list?

An Introduction To Python - FOR Loop

  • 1. An Introduction To Software Development Using Python Spring Semester, 2015 Class #8: FOR Loop
  • 2. Programming Challenge: Print Each Character Of A String • The user will enter their name • Your program will then step through the string that they entered and print out each character by itself on a line listing their name vertically. Image Credit: megmedina.com
  • 3. Programming Challenge: Print Each Character Of A String userName = input(“Enter your name: ”) i = 0 while i < len(userName) : letter = userName[i] print(letter) i = i + 1 Image Credit: thegraphicsfairy.com
  • 4. The For Statement The for loop can be used to iterate over the contents of any container, which is an object that contains or stores a collection of elements. Thus, a string is a container that stores the collection of characters in the string.
  • 5. Programming Challenge: Print Each Character Of A String userName = input(“Enter your name: ”) for letter in userName : print(letter) Image Credit: thegraphicsfairy.com
  • 6. What’s The Difference Between While Loops and For Loops? • In the for loop, the element variable is assigned stateName[0] , stateName[1] , and so on. • In the while loop, the index variable i is assigned 0, 1, and so on. Image Credit: www.clipartpanda.com
  • 7. The Range Function • Count-controlled loops that iterate over a range of integer values are very common. • To simplify the creation of such loops, Python provides the range function for generating a sequence of integers that can be used with the for loop. • The loop code: for i in range(1, 10) : # i = 1, 2, 3, ..., 9 print(i) prints the sequential values from 1 to 9. The range function generates a sequence of values based on its arguments. • The first argument of the range function is the first value in the sequence. • Values are included in the sequence while they are less than the second argument Image Credit: www.best-of-web.com
  • 8. You Can Do The Same Thing With While And For Loops for i in range(1, 10) : # i = 1, 2, 3, ..., 9 print(i) i = 1 while i < 10 : print(i) i = i + 1 Image Credit: www.rgbstock.com Note that the ending value (the second argument to the range function) is not included in the sequence, so the equivalent while loop stops before reaching that value, too.
  • 9. Stepping Out… • By default, the range function creates the sequence in steps of 1. This can be changed by including a step value as the third argument to the function: for i in range(1, 10, 2) : # i = 1, 3, 5, ..., 9 print(i) Image Credit: megmedina.com
  • 10. Loop Challenge #2! • Create a program to print the sum of all odd numbers between a and b (inclusive). Image Credit: www.dreamstime.com
  • 11. For Loop With One Argument • You can use the range function with a single argument. • When you do, the range of values starts at zero. for i in range(10) : # i = 0, 1, 2, ..., 9 print("Hello") # Prints Hello ten times Image Credit: www.canstockphoto.com
  • 12. Review: The Many Different Forms Of A Range
  • 13. Describe The Steps Necessary For Finding A Solution To A Problem Problem: You put $10,000 into a bank account that earns 5 percent interest per year. How many years does it take for the account balance to be double the original?
  • 14. Count Iterations • Finding the correct lower and upper bounds for a loop can be confusing. – Should you start at 0 or at 1? – Should you use <= b or < b as a termination condition? • The following loops are executed b - a times: • These asymmetric bounds are particularly useful for traversing the characters in a string int i = a while i < b : . . . i = i + 1 for i in range(a, b) : for i in range(0, len(str)) : do something with i and str[i] Image Credit: imgarcade.com
  • 15. The +1 Problem • How many times is the loop with symmetric bounds executed? int i = a while i <= b : . . . i = i + 1 • b - a + 1 times. That “+1” is the source of many programming errors. • When a is 10 and b is 20, how many times does the loop execute? • In a Python for loop, the “+1” can be quite noticeable: for year in range(1, numYears + 1) : Image Credit: www.clipartbest.com
  • 16. Loop Challenge #3! • Read twelve temperature values (one for each month), and display the number of the month with the highest temperature. For example the average maximum temperatures for Death Valley are (in order by month, in degrees Celsius): 18.2, 22.6, 26.4, 31.1, 36.6, 42.2, 45.7, 44.5, 40.2, 33.1, 24.2, 17.6 Image Credit: www.dreamstime.com
  • 17. Secret Form Of print Statement • Python provides a special form of the print function that prevents it from starting a new line after its arguments are displayed. print(value1, value2, end="") • By including end="" as the last argument to the first print function, we indicate that an empty string is to be printed after the last argument is printed instead of starting a new line. • The output of the next print function starts on the same line where the previous one left off. Image Credit: www.clipartpanda.com
  • 18. Loop Challenge #4! • Create a program to print the following table that contains the first four power values for the numbers 1-10. Image Credit: www.rafainspirationhomedecor.com Image Credit: www.dreamstime.com
  • 19. Counting Matches In Strings • Count the number of uppercase letters in a string: uppercase = 0 for char in string : if char.isupper() : uppercase = uppercase + 1 • Count the number of occurrences of multiple characters within a string. vowels = 0 for char in word : if char.lower() in "aeiou" : vowels = vowels + 1 Image Credit: www.clipartpanda.com
  • 20. Finding All Matches In A String • When you need to examine every character within a string, independent of its position, you can use the for statement to iterate over the individual characters. • For example, suppose you are asked to print the position of each uppercase letter in a sentence. sentence = input("Enter a sentence: ") for i in range(len(sentence)) : if sentence[i].isupper() : print(i) Image Credit: www.clipartpanda.com
  • 21. Finding the First or Last Match In A String • If your task is to find a match, then you can stop as soon as the condition is fulfilled. found = False position = 0 while not found and position < len(string) : if string[position].isdigit() : found = True else : position = position + 1 if found : print("First digit occurs at position", position) else : print("The string does not contain a digit.")
  • 22. What’s In Your Python Toolbox? print() math strings I/O IF/Else elif While For
  • 23. What We Covered Today 1. For Loop 2. Range 3. Using loops to process strings Image Credit: http://www.tswdj.com/blog/2011/05/17/the-grooms-checklist/
  • 24. What We’ll Be Covering Next Time 1. Lists, Part 1 Image Credit: http://merchantblog.thefind.com/2011/01/merchant-newsletter/resolve-to-take-advantage-of-these-5-e-commerce-trends/attachment/crystal-ball-fullsize/

Editor's Notes

  • #2: New name for the class I know what this means Technical professionals are who get hired This means much more than just having a narrow vertical knowledge of some subject area. It means that you know how to produce an outcome that I value. I’m willing to pay you to do that.