带循环的Python随机数猜测问题
我已经建立了一个随机数猜测游戏的实践,但我有一些麻烦与最后的步骤。当输出时,游戏按预期运行,但是,我希望它询问用户是否希望在每次猜回合后再次玩,其中“是”表示游戏继续进行,“退出”表示游戏停止。到目前为止,游戏要求用户猜测数字,如果所说的数字不匹配,则告诉用户,然后询问他们是否想玩,然后它只重复猜测部分,而不询问用户是否想再次玩。这不是我想要的,因为我想知道如何正确地编写这段代码。 这是我的节目:带循环的Python随机数猜测问题,python,python-3.x,loops,random,input,Python,Python 3.x,Loops,Random,Input,我已经建立了一个随机数猜测游戏的实践,但我有一些麻烦与最后的步骤。当输出时,游戏按预期运行,但是,我希望它询问用户是否希望在每次猜回合后再次玩,其中“是”表示游戏继续进行,“退出”表示游戏停止。到目前为止,游戏要求用户猜测数字,如果所说的数字不匹配,则告诉用户,然后询问他们是否想玩,然后它只重复猜测部分,而不询问用户是否想再次玩。这不是我想要的,因为我想知道如何正确地编写这段代码。 这是我的节目: import random guess = int(input("Gu
import random
guess = int(input("Guess the number => "))
rand = random.randrange(1,10)
print("The number was", rand)
def guess_rand(guess, rand):
if rand == guess:
print("You have guessed right!")
elif rand > guess:
print("You guessed too low!")
elif guess > rand:
print("You guessed too high!")
guess_rand(guess, rand)
again = input("Would you like to try again? => ")
while again.lower() == 'yes':
guess = int(input("Guess the number => "))
rand = random.randrange(1,10)
print("The number was", rand)
guess_rand(guess, rand)
if again.lower() == 'exit':
break
此外,如果有任何关于如何记录用户猜测次数的提示,以及在游戏结束时打印出来,我将不胜感激。谢谢。您缺少在
循环中再次获取用户输入的语句:
again = input("Would you like to try again? => ")
while again.lower() == 'yes':
guess = int(input("Guess the number => "))
rand = random.randrange(1,10)
print("The number was", rand)
guess_rand(guess, rand)
again = input("Would you like to try again? => ")
if again.lower() == 'exit':
break
为了保持计数,您可以在while
循环中添加一个新变量和增量。这是您要求的,我还添加了跟踪玩家的回合
import random
turns = 0
def quit():
i = input ("Do you want to play again? if yes enter Yes if not Enter No\n")
if (i.lower() not in ["yes","no"]):
print ("Invalid input")
return True
if (i.lower() == "yes"):
print ("You choose to play")
return False
else:
print ("Thankyou for playing")
return True
while True:
guess = int(input("Guess the number => "))
rand = random.randrange(1,10)
print("The number was", rand)
def guess_rand(guess, rand):
if rand == guess:
print("You have guessed right!")
elif rand > guess:
print("You guessed too low!")
elif guess > rand:
print("You guessed too high!")
guess_rand(guess, rand)
if quit():
print("You have used",turns,"trun(s)")
break
else:
turns += 1
continue
谢谢,我能完成我所遇到的两个问题。