我试图让我的程序只采取整数,并在用户按0时停止

时间:2017-11-18 17:46:05

标签: python python-3.x

所以代码在我的"之前表现正常,而类型(数字)不是int:"循环,但现在当用户按0时,而不是生成列表的总和,它只是保持循环。

非常感谢一些帮助!谢谢!

List = []



pro = 1
while(pro is not 0):
    number = False
    while type(number) is not int:
        try:
            number = int(input("Please enter a number: "))
            List.append(number)

        except ValueError:

            print("Please only enter integer values.")


    if(number == 0):
        Sum = 0
        for i in List:
            Sum = i + Sum
        ans = 0

print(Sum)

4 个答案:

答案 0 :(得分:0)

if number == 0:置于while type(number) is not int:循环中,如下所示:

List = []

while True:
    try:
        number = int(input("Please enter a number: "))

        if number == 0:
            Sum = 0
            for i in List:
                Sum = i + Sum

            print(Sum)
            break

        List.append(number)

    except ValueError:
        print("Please only enter integer values.")

答案 1 :(得分:0)

实际上,对于用户可能输入的所有数字,这应该永远循环,而不仅仅是零。

要解决此问题,您可以在追加之后(或之前,它并不重要)添加此中断条件:

number = int(input("Please enter a number: "))
List.append(number)
if number == 0:
   break

答案 2 :(得分:0)

我猜你想在用户输入0时结束while循环。

List = []

pro = 1
while pro is not 0:
    try:
        number = int(input("Please enter a number: "))
        List.append(number)
        # This breaks while loop when number == 0
        pro = number
    except ValueError:
        print("Please only enter integer values.")

Sum = 0
for i in List:
    Sum += i

print(Sum)
编辑:我还清理了不必要的代码。

答案 3 :(得分:0)

所以当我这样写的时候我就开始工作了:

SELECT account, sum(amount)
FROM 0_gl_trans 
WHERE account in (
    select account
    from 0_chart_master 
    where account_type IN (60,61,233)
    )
    AND tran_date >= '2017-10-31' 
    AND tran_date <= '2017-11-30'
group by account;

但我真的不明白这是如何使它只采取int值,任何澄清都会非常有用,否则谢谢大家的帮助!