来自用户的输入

问题描述:

Python是获取用户输入的一个非常基本的疑问,Python是否将任何输入作为字符串并将其用于计算,我们必须将其更改为整数或什么?在下面的代码:来自用户的输入

a = raw_input("Enter the first no:") 
b = raw_input("Enter the second no:") 


c = a + b 
d = a - b 
p = a * b 
print "sum =", c 
print "difference = ", d 
print "product = ", p 

Python中给出以下错误:

Enter the first no:2 
Enter the second no:4 

Traceback (most recent call last): 
File "C:\Python27\CTE Python Practise\SumDiffProduct.py", line 7, in <module> 
d=a-b 
TypeError: unsupported operand type(s) for -: 'str' and 'str' 

谁能告诉请为什么我收到此错误?

+0

用户输入是字符串。在执行操作之前使用int()。 – Sudipta

是的,每个输入都是字符串。但只是尝试:

a = int(a) 
b = int(b) 

之前你的代码。

但是请注意,用户可以通过raw_input传递他喜欢的任何字符串。安全的方法是try/except块。

try: 
    a = int(a) 
    b = int(b) 
except ValueError: 
    raise Exception("Please, insert a number") #or any other handling 

所以它可能是这样的:

try: 
    a = int(a) 
    b = int(b) 
except ValueError: 
    raise Exception("Please, insert a number") #or any other handling 
c=a+b 
d=a-b 
p=a*b 
print "sum =", c 
print "difference = ", d 
print "product = ", p 

documentaion

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

是的,你是你需要输入从string更改为整数正确的思想。

a = raw_input("Enter the first no: ")替换为a = int(raw_input("Enter the first no: "))

请注意,如果给定的输入不是整数,将会产生ValueError。请参阅this以了解如何处理此类异常(或使用isnumeric()检查字符串是否为数字)。

此外,要注意的是你,虽然你可能会发现,与input更换raw_input可能的工作,这是一个糟糕和不安全的方法,因为在Python 2.x中它评估输入(尽管在Python 3.x的raw_input被替换为input )。因此

实施例的代码可以是:

try: 
    a = int(raw_input("Enter the first no: ")) 
    b = int(raw_input("Enter the second no: ")) 
except ValueError: 
    a = default_value1 
    b = default_value2 
    print "Invalid input" 

c = a+b 
d = a-b 
p = a*b 
print "sum = ", c 
print "difference = ", d 
print "product = ", p 

raw_input()存储从用户输入的串作为汽提后新行字符后一个“串格式”(当你按下回车键)。您正在使用字符串格式的数学运算,这就是为什么要获取这些错误,首先使用a = int(a)b = int(b)将您的输入字符串转换为某个int变量,然后应用这些操作。

a = input("Enter integer 1: ") 
b = input("Enter integer 2: ") 

c=a+b 
d=a-b 
p=a*b 
print "sum =", c 
print "difference = ", d 
print "product = ", p 

只要使用input(),您将得到正确的结果。 raw_input以字符串形式输入。

还有一个我想补充.. 为什么要使用3个额外的变量?

试试看:

print "Sum =", a + b 
print "Difference = ", a - b 
print "Product = ", a * b 

不要使代码复杂。