[英]Python Guessing game
我是使用2.7.11的python初学者,我做了一个猜谜游戏。 到目前为止,这是我的代码
def game():
import random
random_number = random.randint(1,100)
tries = 0
low = 0
high = 100
while tries < 8:
if(tries == 0):
guess = input("Guess a random number between {} and {}.".format(low, high))
tries += 1
try:
guess_num = int(guess)
except:
print("That's not a whole number!")
break
if guess_num < low or guess_num > high:
print("That number is not between {} and {}.".format(low, high))
break
elif guess_num == random_number:
print("Congratulations! You are correct!")
print("It took you {} tries.".format(tries))
playAagain = raw_input ("Excellent! You guessed the number! Would you like to play again (y or n)? ")
if playAagain == "y" or "Y":
game()
elif guess_num > random_number:
print("Sorry that number is too high.")
high = guess_num
guess = input("Guess a number between {} and {} .".format(low, high))
elif guess_num < random_number:
print("Sorry that number is too low.")
low = guess_num
guess = input("Guess a number between {} and {} .".format(low, high))
else:
print("Sorry, but my number was {}".format(random_number))
print("You are out of tries. Better luck next time.")
game()
您可以像这样创建一个静态变量: game.highscore = 10
您可以在game
函数中添加best_score
参数:
def game(best_score=None):
...
elif guess_num == random_number:
print("Congratulations! You are correct!")
print("It took you {} tries.".format(tries))
# update best score
if best_score is None:
best_score = tries
else:
best_score = min(tries, best_score)
print("Best score so far: {} tries".format(best_score))
play_again = raw_input("Excellent! You guessed the number! Would you like to play again (y or n)? ")
if play_again.lower() == "y":
game(best_score) # launch new game with new best score
...
在代码的开头(在定义函数之前),添加全局变量best_score(或任何您想调用的变量),并将其初始化为None:
best_score = None
在检查数字是否正确时,可以检查best_score的尝试次数,并相应地进行更新:
elif guess_num == random_number:
global best_score
# check if best_score needs to be updated
if best_score == None or tries < best_score:
best_score = tries
print("Congratulations! You are correct!")
print("It took you {} tries.".format(tries))
# print out a message about the best score
print("Your best score is {} tries.".format(best_score))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.