为什么我不能用while总结我所有的值(用户值)问题?

2024-04-29 07:13:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我是新来的编码世界。我在把所有用户的输入值相加时遇到了一个问题,因为我不知道会有多少。有什么建议吗? 我已经走了这么远了。别介意学外语

import math
while(True):
    n=input("PERSONS WEIGHT?")
    people=0
    
    answer= input( "Do we continue adding people ? y/n")
    if answer == "y" :
        continue
    elif answer == "n" :
        break
    else:
        print("You typed something wrong , add another value ")
    people +=1
    limit=300
    if a > limit :
        print("Cant use the lift")
    else:
        print("Can use the lift")

Tags: the用户answer编码inputifuse世界
2条回答

这里有一些值得你学习的东西,我认为它能满足你的所有需求:

people = 0
a = 0

while True:

    while True:
        try:
            n = int(input("PERSONS WEIGHT?"))
            break
        except ValueError as ex:
            print("You didn't type a number.  Try again")

    people += 1
    a += int(n)

    while True:
        answer = input("Do we continue adding people ? y/n")
        if answer in ["y", "n"]:
            break
        print("You typed something wrong , add another value ")

    if answer == 'n':
        break

limit = 300
if a > limit:
    print("Total weight is %d which exceeds %d so the lift is overloaded" % (a, limit))
else:
    print("Total weight is %d which does not exceed %d so the lift can be operated" % (a, limit))

添加的主要思想是,每个输入必须有单独的循环,然后是一个外部循环,以便能够输入多个权重

people = 0移出循环也很重要,这样它就不会一直重置回0,并以同样的方式初始化a

简单的加法不需要导入数学库。因为你没有提到你会犯什么错误,所以我想你需要一个解决问题的方法。你的代码太长了。我已经为你写了一段代码。只有6行。它会解决你的问题。 这是代码

sum = 0;
while(True):
  n = int(input("Enter Number.? Press -1 for Exit: "))
  if n == -1:
    break
  sum = sum+n
print(sum)

代码说明: 首先,我声明了变量sum。我写了while循环,在while循环中,我提示用户输入数字。如果用户输入-1,将停止程序。除非用户输入“-1”,否则此程序将继续接受用户输入。最后它将打印总金额

代码的输出:

Output of the above code

相关问题 更多 >