Chapter 4 For Loops and Strings

Run Loopy String Program

Questions:

  1. What did the program do?
  1. What do you think the key word “for” did?
  1. How did it know to go to the next letter? How did it know when it was finished with the word?

I. For Loops-used when you know how many times you want the loop to iterate.

Iterate- means loop

For Loops automatically increment to the next number/character.

Run Counter Program

Questions.

  1. Write the output for each line found in the program
  2. for i in range(10):

print(i,end=” “)

  1. for i in range(0,50,5):

print(I, end=” “)

  1. for i=range(10,0,-1):

print(i, end=” “)

For loop syntax

for loop control variable(starting value, ending value, increment)

for loop control variable(ending value)- increments by 1 and starts at 0.

for loop control variable(starting value, ending value) increments by 1.

Note the ending value is one greater than the actual last number.

Practice: Write a program using a for loop that adds the numbers from 1 to 50; showing each number and the sum. Output should look like this: 1 + 2 + ….= sum value

Ch. 5 For Loop Worksheet #1

Trace the following code segments. Show the trace of values for each variable in the appropriate columns.

1.

sum = 0

i = 0

for i in range(10):

sum+= 1

2.

sum = 100

i = 0

For i in range( 20, 1 , -3):

sum = sum - i

3.

total =1

limit = 50

deposit = 0

for deposit in range( 0, limit, 10):

total = total + deposit * 0.1

4

num1 = 1

num2 = 1

new = 0

i= 0

for i in range(7):

new = num1 + num2

num1 = num2

num2 = new

5. Write a Forloop that adds the integers -6 through 5 and stores the sum in the variable sum.

6. Write a Forloop that adds the even integers between 20 and 34 and stores the sum in the variable sum.

7. Write a Forloop that displays each of the values in the sequences 24, 28, 32, 36, …, 52 in one line.

8. Write a Forloop that computes the sum of the values in the sequence 1, 3, 6, 10, 15, 21, …, 55 and stores that sum in the variable sum

For Loop Worksheet #2

  1. Write a for loop that adds the numbers from 1 to 50. Have the sum outputted at the end of the loop.
  1. Write a for loop that shows the value of a dice rolled 10 times. Used dice=random.randint(1,6) to tenerate the dice roll.
  1. Write a for loop that would ask the user to enter in a name 6 times.
  1. Write a for loop that shows the numbers 20-10, shown in descending order.
  1. Trace the loop. State the ending value of sum.

i=0

sum=0

for i in range(1,10,2):

sum+=i

II. Using Sequence Operators and Functions with Strings

Run Message Analyzer

Questions

  1. What did Message Analyzer do?
  1. What does the function len produce?
  1. len(string’s name)- returns the length of the string.
  2. Searching for a character in a string
  3. If “e” in message:

print(“is in your message”)

else:

print(“is not in your message”)

  1. You can use “in” anywhere in your programs to check if an element is a member of a sequence.
  2. Indexing Strings-you specify a position (or index) number in a sequence and get the element at that position. The number 0 is the first position or index of a sequence.
  3. Example:

word=”index”

print(word[0]) # prints i

print(word[4]) #prints x

print(word[2]) #prints d

  1. Negative positions may be used to access the sequence backwards.

word=”index”

print(word[-1]) #prints x --- means last element

print(word[-2]) # prints e---means 2nd to last element

0 / 1 / 2 / 3 / 4
i / n / d / e / x
-5 / -4 / -3 / -2 / -1

Random Access Program- type in the following program.

import random

word=”index”

print(“The word is : “,word,”\n”)

high=len(word)

low=-len(word)

for i in range(10):

position=random.randrange(low,high)

print(“word[“, position, “}\t”, word[position])

input(“\n\nPress the enter key to exit”)

Questions

1. What is the range of random numbers generated?

2. How many times did the for loop execute?

Practice:

  1. Write a program that adds the multiples of 3’s from 3-30(inclusive), output the multiples and sum.
  2. Write a program that has the user input a sentence. The user then inputs in a word to search for in the inputted sentence. If the word is found, output “Found word” else says “ Not found”

E. String Immutability

1. Mutable- means changeable

2. Immutable-unchangeable. String sequences in programming are immutable. If you try to change a character in a string through it’s index- you will get an error message.

Example:

word=”game”

word[0]=”t” # This would result in an error.

  1. Building New Strings
  2. Concatenation- adding two strings together. Word=”dog” + “cat” woud result in word=”dogcat”
  3. Building a new string one character at a time.

