如何在python中输入正确之前重复一段程序?

时间:2014-04-03 11:20:24

标签: python loops

我希望我的cade重复,直到玩家猜对了

ghuess=input("state a number between 1-100")
if ghuess>number:
    print "too high try again!"
elif ghuess<number:
    print "too low try again!"
else:
    print "well done! ghuess you have won.."
    time.sleep(1)
    print "3"
    time.sleep(1)
    print "2"
    time.sleep(1)
    print "1"
    time.sleep(1)
    print prize

3 个答案:

答案 0 :(得分:1)

在那里添加while - 循环。这意味着您将无限地循环回答问题,直到您达到满意的结果。

while True:
    ghuess=input("state a number between 1-100")
    if ghuess>number:
        print "too high try again!"
    elif ghuess<number:
        print "too low try again!"
    else:
        # Jackpot, exit the loop.
        break
print "well done! ghuess you have won.."
time.sleep(1)
print "3"
time.sleep(1)
print "2"
time.sleep(1)
print "1"
time.sleep(1)
print prize

答案 1 :(得分:1)

通常使用while循环接近:

while True:
    ... # do your thing
    if finished: # are we done here?
        break # leave
... # execution resumes here after break

答案 2 :(得分:0)

对于没有break的解决方案:

isFound = False
while not isFound:
    ghuess=input("state a number between 1-100")
    if ghuess>number:
        print "too high try again!"
    elif ghuess<number:
       print "too low try again!"
    else:
        isFound = True
        print "well done! ghuess you have won.."
        time.sleep(1)
        print "3"
        time.sleep(1)
        print "2"
        time.sleep(1)
        print "1"
        time.sleep(1)
        print prize