循环中的Python编程

时间:2014-06-24 03:04:21

标签: python-3.4

您好我是python和编程的新手。我正在尝试编写一个程序,该程序使用while循环将整数从1添加到输入的数字。如果用户输入0或负数,程序还必须给出错误声明。到目前为止整数加起来并且错误语句有效,但程序没有循环,它只要求用户输入一次数。请帮忙。到目前为止,这是我的源代码。谢谢

x = int(input("Enter a positive number not including zero:" ))

total = 0
n = 1


 while n <= x:
    total = total + n
    n = n + 1

# prints the total of integers up to number entered
    print("Sum of integers from 1 to number entered= ",total)

if x <= 0 or x == -x:
    print ("invalid entry")

2 个答案:

答案 0 :(得分:0)

以这种方式放置您的整个代码

    done = False
    while not done:
        //your entire code here except the last 2 lines
        if x > 0:
            done = True

答案 1 :(得分:0)

试试这段代码......

op='y'
while op=='y':

        x = int(input("Enter a positive number not including zero:" ))

        total = 0
        n = 1

        if x > 0:

                while n <= x:
                        total = total + n
                        n = n + 1

                        # prints the total of integers up to number entered
                        print("Sum of integers from 1 to number entered= ",total)
        else:
                print ("invalid entry")


        op = raw_input("Are you want to continue this operation (y/n):" )