CSC111 Semantic Variations of the While Loop

From dftwiki3
Revision as of 08:59, 17 February 2014 by Thiebaut (talk | contribs) (Created page with "--~~~~--~~~~ ---- The program below contains different versions of a Python block that asks the use for 2 integers, the second of which must be different from 0. The block t...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

--D. Thiebaut (talk) 08:59, 17 February 2014 (EST)--D. Thiebaut (talk) 08:59, 17 February 2014 (EST)


The program below contains different versions of a Python block that asks the use for 2 integers, the second of which must be different from 0. The block then divides the first number by the second and prints the ratio as a float.


# Different options for a robust input
#

# Version 1
print( "\n\nVersion 1" )
x = int( input( "Please enter an integer: " ) )
y = int( input( "Please enter an integer different from 0: " ) )

while y == 0:
    y = int( input( "0 is not a valid input.  Please reenter: "  ) )

print( "%d / %d = %1.2f" % ( x, y, x/y ) )

# Version 2
print( "\n\nVersion 2" )
x = int( input( "Please enter an integer: " ) )
y = 0
while y == 0:
    y = int( input( "Please enter an integer different from 0: " ) )

print( "%d / %d = %1.2f" % ( x, y, x/y ) )

# Version 3
print( "\n\nVersion 3" )
x = int( input( "Please enter an integer: " ) )
y = 0
while y == 0:
    y = int( input( "Please enter an integer different from 0: " ) )
    if y == 0:
        print( "\n*** Invalid input! ***" )
        
print( "%d / %d = %1.2f" % ( x, y, x/y ) )