跳转到内容

编程基础/循环示例 Python

来自维基教科书,开放的书籍,开放的世界
# This program demonstrates While, Do, and For loop counting using
# user-designated start, stop, and increment values.
#
# References:
#     https://wikibooks.cn/wiki/Python_Programming


def get_value(name):
    print("Enter " + name + " value:")
    value = int(input())    
    return value


def while_loop(start, stop, increment):
    print("While loop counting from " + str(start) + " to " + 
        str(stop) + " by " + str(increment) + ":")
    count = start
    while count <= stop:
        print(count)
        count = count + increment


def do_loop(start, stop, increment):
    print("Do loop counting from " + str(start) + " to " + 
        str(stop) + " by " + str(increment) + ":")
    count = start
    while True:    #This simulates a Do Loop
        print(count)
        count = count + increment
        if not(count <= stop): break   #Exit loop


def for_loop(start, stop, increment):
    print("For loop counting from " + str(start) + " to " + 
        str(stop) + " by " + str(increment) + ":")
    for count in range(start, stop + increment, increment):
        print(count)


def main():
    start = get_value("starting")
    stop = get_value("ending")
    increment = get_value("increment")
    while_loop(start, stop, increment)
    do_loop(start, stop, increment)
    for_loop(start, stop, increment)


main()
Enter starting value:
1
Enter ending value:
3
Enter increment value:
1
While loop counting from 1 to 3 by 1:
1
2
3
Do loop counting from 1 to 3 by 1:
1
2
3
For loop counting from 1 to 3 by 1:
1
2
3

参考资料

[编辑 | 编辑源代码]
华夏公益教科书