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:

defget_user_input():
    whileTrue:
        response = input('Please enter a number: ')
        if response == 'q':
            returnFalse, Nonetry:
            returnTrue, int(response)
        except ValueError:
            continuedefmain():
    print('Give me two numbers and I will divide them.')
    print('Enter \'q\' to quit.')

    continue_program, first_number = get_user_input()
    ifnot continue_program:
        return

    continue_program, second_number = get_user_input()
    ifnot continue_program:
        returntry:
        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
defget_number(display_msg=""):
     sys.stdout.write(display_msg) # OR partial function can be used. for response initer(input, 'q'): # sentineltry:
            returnint(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: ")
ifisinstance(first_number, int) andisinstance(second_number, int):
     #..do something with first_number, second_number

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