Download presentation
Presentation is loading. Please wait.
Published byMargaret Curtis Modified over 8 years ago
2
See pages 65 – 67 in your book While loops are all around us ◦ Shampoo Rinse, Lather, Repeat While (Condition Is True) : ◦ Execute a block of code While loops are controlled by a sentry value
3
Make sure the sentry value can evaluate to True, otherwise the while block will never run Make sure the sentry value can evaluate to False, otherwise the program will never end, resulting in an ‘endless loop’
4
hungry = True while(hungry == True) : print("Taking a bite") response = input("Still hungry? (y or n)") if (response == "n") : hungry = False print("Well, that was a good hamburger")
5
secretPassword = “taylorSwift” guessedPassword = “” while (guessedPassword != secretPassword) : guessedPassword = input(“Enter password: ”) if (guessedPassword != secretPassword) : print(“Password incorrect. Try again.”) print(“Password is correct”)
6
# if statement # if ( ) : # Only executed if condition is true # block A is executed else : # Only executed if condition is false block B is executed # while loop # while ( ) : # Executes over and over as long # as condition evaluates to true block C is executed
7
# Parent and two-year-old conversation simulator # response = input(“Why won’t you eat your carrots?”) while (response == ‘Because’) : response = input(‘Because why?’) print(‘The real reason: ’, response)
8
A ‘for loop’ iterates over a sequence one element at a time A ‘for loop’ uses uses a variable that gets each successive element of the sequence Inside the loop body, the loop can then do something with each successive element
9
Start with a ‘for’, followed by a variable for each element, followed by ‘in’ Sometimes you need to count. Python provides the range() function for i in range(1, 5) : print(i) Output: 1 2 3 4
10
for letter in ‘Python’ : print(letter) Output: P y t h o n
11
Write the Python code that uses a while loop to print even numbers between 100 and 200 Now print the even numbers between 100 and 200 using a for loop Write the Python code that uses a for loop to print each character of “Taylor Swift” on a separate line. Use a for loop
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.