An Introduction To Python - FOR Loop

24
An Introduction To Software Development Using Python Spring Semester, 2015 Class #8: FOR Loop

Transcript of An Introduction To Python - FOR Loop

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 = 0while 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, ..., 9print(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, ..., 9print(i)

i = 1while 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 changedby including a step value as the third argument to the function:

for i in range(1, 10, 2) : # i = 1, 3, 5, ..., 9print(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, ..., 9print("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 foreach 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.comImage Credit: www.dreamstime.com

Counting Matches In Strings

• Count the number of uppercase letters in a string:

uppercase = 0for 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 MatchIn A String

• If your task is to find a match, then you can stop as soon as the condition is fulfilled.

found = Falseposition = 0while 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/