2013-08-20 124 views
2

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

回答

2

是的,每個輸入都是字符串。但只是嘗試:

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.

1

是的,你是你需要輸入從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 
0

raw_input()存儲從用戶輸入的串作爲汽提後新行字符後一個「串格式」(當你按下回車鍵)。您正在使用字符串格式的數學運算,這就是爲什麼要獲取這些錯誤,首先使用a = int(a)b = int(b)將您的輸入字符串轉換爲某個int變量,然後應用這些操作。

0
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 

不要使代碼複雜。

相關問題