Python 要求用户输入数字并输出输入数字的总和和数量的程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26350627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:22:54  来源:igfitidea点击:

Program that asks user for numbers and outputs the sum and the amount of numbers entered

pythonloopscountwhile-loopadd

提问by

I'm a beginner in python, and I'm creating a program that asks the user for as many numbers as they want until they input "stop". Then the program would output how many numbers they entered and the result of all the numbers added together. Everything works well the first time, but as soon as I enter another number, the addition will be incorrect.

我是 Python 的初学者,我正在创建一个程序,该程序要求用户输入任意数量的数字,直到他们输入“停止”为止。然后程序会输出他们输入了多少个数字以及所有数字相加的结果。第一次一切正常,但一旦我输入另一个数字,加法就会不正确。

count=1
numberstring=raw_input("Please enter a number: ")
number=float(numberstring)
while number!="stop":
    numberString=raw_input("Please enter another number: ")
    number1=float(numberString)
    sum=number+number1
    count= count+1
    print "The amount of numbers you entered was: " + str(count) + " and the sum of all these numbers together is: " + str(sum)     

采纳答案by xgord

You have a couple problems here. The first is that what you're trying to do is find the sum of all the numbers the user enters and print that out. But what you're really doing is only printing out the sum of the first number the user entered and the latest number.

你在这里有几个问题。首先,您要做的是找到用户输入的所有数字的总和并将其打印出来。但是您真正要做的只是打印出用户输入的第一个数字和最新数字的总和。

Your sum variable is set here:

您的 sum 变量在此处设置:

sum=number+number1

but the numbervariable is never updated; it's always the first number the user input. number1on the other hand is only the last number the user input. so sum is always being set to the 1st_number + last_number.

number变量永远不会更新;它始终是用户输入的第一个数字。number1另一方面只是用户输入的最后一个数字。所以 sum 总是被设置为1st_number + last_number.

what you need to do instead is add the latest number to sum like so: sum += number1(with sum set to 0 before the while loop).

您需要做的是将最新的数字添加到 sum 中,如下所示:(sum += number1在 while 循环之前将 sum 设置为 0)。

The second problem with your code is this line:

您的代码的第二个问题是这一行:

number1=float(numberString)

This line will throw an error if numberStringis anything other than a number. The condition of your while loop checks to see if numberString == 'stop', but this can never be true. If the user enters "stop", the program will instead throw an error because a string cannot be converted to a float. So before converting the numberString to a float, you should check to see if your condition has been met.

如果numberString不是数字,此行将引发错误。您的 while 循环的条件会检查 if numberString == 'stop',但这永远不会为真。如果用户输入“stop”,程序将抛出错误,因为字符串无法转换为浮点数。因此,在将 numberString 转换为浮点数之前,您应该检查是否满足您的条件。

回答by John1024

prompt = "Please enter a number: "
sum = 0
count = 0
while True:
    s = raw_input(prompt)
    prompt = "Please enter another number: "
    if s.lower() == 'stop':
        break
    try:
        sum += float(s)
        count += 1
    except ValueError:
        print "Bad number.  Try again"
print "You entered %s numbers whose sum is %s." % (count, sum)

回答by Anand Surampudi

I am a beginner too in whole of programming. Sharing my learning here as first steps in using this website too.

我也是整个编程的初学者。在这里分享我的学习也是使用本网站的第一步。

One of the books I am following for self-learning python has an exercise as follows.

我正在阅读的一本自学python的书有一个练习如下。

Write a program which repeatedly reads numbers until the user enters “done”. Once “done” is entered, print out the total, count, and average of the numbers. If the user enters anything other than a number, detect their mistake using try and except and print an error message and skip to the next number.

编写一个程序,重复读取数字,直到用户输入“完成”。输入“完成”后,打印出数字的总数、计数和平均值。如果用户输入数字以外的任何内容,请使用 try 和 except 检测他们的错误并打印错误消息并跳到下一个数字。

And thanks @John1024, I tried it this way using your help.

感谢@John1024,我在您的帮助下以这种方式尝试过。

inp = 'Enter a number: '
total = 0
count = 0
average = 0

while True:
        s = raw_input(inp)
        if s == 'done':
                break
        try:
                total += float(s)
                count += 1
                average = total / count
        except ValueError:
                print "Invalid Input. Try again: "
        continue
print 'You entered %s numbers whose total is %s and average is %s.' % (str(count), str(total), str(average))

回答by Jaimish Ashar

  1. I wrote this code for Python, it seemed to work okay for the task at hand.
  2. It takes numbers one by one and calculates the total and count accordingly.
  3. If a letter is encountered it subtracts 1 from the count, otherwise the average would be wrong.
  4. If 'done' is encountered, the loop is exited.
  5. Average is calculated outside the loop, as it just needs to be calculated once.

    count = 0
    total = 0
    average = 0 
    while True:
            numlist = raw_input('Enter number\n')
            if numlist == 'done':
                    break
            try:
                    count = count + 1
                    total = total + float(numlist)
            except:
                    count = count - 1
                    print 'Enter a valid number'
                    continue
    average = float(total)/float(count) 
    print 'Count:',count
    print 'Total:',total
    print 'Avg:',average
    
  1. 我为 Python 编写了这段代码,它似乎适合手头的任务。
  2. 它一个一个地取数字并计算总数并相应地计数。
  3. 如果遇到一个字母,它会从计数中减去 1,否则平均值将是错误的。
  4. 如果遇到“done”,则退出循环。
  5. 平均值在循环外计算,因为它只需要计算一次。

    count = 0
    total = 0
    average = 0 
    while True:
            numlist = raw_input('Enter number\n')
            if numlist == 'done':
                    break
            try:
                    count = count + 1
                    total = total + float(numlist)
            except:
                    count = count - 1
                    print 'Enter a valid number'
                    continue
    average = float(total)/float(count) 
    print 'Count:',count
    print 'Total:',total
    print 'Avg:',average