The Magic Word ๐ช
while loops are perfect for asking a question until you get the answer
you want. A for loop can't do this โ you have no idea how many guesses
someone will need!
answer = ""
while answer != "banana":
answer = input("Say the magic word: ")
print("๐ You said it!")
Here's the trick: you have to give answer a starting value before the
loop, or Python doesn't know what to compare on the very first check. An
empty string "" is perfect โ it's definitely not the magic word, so the
loop is guaranteed to run at least once.
Each turn, input() replaces answer with whatever they typed. The moment
it matches, the comparison turns False and the loop lets go.
Your mission
- Make a variable
magic_wordwith your secret word, and a variableguessthat starts out empty:guess = "" - Write a
whileloop that keeps callinginput()untilguessmatchesmagic_word - Inside the loop, use an
ifto tease them when the guess is wrong - After the loop, print a big celebration
Run it and get it wrong a few times on purpose. That's the whole point! ๐
Your code
Press โถ Run to see what your code does!