代码工作正常,但我无法弄清楚如何完全重启程序。我把继续放在代码中,我知道这是不正确的,因为我想让它在猜到正确的数字后完全重启,并显示“祝贺!”你在_猜猜中猜到了我的号码。
import random
guesses = 0
number = random.randint(1, 100)
print('I am thinking of a number between 1 and 100.')
while guesses < 100:
guess = int(input('Guess? '))
guesses = guesses + 1
if guess < number:
print('Your guess is too low.')
if guess > number:
print('Your guess is too high.')
if guess == number:
continue
if guess == number:
guesses = str(guesses)
print('Congratulations! You guessed my number in ' + guesses + ' guesses!')
答案 0 :(得分:0)
所以这样:
while True:
guesses = 0
while guesses < 100:
if guesses == 100:
break
...
if guess == number:
print ...
yorn = input "do you want to try again?")
if yorn == 'n':
break
所以只需将你的代码包装在外面,显然我会跳过你的很多代码
答案 1 :(得分:0)
如果您想继续猜测并自动启动游戏,则需要进行递归调用:
import random
def guess_func():
number = random.randint(1, 100)
guesses = 0
while True:
guess = int(raw_input("Enter your guess: "))
if guess < number:
print('Your guess is too low.')
guesses += 1
if guess > number:
print('Your guess is too high.')
guesses += 1
if guess == number:
print "Congratulations! You guessed my number in [{}] guesses".format(guesses)
print "Let's keep on guessing!"
return guess_func()
guess_func()