当我尝试比较两个整数时,我得到一个int错误。说它不能比较int型和字符串,但我将输入(字符串)转换为int型。有人能解释一下为什么会这样吗?
我尝试将userInput转换为int(input(PROMPT)),然后返回userInput。然后我尝试将我的computerChoice与userInput进行比较,并得到一个错误。
def userInput():
userInput = int(input(PROMPT))
return userInput
完整代码如下:Python3顺便说一句:
PROMPT = "Please enter an integer: "
WELCOME = "THE GUESSING GAME"
#get input
def userInput():
userInput = int(input(PROMPT))
return userInput
#get computer guess
def computerGuess():
import random
computerGuess = (int)(random.random()*6)
return computerGuess
def game(userInput, computerInput):
while userInput != computerInput:
print("Try again")
userInput()
if userInput == computerInput:
print("You win!!")
def main():
#get user Input in main
theInput = userInput()
#computer input
computer = computerGuess()
#launch game
game(theInput, computer)
main()
您在game
函数中为表示用户输入(userInput
)的参数选择的名称与捕获用户输入的函数名称相同。因此,在game
函数的范围内,userInput
是整数,但是当您尝试将其用作函数时(并且int
类型不可调用)。
此外,userInput()
函数的返回值不用于更新变量userInput
的值,因此,如果用户提供的第一个值与computerInput
不同,则循环将永远继续下去。
如果您更改game
函数中参数的名称并更新用户提供的值,程序将按预期工作:
def game(user_input, computer_input):
while user_input != computer_input:
print("Try again")
user_input = userInput()
if user_input == computer_input:
print("You win!!")
否则,你可以稍微改变一下你的代码,从游戏函数的参数中删除用户输入:
def game(computer_input):
while userInput() != computer_input:
print("Try again")
print("You win!!")
显然,您还必须从main
函数中删除theInput = userInput()
。实际上,您可以去掉main函数,直接使用game
函数:
game(computerGuess())
然而,userInput
和computerGuess
函数中变量名的选择也是不明智的:你应该避免在函数中使用相同的函数名来命名变量,因为这会造成混淆,使你的代码更容易出错。
另一个建议:你可以很容易地通过限制值的范围来改进你的程序:例如,生成一个1到10之间的随机整数,然后让用户猜它。你可以修改computerGuess
,使用random.randint
代替random.random
,并添加一个检查,不允许用户输入范围[1;10]。