首页 > 解决方案 > Python3.7 input() 连接整数

问题描述

我有以下python代码。

a = input("Enter first number") # 2
b = input("Enter second number") # 3

c = a+b # 23 instead of 5
print(c) # prints out 23 why?

我正在使用以下命令来运行 python:

python3.7 filename.py 

不是添加两个数字而是连接两个数字并给我 23 而不是 5,即使我使用的是 python3.7。

我读到的每个答案都说它评估并返回正确的类型:

https://www.quora.com/What-is-the-difference-between-raw_input-and-input-in-Python#

标签: python

解决方案


a+b连接字符串作为input返回字符串。您需要显式类型转换才能使用int()函数将输入转换为整数。

a = int(input("Enter first number")) 
b = int(input("Enter second number"))

推荐阅读