简体   繁体   English

Python用户输入和数学运算错误

[英]Python user input and mathematical operation error

>>> g = input("Enter a number")
Enter a number43
>>> g + 2
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    g + 2
TypeError: Can't convert 'int' object to str implicitly

The program wont let me use the input variable in mathematical operations, like g + 2 该程序不会让我在数学运算中使用输入变量,例如g + 2

In python 3, input() returns a string type even if you input a number. 在python 3中,即使您输入数字, input()也会返回字符串类型。 Thus, you're trying to add an integer with a string 因此,您正在尝试添加带有字符串的整数

You need to convert it to an integer type by using int() : 您需要使用int()将其转换为整数类型:

g = int(input("Enter a number"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM