【问题标题】:Trying to make answer repeat [duplicate]试图让答案重复[重复]
【发布时间】:2019-10-18 01:27:35
【问题描述】:

如果输入的答案不正确,我会尝试重复问题。

answer = raw_input("Please enter the capital of Canada")
Times = 0

if answer == "Ottawa":
    print "good you made " + str(Times) + " attempts"
    print "you know Canadian Geography"
else:
    Times = Times + 1
    print "Please take another Canadian Geography course."

【问题讨论】:

标签: python loops


【解决方案1】:

你会想要一个while 循环。

Times = 0

while True:
    answer = raw_input("Please enter the capital of Canada")

    if answer == "Ottawa":
        print "good you made " + str(Times) + " attempts"
        print "you know Canadian Geography"
    else:
        Times = Times + 1
        print "Please take another Canadian Geography course."

这将创建一个无限循环,因此您可能需要一些停止条件,例如用户回答错误 10 次。

Times = 0
StopTimes = 10

while True:
    answer = raw_input("Please enter the capital of Canada")

    if answer == "Ottawa":
        print "good you made " + str(Times) + " attempts"
        print "you know Canadian Geography"
    else:
        Times = Times + 1
        print "Please take another Canadian Geography course."

    if Times > StopTimes:
        break

【讨论】:

    【解决方案2】:

    与 Eric 的回答类似,但当他们做对时,这个循环就会中断。

    注意 python3 使用 input 而不是 raw_input。

    answer=raw_input("Please enter the capital of Canada:")
    
    attempts=1
    flag=True
    while flag:
        if answer=="Ottawa":
            print("Good, you made %d attempts"%attempts)
            flag=False
        else:
            attempts += 1
            answer=raw_input("Please take another attempt, enter the capital of Canada:")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-08
      • 1970-01-01
      • 2015-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多