Chapter 4 Part 3 Pfe
Chapter 4 Part 3 Pfe
1
The for loop
• The for loop makes this process particularly easy to program. For
example, suppose we want to print a string, with one character
per line. We cannot simply print the string using the print
function. Instead, we need to iterate over the characters in the
string and print each character individually. Hereis how you use
the for loop to accomplish this task:
stateName = "Virginia"
for letter in stateName :
print(letter)
2
Equivalent while loop
i=0
while i < len(stateName) :
letter = stateName[i]
print(letter)
i=i+1
3
Range in python
4
Range in python
• We can also have the for loop count down instead of up:
5
Range in python
• Finally, you can use the range function with a single argument.
When you do, the range of values starts at zero.
6
Nested loops
• In this program, we
want to show the
results of multiple print
statements on the
same line. This is
achieved by adding the
argument end="" to
the print function.
8
Nested for loops
9
Practice questions
• How would you change the program to display all powers from
x^0 to x^5?
10
Some more fun with nested for
loops
• Prints 4 rows of * with lengths 1, 2, 3, and 4.
11
Some more fun with nested for
loops
• Prints 4 rows of * with lengths 1, 2, 3, and 4.
12
• Special Form of the print Function
• 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, . . ., valuen, end="")
14
Validating a string
15
16