I am working on an assignment for school, and this program is SUPER easy, but my if statement isn't working properly. Does anybody know why? Here is the code:
letter = input("Name one of the most common letters in wheel of fortune puzzles: ")
if letter == "r":
print(letter, "is one of the most common letters!")
if letter == "s":
print(letter, "is one of the most common letters!")
if letter == "t":
print(letter, "is one of the most common letters!")
if letter == "l":
print(letter, "is one of the most common letters!")
if letter == "n":
print(letter, "is one of the most common letters!")
if letter == "e":
print(letter, "is one of the most common letters!")
else:
print("Incorrect!")
letter = input("Name one of the most common letters in wheel of fortune puzzles: ")
input("\n\nPress the enter key to exit:")
Output is:
Name one of the most common letters in wheel of fortune puzzles: j
Incorrect!
Name one of the most common letters in wheel of fortune puzzles: r
Press the enter key to exit:
I would write something like this:
# Assumes Python 3
# Python 2: Use `raw_input` instead of input
common_letters = 'rstlne'
prompt = "Name one of the most common letters in wheel of fortune puzzles: "
while True:
letter = input(prompt).strip()
if letter in common_letters:
print(letter, "is one of the most common letters!")
break
else:
print("Incorrect!")
answer = input('Type "end" to exit: ')
if answer.strip() == 'end':
break
There are a few thing I changed:
Instead of that many if statements I used if letter in common_letters:. This allows you to just add ore remove another letter to/from common_letters.
I use input(prompt).strip()to strip of extra white space.
I use a while True loop to repeat the question over and over again if no common letter was entered. The break terminates this loop, i.e. the progam is finished.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With