繁体   English   中英

如何重复操作直到在Python中完成

[英]How to repeat an action until it is completed in Python

from random import randint
guessed = randint(0,2)
user_guess = input("What do you think the number I'm thinking of is?")

if user_guess == guessed:
    print("Correct!")
else:
    print("Incorrect!")

我正在寻找一种重复代码的方式,或者一种打印不同消息的方式,直到user_guess与猜测的相同。

如果对方猜错了,我希望能够告诉他们,然后再给他们一次机会。

谢谢,很抱歉初学者的问题。

使用while循环。

from random import randint
correct = False
while (not correct): 
     guessed = randint(0,2)
     user_guess = int(input("What do you think the number I'm thinking of is?"))
     if user_guess == guessed: 
          print("Correct!")
          correct = True
     else: 
          print("Incorrect!")

只要猜测是错误的,就停留在while循环中。 您需要第一个猜测来“启动”循环。

# get the first user guess

while user_guess != guessed:
    print "Incorrect"
    # Get next user guess

请注意,“下一个用户猜测”的代码与“第一个用户猜测”非常相似。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM