Discuss / Python / python3.x里面用户输入的变量不能直接参与计算吗?

python3.x里面用户输入的变量不能直接参与计算吗?

Topic source

Muretto

#1 Created at ... [Delete] [Delete and Lock User]

变量为*input()*用户输入后计算得不到结果,是什么原因呢?

num=input()

print(200+num)

运行代码:

#我输入20后提示错误

20

Traceback (most recent call last):

*  File "D:\work\Formula.py", line 2, in <module>*

*    print(200+num)*

TypeError: unsupported operand type(s) for +: 'int' and 'str'

然而固定的一个数值却可以得出正确结果:

num=100

print(200+num)

变量input()不能直接参与计算吗?

因为你输入的数据没有转换类型,你输入之后是字符串类型,和整型数据类型不同,不能相加

Muretto

#3 Created at ... [Delete] [Delete and Lock User]

谢谢指点!按你的提示找到了相关资料,然后重新改了一下测试成功了!

num=input('请输入一个数字')

num=int(num)

print(200+num)

Muretto

#4 Created at ... [Delete] [Delete and Lock User]

描述

int() 函数用于将一个字符串或数字转换为整型。

语法

以下是 int() 方法的语法:

class int(x, base=10)

  • 1

Reply