计算机产生一个数字,用户猜测数字,不管它总是在什么地方

2024-09-28 03:12:37 发布

您现在位置:Python中文网/ 问答频道 /正文

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

有人能告诉我这个代码有什么问题吗

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


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?"

Tags: toinyouinputifdefarelike
3条回答

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

另一方面,你真的不应该使用全局变量。学习使用returns,尤其是在使用函数时,否则使用函数就毫无意义了

下面是一个示例代码:

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()

当comproll为int时,用户当前输入一个字符串。您可以通过以下方式更改此设置:

user = int(input("Input a number: "))

对我来说,除了输入字段的语法错误外,它还能工作:

def guess_evaluation():

  if user != comproll:
    print("You are incorrect.")
    again = input("Would you like to try again? ")
    if again in("y"): # syntax error here, enter space between "in" and "('y')".
      user_guess()

    elif again in ("n"):
      print("Thanks for playing.")

相关问题 更多 >

    热门问题