This document discusses for loops in Python. It explains that for loops can be used to iterate over any container, including strings which store a collection of characters. The document provides examples of using for loops to print each character in a string. It also discusses the range function, which can generate a sequence of integers to iterate over in a for loop. The key differences between while and for loops are explained.
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
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
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
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.