CSC111 Semantic Variations of the While Loop

From dftwiki3
Revision as of 10:02, 17 February 2014 by Thiebaut (talk | contribs)
(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
#

# =======================================
#__     __            _               _ 
#\ \   / /__ _ __ ___(_) ___  _ __   / |
# \ \ / / _ \ '__/ __| |/ _ \| '_ \  | |
#  \ V /  __/ |  \__ \ | (_) | | | | | |
#   \_/ \___|_|  |___/_|\___/|_| |_| |_|
#
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 ) )



# =======================================
#__     __            _               ____  
#\ \   / /__ _ __ ___(_) ___  _ __   |___ \ 
# \ \ / / _ \ '__/ __| |/ _ \| '_ \    __) |
#  \ V /  __/ |  \__ \ | (_) | | | |  / __/ 
#   \_/ \___|_|  |___/_|\___/|_| |_| |_____|
#                                           
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 ) )



# =======================================
#__     __            _               _____ 
#\ \   / /__ _ __ ___(_) ___  _ __   |___ / 
# \ \ / / _ \ '__/ __| |/ _ \| '_ \    |_ \ 
#  \ V /  __/ |  \__ \ | (_) | | | |  ___) |
#   \_/ \___|_|  |___/_|\___/|_| |_| |____/ 
#
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 ) )