[Python] Terminal does not return output, instead restarts code

Discussão em 'Python' iniciado por Stack, Agosto 31, 2025.

  1. Stack

    Stack Membro Participativo

    I'm new to Python and am building a simple interactive calculator as a project. When I run the code in the terminal, it takes all the inputs but does not return the final output. The code restarts instead and asks for inputs again. I'd like to know where I'm going wrong.

    Thank you!

    Here's the code:

    def solver():

    while True:
    try:
    arg1 = float(input('Add 1st number: '))
    arg2 = float(input('Add 2nd number: '))
    except ValueError:
    print('Invalid input. Please enter a number')
    continue

    allowed_functions = set(['+', '-', '/', '*'])
    try:
    function = input('Please choose operation from [+, -, *, /]: ')
    except function not in allowed_functions:
    print(f'Function must contain mathetmatical operation values only')
    continue


    #empty formatting strings
    first_line = ""
    second_line = ""
    dashes = ""
    solutions = ""





    #define mathematical operations
    if function == '+':
    output = arg1 + arg2
    elif function == '-':
    output = arg1 - arg2
    elif function == '*':
    output = arg1 * arg2
    elif function == '/':
    if arg2 == 0:
    print(f'Division by 0 not possible')
    continue
    else:
    output = arg1 / arg2


    #convert values to strings for formatting
    str_arg1 = str(arg1)
    str_arg2 = str(arg2)
    str_output = str(output)

    #output format
    width = max(len(str_arg1), len(str_arg2)) + 2
    top = str_arg1.rjust(width)
    bottom = function + str_arg2.rjust(width-1)
    lines = '-' * width
    result = str_output.rjust(width)


    first_line += top
    second_line += bottom
    dashes += lines
    solutions += result

    #final output
    problems = f'{first_line}\n{second_line}\n{dashes}\n{solutions}'
    return problems

    quit_program = input('Quit Program? Y/N: ')
    if quit_program == 'Y' or quit_program == 'y':
    break


    solver()

    Continue reading...

Compartilhe esta Página