Week 4
Control - while and for
Last updated
acceptance = "" # Keep track of condition
print("I know these python classes are the highlight of your week!")
while (acceptance != "It's true"):
acceptance = input("Confess! ")password = "hello"
user_pass = input("Please enter your password")
remaining_attempts = 3
while (user_pass != password) and (remaining_attempts > 0):
user_pass = input("Try again: ")
remaining_attempts = remaining_attempts - 1# Remove all 4 limbs
limbs_remaining = 4
while limbs_remaining > 0: # Run until the blacknight dies
print("Come on then!")
limbs_remaining = limbs_remaining - 1 # Increment the counter
print("We'll call it a draw")my_list = ['She', 'sells', 'sea', 'shells']
index = 0 # "counter" to keep track of index
# Loop through our list
while index < len(my_list):
print(my_list[index])
index = index + 1# We can use for loops to get things directly from a list
for item in ["Python", "classes", "ftw"]:
print(item)my_dict = {"hi" : 1, "fish" : "frog"}
# Can also use for loops to loop through dictionaries
for thing in my_dict: # gives same as my_dict.keys()
print(thing)for num in range(2, 6):
print(num)
# prints 2 3 4 5numbers = list(range(2,14)) # Create a list of integers
print(numbers)# Print even numbers <= 20
for num in range(0, 20):
if num % 2 == 0:
print(str(num) + " is an even number")# Better way to print even numbers <= 20
for num in range(0, 10):
print(str(num * 2))my_list = ['Size', 'doesn\'t', 'matter']
size = len(my_list) # size = 3# Another example - a duplicate search
sentence = ['She', 'sells', 'sea', 'shells', 'on', 'the', 'sea', 'shore']
# Use indices explicitly, to avoid checking the same word against itself
for i in range(len(sentence)):
for j in range(len(sentence)):
if (i != j) and (sentence[i] == sentence[j]):
print(sentence[i] + " is duplicated!")