Skip to content Skip to sidebar Skip to footer

How Can I Improve This Program?

Asks the user for a number If the user enters 'q', quits the program. If the user enters a non-integer value, output: 'Please enter a number' and ask for the first number again. I

Solution 1:

The most obvious improvement as bruno and Matthias point out is to factor out the user input logic into its own function. Something like this might do:

def get_user_input():
    while True:
        response = input('Please enter a number: ')
        if response == 'q':
            return False, None
        try:
            return True, int(response)
        except ValueError:
            continue


def main():
    print('Give me two numbers and I will divide them.')
    print('Enter \'q\' to quit.')

    continue_program, first_number = get_user_input()
    if not continue_program:
        return

    continue_program, second_number = get_user_input()
    if not continue_program:
        return

    try:
        quotient = first_number // second_number
        print('{} / {} = {}'.format(first_number, second_number, quotient))
    except ZeroDivisionError:
        print('You cannot divide by zero')


if __name__ == '__main__':
    main()

Example run (happy path)

Give me two numbers and I will divide them.
Enter 'q' to quit.
Please enter a number: 10
Please enter a number: 6
10 / 6 = 1

Solution 2:

Useful thing: sentinel to iter() value for this kind of scenarios

import sys
def get_number(display_msg=""):
     sys.stdout.write(display_msg) # OR partial function can be used. 
     for response in iter(input, 'q'): # sentinel
        try:
            return int(response)
        except ValueError:
            continue
first_number = get_number(display_msg="Please enter 1st the number: ")
second_number = get_number(display_msg="Please enter 2nd the number: ")
if isinstance(first_number, int) and isinstance(second_number, int):
     #..do something with first_number, second_number

Post a Comment for "How Can I Improve This Program?"