Skip to main content
 首页 » 编程设计

python之计算机生成一个数字,用户猜测数字,不管怎么猜总是不对

2024年11月24日8bhlsheji

我制作了一个简单的程序,让用户猜测随机生成的计算机号码。为了测试程序是否正常工作,我将生成的计算机值更改为 5。但是,当我“猜”到 5 时,不知何故我仍然不正确。

谁能告诉我这段代码有什么问题吗?

我试着弄乱返回变量,但我不明白返回命令是如何工作的,所以我没有成功。

 
def computer_roll(): 
  global comproll 
  comproll = random.randint(1,3) 
  # comproll = 5 
  user_guess() 
 
def user_guess(): 
  global user 
  user = input("Input a number: ") 
  guess_evaluation() 
 
def guess_evaluation(): 
 
  if user != comproll: 
    print("You are incorrect.") 
    again = input("Would you like to try again? ") 
    if again in("y"): 
      user_guess() 
 
    elif again in ("n"): 
      print("Thanks for playing.") 
 
  elif user == comproll: 
    print("You are correct.") 
    again = input("Would you like to play again? ") 
    if again in("y"): 
      user_guess() 
 
    elif again in ("n"): 
      print("Thanks for playing.") 
 
computer_roll() # Start``` 
 
 
 
# Expected Results:  
 
# When I enter 5 it should say "You are correct." and then "Would you like to play again?" 
 
# Actual Results: 
 
# When I enter 5 it says "You are incorrect" and then "Would you like to play again?" 

请您参考如下方法:

您正在将整数与字符串进行比较,这就是为什么它永远不会正确的原因。 试试,user = int(input("Input a number: "))

旁注,您真的不应该使用全局变量。学习使用返回,尤其是因为您正在使用函数,否则根本没有使用函数的意义。

下面是一个示例代码:

import numpy as np 
import random 
 
def computer_roll(): 
  return random.randint(4,6) 
 
def user_guess(): 
  return int(input("Input a number: ")) 
 
def guess_evaluation(): 
 
  if user_guess() != computer_roll(): 
    print("You are incorrect.") 
  else: 
    print("You are correct.") 
 
  again = input("Would you like to play again? ") 
 
  if again in ("n"): 
    print("Thanks for playing.") 
  else: 
    guess_evaluation() 
 
guess_evaluation()