Jump to content

Programming Fundamentals/Loop Examples Python

From Wikibooks, open books for an open world

Counting

[edit | edit source]
# This program demonstrates While, Do, and For loop counting using
# user-designated start, stop, and increment values.
#
# References:
#     https://en.wikibooks.org/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()

Output

[edit | edit source]
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

References

[edit | edit source]