0
input1 = raw_input("Hello enter a list of numbers to add up!")
lon = 0
while input1:
  input1 = raw_input("Enter numbers to add")
  lon = lon + input1
print lon

このプログラムは、与えられたすべての数字を加算することになっています。うまくいかないので、リストを作成してみました:

input1 = raw_input("Hello enter a list of numbers to add up!")
lon = []
while input1:
  input1 = raw_input("Enter numbers to add")
  lon.append(input1)
print sum(lon)

それはまだ動作しませんか?なぜ解決策はありますか?私はPythonの初心者で、約1か月しかやっていません。ありがとう!

4

3 に答える 3

0

まず第一に、インデントが正しいと仮定しています (while ループ内のステートメントのタブ/スペース)。それ以外の場合は、それを修正する必要があります。

さらに、raw_input は文字列を返します。最初の例では、「入力」に置き換えることができ、それは機能します。

2 番目の例では、次のように、文字列を数値に分割し、それらに合計を適用できます。

input1 = raw_input("Enter numbers to add")
lon.extend(map(int, input1.split()))

追加ではなく「拡張」を使用したことに注意してください。そうしないと、新しい番号で拡張するのではなく、番号のリストをリスト内のリスト要素として追加することになります。

于 2012-09-05T22:16:20.147 に答える
0

空の入力で終了したいように見えるので、int に変換する前にそれを確認する必要があります

print "Hello enter a list of numbers to add up!"
lon = 0
while True:
    input1 = raw_input("Enter numbers to add")
    if not input1:
        # empty string was entered
        break
    lon = lon + int(input1)
print lon

このプログラムは、ユーザーが int に変換できないものを入力するとクラッシュするため、このような例外ハンドラーを追加できます。

print "Hello enter a list of numbers to add up!"
lon = 0
while True:
    input1 = raw_input("Enter numbers to add")
    if not input1:
        # empty string was entered
        break
    try:
        lon = lon + int(input1)
    except ValueError:
        print "I could not convert that to an int"
print lon

同様に、プログラムの 2 番目のバージョンでは、これを行う必要があります。

lon.append(int(input1))

上記のような例外ハンドラを追加できます

于 2012-09-06T00:09:41.290 に答える