我正在使用python 2.7.1
我希望能够根据用户输入重新启动游戏,因此可以选择重新启动,而不是退出游戏并再次打开。 有人可以帮我搞清楚吗?谢谢
import random
the_number = random.randrange(10)+1
tries = 0
valid = False
while valid == False:
guess = raw_input("\nTake a guess: ")
tries += 1
if guess.isdigit():
guess = int(guess)
if guess >= 1 and guess <= 10:
if guess < the_number:
print "Your guessed too low"
elif guess > the_number:
print "Your guessed too high"
elif tries <= 3 and guess == the_number:
print "\n\t\tCongratulations!"
print "You only took",tries,"tries!"
break
else:
print "\nYou guessed it! The number was", the_number,"\n"
print "you took",tries,"tries!"
break
else:
print "Sorry, only between number 1 to 10"
else:
print "Error,enter a numeric guess"
print "Only between number 1 to 10"
if tries == 3 and guess != the_number:
print "\nYou didn't guess the number in 3 tries, but you still can continue"
continue
while tries > 3 and guess != the_number:
q = raw_input("\nGive up??\t(yes/no)")
q = q.lower()
if (q != "yes") and (q != "no"):
print "Only yes or no"
continue
if q != "no":
print "The number is", the_number
valid = True
break
else:
break
答案 0 :(得分:3)
将当前代码放在函数中,例如play_game
或其他任何函数。然后编写一个调用该函数的循环,直到用户已经足够。例如:
def global_thermonuclear_war():
print "Boom!"
while raw_input("Shall we play a game? [y|n] ") == 'y':
global_thermonuclear_war()
答案 1 :(得分:1)
添加变量,将其命名为continue
,并将其初始化为true
。然后将整个事物包裹在while(continue)
循环中,并在循环结束时打印play again?
并接受用户输入,根据他们的答案设置continue
。
答案 2 :(得分:0)
while True:
play_guessing_game()
user = raw_input("Play again? (Y/n) ")
again = "yes".startswith(user.strip().lower())
if not again:
break
...“是”.startswith()位使其接受“Ye”或“yeS”之类的输入或只是按Enter键。