【问题标题】:Accumulator using For Loop in Python在 Python 中使用 For 循环的累加器
【发布时间】:2015-02-18 20:33:17
【问题描述】:

我的老师想要一个程序来询问用户一个正整数值,程序应该循环以获取从 1 到输入的编号的所有整数的总和。在 For 循环中使用 Python。

这是我为 For 循环想出的,但当我输入负数时它不是不循环,当我输入负数后输入正数时它不会显示答案。

x=int(input("Please pick a positive integer"))
sum=0
for i in range(1,x):
    sum=sum+1
    print(sum)
else:
    x=int(input("Please pick a positive integer"))

帮助?

【问题讨论】:

  • 供将来参考,python 提供了 sum 函数。所以你可以使用sum(range(x+1)),其中 x 是你的正整数值。

标签: python for-loop


【解决方案1】:

如何实现以下内容。您的程序存在一些问题,最明显的是

1. 重复打印每个值的总和。

2. 您只是将总和加 1,而不是整数 i

3. 如果您的用户没有输入正整数,您就不会返回您的函数。

4.如果整数大于0,你没有if语句。

def intpicker():
        x=int(input("Please pick a positive integer"))
        sum=0
        if x >= 0:
            for i in range(1,x):
                sum=sum+i
            print(sum)
        else:
            return intpicker()

此代码可以进一步缩写,但出于所有意图和目的,您可能应该尝试理解此实现作为开始。

【讨论】:

  • 退出递归呢?现在它将是永远的循环。
【解决方案2】:

您的程序存在一些致命缺陷。见下文:

x=int(input("Please pick a positive integer")) #what if the user inputs "a"
sum=0
for i in range(1,x): # this will not include the number that they typed in
    sum=sum+1 # you are adding 1, instead of the i
    print(sum) 
else:
    x=int(input("Please pick a positive integer")) # your script ends here without ever using the above variable x

这是我可能会做的:

while True: # enters loop so it keeps asking for a new integer
    sum = 0
    x = input("Please pick an integer (type q to exit) > ")
    if x == "q": # ends program if user enters q
        break
    else:
        # try/except loop to see if what they entered is an integer
        try:
            x = int(x)
        except:
            print "You entered {0}, that is not a positive integer.".format(x)
            continue
        for i in range(1, x+1): # if the user enters 2, this will add 1 and 2, instead of 1.
            sum += i 
        print sum

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-08
    • 2018-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-17
    相关资源
    最近更新 更多