我做了一个简单的程序,用户猜测随机生成的计算机编号。为了测试程序是否正常工作,我将生成的计算机值更改为 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()
对我来说
,它有效,除了输入字段中的语法错误:
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.")
当 comproll 是整数时,用户通常会输入字符串。您可以通过以下方式更改此设置:
user = int(input("Input a number: "))