Python Examples
Dave Braunschweig
Counting
# 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 demonstrate_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 demonstrate_do_loop(start, stop, increment): print("Do loop counting from " + str(start) + " to " + str(stop) + " by " + str(increment) + ":") count = start while True: print(count) count = count + increment if not(count <= stop): break
def demonstrate_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") demonstrate_while_loop(start, stop, increment) demonstrate_do_loop(start, stop, increment) demonstrate_for_loop(start, stop, increment) main()
Output
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