2017-04-24 118 views
0

我這個程序有錯誤。你能幫我解釋一下發生了什麼,因爲系統似乎把我的變量混淆成字符串。我試圖改變變量,但它似乎總是停止工作。爲什麼這段簡單的代碼不起作用

# Area of rectangle 
a = input("What is the length of side a in centimeters") 
b = input("What is the length of side b in centimeters") 
area = a * b 
print(area) 

它給了我這種反應

line 5, in <module> 
    area = a * b 
TypeError: can't multiply sequence by non-int of type 'str' 

鑑於我的業餘編碼狀態,所有我從這個拿的是,它試圖乘那裏有沒有串的字符串。

+0

您不能將'str'乘以另一個'str'或'float'或'byte'。你只能用'int'乘以'str'。 –

+1

男人,我不明白爲什麼老師讓你在學習代碼時使用像Pycharm這樣的東西。我可以完全理解用於學習Java,C++等語言的IDE,但是如果您正在學習* Python *,有時候我認爲文本編輯器/終端在開始時是一個很好的組合。 –

回答

3

以前的答案是正確的,因爲簡單的修正是將輸入強制轉換爲int的值。但是,這個錯誤有點神祕:

TypeError: can't multiply sequence by non-int of type 'str'

並值得加以解釋。

這裏發生了什麼是python理解一個字符串是一個字符序列。甚至對於單個字符也是如此,例如'a'或沒有字符,例如'' - 您通常不會在python中使用底層字符類型。

而且事實證明,在Python中,你可以乘序列 - 列表或元組或一些這樣的 - 由一個數值n重複該序列n次:

>>> [1, 2, 3] * 5 
[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3] 

,所以你可以做這跟弦:

>>> [1, 2, 3] * ['a', 'b', 'c'] 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: can't multiply sequence by non-int of type 'list' 

>>> "abc" * 3 
'abcabcabc' 

,但你不能用另一個序列乘以序列

和預期,我們在嘗試用繩子乘字符串時同樣的錯誤:

>>> "abc" * "def" 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: can't multiply sequence by non-int of type 'str' 

即使兩個字符串看起來像數字:

>>> "6" * "10" 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: can't multiply sequence by non-int of type 'str' 

我希望這可以幫助你理解不只是如何解決錯誤,但錯誤是從什麼開始的。

0
# Area of rectangle 
a = input("What is the length of side a in centimeters") 
b = input("What is the length of side b in centimeters") 
#convert input to int. 
area = int(a) * int(b) 
print(area) 
+0

感謝您的幫助:) – HeatwaVe

1

您需要將輸入轉換爲int/float。

int(a) * int(b) 
+0

感謝您的幫助:) – HeatwaVe

0

input()閱讀給定的數字作爲一個字符串:

input,所以你需要投像這樣返回一個字符串。你要轉換爲數字做任何算術計算之前

a = int(input("What is the length of side a in centimeters")) 
b = int(input("What is the length of side b in centimeters")) 
area = a * b 
print(area) 

OR

a = input("What is the length of side a in centimeters") 
b = input("What is the length of side b in centimeters") 
area = int(a) * int(b) 
print(area) 

注: 可以簡化代碼(如果你想):

a = int(input("What is the length of side a in centimeters")) 
b = int(input("What is the length of side b in centimeters")) 
print(a*b) 
相關問題