首页 > 解决方案 > 问题:while循环不能正确地重新运行程序

问题描述

user_input = input('Welcome to the Scribble Scorer; Enter Word:')

i = {'e': 1, 't': 1.5, 'a': 2, 'i': 2, 'n': 2, 's': 2, 'h': 2.5, 'r': 2.5, 'd': 2.5, 'l': 3, 'u': 3, 'c': 3.5, 'm': 3.5, 'f': 4, 'w': 4.5, 'y': 4.5, 'p': 5, 'g': 5, 'b': 5.5, 'v': 5.5, 'k': 5.5, 'q': 5.5, 'j': 6, 'x': 6, 'z':6}

totalValue = 0
    for char in user_input: # For every character in our string.
        if char in i: # If this character has a defined weight value.
            totalValue += i[char] # Add it to our total.

print('Word:', user_input, 'Score:', totalValue)


while user_input != 'nothing':
    user_input = input('Welcome to the Scribble Scorer; Enter Word:')

    if user_input != 'nothing':
    
        print('Word:', user_input, 'Score:', totalValue)

结果:

Welcome to the Scribble Scorer; Enter Word: fazli
Word: fazli Score: 17
Welcome to the Scribble Scorer; Enter Word: mia
Word: mia Score: 17
Welcome to the Scribble Scorer; Enter Word:

目前,我的程序将根据用户输入的内容打印分数。第一次输入后,'fazli' 得分为 17。

我的 while 循环应该一直运行,直到用户不输入任何内容。

问题是我相信我的while循环。它不会产生新的分数,它只会复制第一个分数。

如何在不复制第一个输入的单词分数的情况下继续运行我的 while 循环?

标签: pythonwhile-loop

解决方案


因为您没有在 while 循环中更新分数。您必须在每次迭代时重新计算它。我给你改了。

i = {'e': 1, 't': 1.5, 'a': 2, 'i': 2, 'n': 2, 's': 2, 'h': 2.5, 'r': 2.5, 'd': 2.5, 'l': 3, 'u': 3, 'c': 3.5, 'm': 3.5, 'f': 4, 'w': 4.5, 'y': 4.5, 'p': 5, 'g': 5, 'b': 5.5, 'v': 5.5, 'k': 5.5, 'q': 5.5, 'j': 6, 'x': 6, 'z':6}
user_input = input('Welcome to the Scribble Scorer; Enter Word:')
while user_input != 'nothing':
    totalValue = 0
    for char in user_input: # For every character in our string.
        if char in i: # If this character has a defined weight value.
            totalValue += i[char] # Add it to our total.
    print('Word:', user_input, 'Score:', totalValue)
    user_input = input('Welcome to the Scribble Scorer; Enter Word:')

推荐阅读