如何使用带数字输入的循环,打印数字直到输入“完成”?

问题描述 投票:1回答:3

我是Python的新手。我需要编写一个使用循环的代码,该循环将接受数字输入,然后打印数字。它将无限地执行此操作,直到键入“完成”为止。输入“完成”后,将打印输入数字的平均值,计数和总和。如果输入另一个单词(例如'stop')而不是'complete',则指示用户输入数字或'complete'的消息将打印并重新启动循环。

`import sys
count = 0
sumN = 0.0
line = 1

while True:
    line = (input('>>> '))
    sumN = sumN + float(line)
    count += 1
    try:
        if line == '#':
            sumN = sumN + float(line)
            count += 1
            print(line)
            continue
        elif line == 'done':
            print(float(line)) # to send to except
            break
        elif line != '#' and line != 'done':
            print("Please enter a number or 'done' to finish input:")
            continue
    except:
        print('The total sum of your inputs is: ' + str(sumN))
        print('The count of your inputs is: ' + str(count))
        print('The average of your inputs is: ' + str(sumN/count))` 
python
3个回答
0
投票

你遇到的问题是你在进入'try catch'块之前尝试将input转换为float。

import sys
count = 0
sumN = 0.0
line = 1

while True:
    line = (input('>>> '))
    try:
        sumN = sumN + float(line) <--- this was causing the issue
        count += 1
        if line == '#':
            sumN = sumN + float(line)
            count += 1
            print(line)
            continue
        elif line == 'done':
            print(float(line)) # to send to except
            break
        elif line != '#' and line != 'done':
            print("Please enter a number or 'done' to finish input:")
            continue
    except ValueError :
        print('The total sum of your inputs is: ' + str(sumN))
        print('The count of your inputs is: ' + str(count))
        print('The average of your inputs is: ' + str(sumN/count))

这应该工作。注意try的新位置


0
投票

首先,你应该说它为什么不起作用。它是错误的,还是完整但没有给出正确的行为或数据。

我看到的主要问题是

        if line == '#':
            sumN = sumN + float(line)

变量line是一个字符串,保存用户的输入。说'line ==“#”'不测试行是一个数字。相反,你需要做以下事情:

try:
   number = float(line) # Try to convert input into a number.
   sumN += number
   count += 1
except:
   print("Please enter a number or 'done', [%s] is not a number" # line)
   continue

这是Python中的常见做法,尝试一些东西,并通过异常处理错误。您也可以尝试在行中搜索数字字符,但如果您想要允许小数点,负号等,这会变得混乱。您可以检查每个字符,但只是尝试将行转换为带浮点数的数字更简单( ),并在错误发生时处理。

此外,您正在为每个输入递增计数器。相反,您应该只在用户输入数字时递增它。


0
投票

你也可以试试这个:

import sys

count = 0
sumN = 0.0

while True:
    line = input(">>> ")
    try:
        if line.isdigit():
            sumN += float(line)
            count += 1
            print(line)
        elif line == 'done':
            raise Exception()
        else:
            print("Please enter a number or 'done' to finish input:")
    except:
        print('The total sum of your inputs is: ' + str(sumN))
        print('The count of your inputs is: ' + str(count))
        print('The average of your inputs is: ' + str(sumN/count))
        break

您可以使用str.isdigit()函数检查字符串是否为数字。

© www.soinside.com 2019 - 2024. All rights reserved.