以前的答案是正確的,因爲簡單的修正是將輸入強制轉換爲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'
我希望這可以幫助你理解不只是如何解決錯誤,但錯誤是從什麼開始的。
您不能將'str'乘以另一個'str'或'float'或'byte'。你只能用'int'乘以'str'。 –
男人,我不明白爲什麼老師讓你在學習代碼時使用像Pycharm這樣的東西。我可以完全理解用於學習Java,C++等語言的IDE,但是如果您正在學習* Python *,有時候我認爲文本編輯器/終端在開始時是一個很好的組合。 –