如果python中的语句没有打印

E. *_*ham 4 python if-statement python-3.x

我正在为学校工作,这个程序很容易,但我的if语句不能正常工作.有人知道为什么吗?这是代码:

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:")
Run Code Online (Sandbox Code Playgroud)

输出是:

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:
Run Code Online (Sandbox Code Playgroud)

Mik*_*ler 5

我会写这样的东西:

# 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
Run Code Online (Sandbox Code Playgroud)

我改变了一些事情:

  1. 而不是if我使用的那么多陈述if letter in common_letters:.这允许您只需添加矿石删除​​另一个字母common_letters.

  2. input(prompt).strip()用来剥去额外的空白区域.

  3. while True如果没有输入常用字母,我会一次又一次地使用循环来重复这个问题.该break终止这个循环,即在编程'完成.