基本python cod中的错误

2024-05-13 00:10:47 发布

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

所以我今天才开始学Python。尝试了一个basic程序,但收到一个错误“cannot convert int object to str implicity”

userName = input('Please enter your name: ' )
age = input('Please enter your age: ')

factor = 2
finalAge = age + factor  **ERRORS OUT ON THIS LINE**
multAge = age * factor
divAge = age / factor


print('In', factor, 'years you will be', finalAge, 'years old', userName )
print('Your age multiplied by', factor, 'is', multAge )
print('Your age divided by', factor, 'is', divAge )

当我输入int(age)+factor,而不是age时,它就完美地工作了。但是作者说python在输入变量类型时会自动检测它。所以在这种情况下,当我输入age=20时,那么age应该自动变成整数,对吗?在

期待任何帮助!!在


Tags: inputageyourbyusernameintprintenter
3条回答

Python不知道您要进行什么操作,前提是“+”运算符既可以用于连接字符串,也可以用于添加数字。在

所以,它不知道你是否想这么做

finalAge = int(age) + factor   #finalAge is an integer

或者

^{pr2}$

你需要显式地转换你的变量,这样它就不会模棱两可了。在

在您的例子中,int(age)返回一个整数,这是获得所需内容的正确方法。在

您的问题是input返回一个字符串(因为通常,来自命令行的输入是文本)。您可以像您所做的那样将其转换为int来删除错误。在

Python只会自动检测程序中没有类型的变量的类型-它不会自动将类型化变量转换为不同的类型。在

doc

The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.

如您所见,python3+中的input()函数通过转换给定的任何输入返回一个字符串,就像python2.x中的raw_input()

因此,age显然是一个字符串。在

不能添加带有整数的字符串,因此会出现错误。在

can't convert int object to str implicity

int(age)age转换为一个整数,因此它适用于您的情况。在

你能做什么:

使用:

age = int(input('Please enter your age: '))

将输入显式转换为整数。在

相关问题 更多 >