如何包括一个用于计算猜测数字的函数?

huangapple go评论66阅读模式
英文:

How can I include a function to count the guessing number?

问题

以下是代码部分的中文翻译:

def main():
  print("********* 欢迎来到猜数字游戏 *********")
  run_game()
  play_again()

def run_game():
  # 导入随机模块
  import random
  # 生成一个随机数
  n = random.randrange(1, 100)
  # 用户猜测随机数
  guess = int(input("请输入任意数字:"))
  count = 1  # 用于计数猜测次数的变量
  while n != guess:
    if guess < n:
      print("太低了")
      guess = int(input("再次输入数字:"))
      count += 1  # 每次猜测后增加计数
    elif guess > n:
      print("太高了!")
      guess = int(input("再次输入数字:"))
      count += 1  # 每次猜测后增加计数
    else:
      break
  print("你猜对了!")
  print(f"你猜了{count}次")

def play_again():
  while True:
    retry = input("你想再玩一次吗?:")
    if retry == "是":
      main()
    if retry == "否":
      print("好游戏!下次你赢不了我!")
      break
    else:
      print("请输入是或否")

main()

希望这对你有所帮助。如果有任何其他问题,请随时告诉我。

英文:

Instructions for the program:

Write a program that generates a random number in the range of 1 through 100, and asks the user to guess what the number is. If the user’s guess is higher than the random number, the program should display “Too high, try again.” If the user’s guess is lower than the random number, the program should display “Too low, try again.” If the user guesses the number, the application should congratulate the user and generate a new random number so the game can start over. The game needs to keep count of the number of guesses that the user makes. When the user decides to stop playing, the number of correct guesses should be displayed.

So far I've completed most of the code, I'm just missing a function to count the guessing times


def main():
  print(&quot;********* Welcome to the random number guessing game *********&quot;)
  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(&quot;Enter any number: &quot;))
  while n!= guess:
    if guess &lt; n:
        print(&quot;Too low&quot;)
        guess = int(input(&quot;Enter number again: &quot;))
    elif guess &gt; n:
        print(&quot;Too high!&quot;)
        guess = int(input(&quot;Enter number again: &quot;))
    else:
      break
  print(&quot;you guessed it right!!&quot;)
def play_again():
    while True:
        retry = input(&quot;Would you like to play again?: &quot;)
        if retry == &quot;yes&quot;:
            main()
        if retry == &quot;no&quot;:
            print(&quot;Good game! Next time you won&#39;t beat me!&quot;)
            break
        else:
            print(&quot;Please enter either yes or no&quot;)

main()

答案1

得分: 0

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

guess = int(input("输入任何数字:"))
count_guessing=0 ### 在您的代码中添加新行 #####
while n!= guess:
    if guess < n:
        print("太低了")
        count_guessing+=1 ### 在您的代码中添加新行 #####
        guess = int(input("再次输入数字:"))
    elif guess > n:
        print("太高了!")
        count_guessing+=1 ### 在您的代码中添加新行 #####
        guess = int(input("再次输入数字:"))
    else:
        print(count_guessing)
      break
英文:

Actually you can write code in better way, Anyway just you have add line in your code

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

答案2

得分: 0

以下是代码部分的中文翻译:

import random  # 最好在文件顶部只导入一次

def main():
    while True:
        run_game()
        retry = input("你想再玩一次吗?:").lower()  # 接受大写字母
        if retry in ["y", "yes"]:  # y 也可以
            pass
        if retry in ["n", "no"]:
            print("好游戏!下次你不会赢我!")
            break
        else:
            print("请只输入是或不是")

def run_game():
    print("********* 欢迎来到随机数猜谜游戏 *********")
    n = random.randrange(1, 101)  # 注意randrange不包括结束点
    guess = int(input("输入任何数字:"))
    num_guesses = 1  # 这是猜测的次数
    while n != guess:
        if guess < n:
            print("太低了")
        elif guess > n:
            print("太高了!")
        else:
            break
        guess = int(input("再次输入数字:"))
        # TODO 处理num_guesses

    print(f"你猜对了,你猜了{num_guesses}次!!")

if __name__ == '__main__':  # 只有在运行这个文件时才调用main
    main()

希望这有助于你的理解。如果有任何问题,请随时提出。

英文:

Counting the number of guesses is easily done with a variable that exists as long as the game is running. For each guess, it needs to be incremented.

As this is obviously a homework question, please take a moment to think how you can apply this to your code before reading on.

Thank you. I'm also not going to post a complete answer but it should be obvious what to do to make it work.

I took the liberty of restructuring your code somewhat. Don't just copy and paste it as is but try to understand what I changed and why.

The issues I tried to address are:

  • Recursive call: main calls play_again calls main calls play_again etc. None of these return until you quit the program. This may (if you play a lot) cause python to raise an exception. I eliminated play_again.
  • Move import to top of the file. This is where it's usually done in python.
  • Fix range. random.randrange excludes the end point (as opposed to random.randint, which does)
  • Play again? also accepts single letter answers ('y' or 'n') as well as capital letters.

So here's my take on your code:

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


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


def run_game():
    print(&quot;********* Welcome to the random number guessing game *********&quot;)
    n = random.randrange(1, 101)  # note that randrange does *not* include the end point
    guess = int(input(&quot;Enter any number: &quot;))
    num_guesses = 1  # this is the number of guesses
    while n != guess:
        if guess &lt; n:
            print(&quot;Too low&quot;)
        elif guess &gt; n:
            print(&quot;Too high!&quot;)
        else:
            break
        guess = int(input(&quot;Enter number again: &quot;))
        # TODO do something with num_guesses

    print(f&quot;you guessed it right, it took you {num_guesses} guesses!!&quot;)


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

huangapple
  • 本文由 发表于 2023年4月4日 13:28:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/75925791.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定