3

私はPythonが初めてで、これが機能しない理由を理解するのに苦労しています。

number_string = input("Enter some numbers: ")

# Create List
number_list = [0]

# Create variable to use as accumulator
total = 0

# Use for loop to take single int from string and put in list
for num in number_string:
    number_list.append(num)

# Sum the list
for value in number_list:
    total += value

print(total)

基本的に、たとえばユーザーに 123 と入力して、1 と 2 と 3 の合計を取得してもらいます。

このエラーが発生しましたが、対処方法がわかりません。

Traceback (most recent call last):
  File "/Users/nathanlakes/Desktop/Q12.py", line 15, in <module>
    total += value
TypeError: unsupported operand type(s) for +=: 'int' and 'str'

教科書でこれに対する答えを見つけることができず、2番目の for ループがリストを反復せず、値を合計に累積しない理由がわかりません。

4

4 に答える 4

11

文字列を追加する前に、文字列を整数に変換する必要があります。

この行を変更してみてください:

number_list.append(num)

これに:

number_list.append(int(num))

または、これを行うより Pythonic な方法は、sum()関数を使用map()して、初期リストの各文字列を整数に変換することです。

number_string = input("Enter some numbers: ")

print(sum(map(int, number_string)))

ただし、「123abc」のようなものを入力すると、プログラムがクラッシュすることに注意してください。興味がある場合は、例外の処理、特にValueError.

于 2013-04-30T10:17:22.657 に答える
0

行を次のように変更します。

total += int(value)

また

total = total + int(value)

PS両方のコード行は同等です。

于 2013-04-30T10:23:04.343 に答える
0

Python 3 での入力に関する公式ドキュメントは次のとおりです。

 input([prompt])

If the prompt argument is present, it is written to standard output without a trailing    newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised. Example:

>>> s = input('--> ')
--> Monty Python's Flying Circus
>>> s
"Monty Python's Flying Circus"

したがって、例の最初の行で入力を行うと、基本的に文字列が取得されます。

合計する前に、これらの文字列intに変換する必要があります。したがって、基本的には次のようにします。

total = total + int(value)

デバッグについて:

同様の状況で、次のようなエラーが発生した場合: +=: 'int' および 'str' のオペランド型がサポートされていません。type ()関数を使用できます。

type(num) を実行すると、それが文字列であることがわかります。明らかに、 stringintを追加することはできません。

`

于 2013-04-30T10:25:49.783 に答える