Run No Vowels Program.

  1. What happened in this program?
  2. How did it know when to stop the for loop?
  3. What did the lines Not in VOWELS do?
  4. Why use letter.lower?
  1. Variables typed in all CAPS mean they are constants. They are not meant to be changed. In Python, the constant can be changed without an error. Some programming languages have different ways to create constants that prevent the user from changing the value.
  1. Slicing Strings
  2. You can have your coding grab one character or a sequence of characters.
  3. You supply a starting position and an ending position. Every element between the two points becomes part of the string.
  4. Run Pizza Slicer

word=”pizza”

print(word[0:5]) #prints pizza

print(word[1:3]) # prints iz

print(word[-4:-2]) # prints iz

print(word[-4:3]) # prints iz

print(word[::-1] #azzip (shows word backwards)

0 1 2 3 4 5

p / i / z / z / a

-5 -4 -3 -2 -1

Strings Worksheet 1Name______

phrase=”This is a sentence.”

State the value of the variable on the left.

1. x=len(phrase)1. ______

2. y=phrase[0]2. ______

3. z=phrase[5]3. ______

4. letter=phrase[-1]4. ______

5. letter1=phrase[-3]5. ______

6. letter2=phrase[12]6. ______

7. if “i” in phrase:7. ______

print(“I in message”)

else:

print(“I not in message”)

Concatenating Strings

first=”John”

last=”Smith”

middle=”Pete”

8. name=first + “ “ + middle + “ “ + last8. ______

phrase2=”This is a string”

9. x=len(phrase2)9. ______

10. part1=phrase[0:6]10. ______

11. part2=phrase[10:16]11. ______

12. part3=phrase[10:15]12. ______

13. part5=phrase[::-1]13. ______

Try the following in IDLE. Write down the output.

string1=”Python is fun”

print(string1[:9:2])

print(string1[::5])

print(string1[2:6:2])

print(string1[3:12:4]

Explain what each number represents in the slice.

  1. Tuples
  2. Sequence of values. Indexed by integers 0,1,2,…
  3. Can contain elements of any type. Immutable(can not change contents)
  4. To create a tuple, you surround a sequence of values, separated by commas, with parenthesis. Ex. Inventory=() #creates an empty tuple
  5. <variable>=(item_0, item_1, …)
  6. mixed=(“Monday”, 1, 2, “Tuesday”) #holds mixed data types.
  7. When listing only one item, a commas is need after item.
  8. Name=(“John”,)

g. Printing a tuple use keyword print ( tuple name). ex. print(inventory)

Practice:

1. Create a tuple named numbers that holds the numbers 1-7.

2. Create a tuple named friends that holds five of your friend’s names.

3. Write coding that adds tuple1 to tuple 2 and prints out the result.

tuple1=(1,2,3)

tuple2=(4,5,6)

Look at Program Heros Inventory

h. As a condition an empty tuple is false. A tuple with at least one element is True.

i. Printing a tuple use keyword print ( tuple name). ex. print(inventory)

  1. len() function works the same with tuples as strings.
  2. Indexing tuples- same as string . First item in tuple is position 0.
  3. Slicing –same as strings
  4. Concatenating tuples- use + to join them
  5. Min function of tuple, returns lowest value
  6. Max function of tuple, returns highest value.
  7. Ex. numTuple=(200, 3, 25, -5)

min(numTuple) #returns -5

max(numTuple) # returns 200

p. Used to process lots of data and for data that will not be modified.

Open Word Jumble

1. What is the name of the tuple and what did it store?

2. How does the loop work?

3. What line of coding generates a random position in the word?

4. How is the new word created?

End of Unit Programs- You must complete programs 1-3. For a score above a 90, you must complete a 4th program.

1. Create a program that gets a message from the user and then prints it out backwards.

2. HangMan. Create a game where the computer picks a random word and the player has to guess the word. Choose a category for your word bank. Show the category to the user. The computer tells the player how many letters are in the word. Then the player gets five chances to ask if a letter is in the word. The computer can only respond with “yes” or “no”. At the end of the five guesses, the player must guess the word. The computer either says “Yes you got it right” or “Better luck next time, the word was…”. Store your word bank in a tuple.

3. Create a SumNumbers program that calculates the sum of a range of numbers entered by the user and displays an expression such as : 1 + 2 + 3 …= sum. The user should enter in the starting value and the ending value and then show the sum. For example if the starting value was 10 and ending value was 15 the expression 10 + 11 + 12 + 13 + 14 + 15= 75 would be displayed.

4. Write a nested for loop application that shows the multiplication tables for the numbers 2, 3, 4. It should show the table for those values multiplied by the numbers 1 through 10. Display format is up to you.

5. Factorial. Write an application that finds the factorial of a number.Example output below.

3!= 3 * 2* 1=6

5!= 5*4*3*2*1=120

6. Odd Number Sum- Create an Odd Number sum application that displays the sum of the odd numbers from 1 to a maximum value entered by the user.