我做了一个猜数游戏,如果你愿意的话,我已经让它重新开始了。 然而,它重新开始,回到开始并再次询问“myname”,我怎么能这样做,以便它回到它想到一个数字的位,并从第一次记住我的名字?
import random
restart = '1'
def main():
guessestaken = 0
print ('Hello, what is your name?')
myname = raw_input()
number = random.randint(1, 50)
print ('Okay ' + myname + ', I am thinking of a number between 1 and 50. You have 5 guesses.')
while guessestaken < 5:
print ('Take a guess.')
guess = input()
guess = int(guess)
guessestaken = guessestaken + 1
if guess < number:
print ('Your guess is too low.')
if guess > number:
print ('Your guess is too high.')
if guess == number:
break
if guess == number:
guessestaken = str(guessestaken)
print ('Good job ' + myname + ', you got the correct answer in ' + guessestaken + ' guesses')
if guess != number:
number = str(number)
print ('Oh dear ' + myname + ', the number I was thinking of was ' + number + '.')
while restart == '1':
main()
restart = raw_input('Would you like to try again? Press 1 for Yes, and 2 for No: ')
此刻它再次要求我的名字。我的意思是,它很实用,很讨厌。
由于
答案 0 :(得分:1)
你可以简单地移动
print ('Hello, what is your name?')
myname = raw_input()
在main()
函数之前,因此它只会运行一次。
您还需要在raw_input()
函数中使用input()
代替main()
。
答案 1 :(得分:0)
最简单的方法是在main()
函数之外询问名称,然后将其传递给每个游戏。从技术上讲,你不必传入它(python仍然可以访问变量),但最好这样做。
def main(myname):
# Remove the name prompt from here
...
print ('Hello, what is your name?')
myname = raw_input()
while restart == '1':
main(myname)
restart = raw_input('Would you like to try again? Press 1 for Yes, and 2 for No: ')
答案 2 :(得分:0)
一个简单的解决方法是将myname
放在main
之外,将myname = ''
放在restart = '1'
之下。然后,只询问玩家姓名,如果他的名字不明,即:
if myname == '':
print ('Hello, what is your name?')
myname = raw_input()