1

新しい入力数値が古い入力数値よりも大きい場合にのみループが実行されるように、Python でセンチネル ループを設定するにはどうすればよいですか?

これは私が今持っているものですが、正しくないことはわかっています。

    totalScore = 0
    loopCounter = 0
    scoreCount = 0
    newScore = 0
    oldscore = newscore - 1
    print("Enter the scores:")
    score = (raw_input("Score 1"))
    while newScore >= oldScore:
        newScore = int(raw_input("Score " ) + (loopCounter + 1))
        scoreTotal = scoreTotal+newScore+oldScore
        scoreCount = scoreCount + 1
        loopCounter = loopCounter + 1
    averageScore = scoreTotal / scoreCount
    print "The average score is " + str(averageScore)
4

4 に答える 4

2

これを処理する事実上の方法は、個々のスコアを毎回破棄するのではなく、リストを使用することです。

scores = [0] # a dummy entry to make the numbers line up
print("Enter the scores: ")
while True: # We'll use an if to kick us out of the loop, so loop forever
    score = int(raw_input("Score {}: ".format(len(scores)))
    if score < scores[-1]:
        print("Exiting loop...")
        break
        # kicks you out of the loop if score is smaller
        # than scores[-1] (the last entry in scores)
    scores.append(score)
scores.pop(0) # removes the first (dummy) entry
average_score = sum(scores) / len(scores)
# sum() adds together an iterable like a list, so sum(scores) is all your scores
# together. len() gives the length of an iterable, so average is easy to test!
print("The average score is {}".format(average_score))
于 2014-02-21T18:26:21.307 に答える
1

毎回より多くの数を入力しながら、ユーザーに新しい入力を求め続けたいとします。リストを使用して入力されたすべてのスコアを保持し、sum組み込み関数を使用して作業を行うことができます。

scores = []
while True:
   current_size = len(scores)
   score = int(raw_input("Score %s" % (current_size + 1)))
   # Check if there's any score already entered and then if the new one is 
   # smaller than the previous one. If it's the case, we break the loop
   if current_size > 0 and score < scores[-1]:
       break
   scores.append(score)

# avg = total of each scores entered divided by the size of the list
avg = sum(scores) / len(scores)
print "The average score is %s" % avg
于 2014-02-21T18:28:22.383 に答える
1

Raymond Hettinger の講演と Amir のブログ投稿http://blog.amir.rachum.com/blog/2013/11/10/python-tips-iterate-with-a-sentinel-value/に従ってください。

In [1]: def loop():
   ...:     old = 0
   ...:     while True:
   ...:         new = raw_input("gimme")
   ...:         yield new > old
   ...:         old = new
   ...:         

In [2]: l = loop()

In [4]: list(iter(l.next, False))
gimme1
gimme2
gimme0
Out[4]: [True, True]
于 2014-10-15T13:55:44.437 に答える