如何包含一个函数来计算猜测数



程序说明:

编写一个程序,生成一个从1到100的随机数,并要求用户猜测这个数字是什么。如果用户的猜测高于随机数,程序应该显示"太高,再试一次"。如果用户猜测低于随机数,则程序应该显示"太低,再试一一次",应用程序应该祝贺用户并生成一个新的随机数,以便游戏可以重新开始。游戏需要记录用户的猜测次数。当用户决定停止播放时,应显示正确猜测的次数。

到目前为止,我已经完成了大部分代码,我只是缺少了一个计算猜测次数的函数


def main():
print("********* Welcome to the random number guessing game *********")
run_game()
play_again() 
def run_game():  
#Importing the random module 
import random
#Generation of a random number
n = random.randrange(1,100)
#User guess the random number 
guess = int(input("Enter any number: "))
while n!= guess:
if guess < n:
print("Too low")
guess = int(input("Enter number again: "))
elif guess > n:
print("Too high!")
guess = int(input("Enter number again: "))
else:
break
print("you guessed it right!!")
def play_again():
while True:
retry = input("Would you like to play again?: ")
if retry == "yes":
main()
if retry == "no":
print("Good game! Next time you won't beat me!")
break
else:
print("Please enter either yes or no")
main()

只要游戏运行,就可以使用一个存在的变量轻松计算猜测次数。对于每个猜测,它都需要递增。

由于这显然是一个家庭作业问题,请花点时间思考如何在阅读之前将其应用于您的代码。

谢谢。我也不会发布一个完整的答案,但应该很清楚该怎么做才能让它发挥作用。

我冒昧地对您的代码进行了一些重组。不要只是照原样复制粘贴,而是试着理解我改变了什么以及为什么。

我试图解决的问题是:

  • 递归调用:main调用play_again调用main调用play_again等。在退出程序之前,这些调用都不会返回。这可能会(如果你经常玩)导致python引发异常。我淘汰了play_again
  • import移动到文件顶部。这是python中通常执行的操作
  • 固定范围。random.randrange排除端点(与random.randint相反,后者确实排除端点)
  • 再次播放?也接受单字母答案('y'或'n')以及大写字母

下面是我对你的代码的看法:

import random  # better do it once, at the top of the file

def main():
while True:
run_game()
retry = input("Would you like to play again?: ").lower()  # accept capital letters
if retry in ["y", "yes"]:  # y is also fine
pass
if retry in ["n", "no"]:
print("Good game! Next time you won't beat me!")
break
else:
print("Please enter either yes or no")

def run_game():
print("********* Welcome to the random number guessing game *********")
n = random.randrange(1, 101)  # note that randrange does *not* include the end point
guess = int(input("Enter any number: "))
num_guesses = 1  # this is the number of guesses
while n != guess:
if guess < n:
print("Too low")
elif guess > n:
print("Too high!")
else:
break
guess = int(input("Enter number again: "))
# TODO do something with num_guesses
print(f"you guessed it right, it took you {num_guesses} guesses!!")

if __name__ == '__main__':  # only call main when you run this file
main()

实际上,你可以用更好的方式编写代码,无论如何,你只需要在代码中添加一行

guess = int(input("Enter any number: "))
count_guessing=0 ### add new line to your code #####
while n!= guess:
if guess < n:
print("Too low")
count_guessing+=1 ### add new line to your code #####
guess = int(input("Enter number again: "))
elif guess > n:
print("Too high!")
count_guessing+=1 ### add new line to your code #####
guess = int(input("Enter number again: "))
else:
print(count_guessing)
break

相关内容

  • 没有找到相关文章

最新更新