Home > OS >  Broken user input loop
Broken user input loop

Time:10-02

My code breaks when I type n in the console instead of looping back to the beginning.

from art import logo
from calc_functions import add, subtract, divide, multiply

print(logo)

operations = {
    ' ': add,
    '-': subtract,
    '*': multiply,
    '/': divide
}


def calculation():
    num1 = float(input('Enter a number: '))
    for symbol in operations:
        print(symbol)
    loop = True

    while loop:
        symbol1 = input('Choose a calculation: ')
        num2 = float(input('Enter another number.'))
        result = operations[symbol1](num1, num2)
        print(f'{num1} {symbol1} {num2} = {result}')
        reentry = input('Do you wish to continue doing operations? Type "y" or "n".').lower()
        if reentry == 'y':
            num1 = result
        else:
            loop = False

calculation()

CodePudding user response:

You can create a loop over the main function:

while True:
    calculation()

CodePudding user response:

I managed to stop the crashes you were reporting in my tests, I made some changes to your code:

def calculation():
    num1 = float(input('Enter a number: '))
    for symbol in operations:
        print(symbol)

    # UPDATE: 'loop = True' was removed, it is not necessary to assign it
    # to False inside the loop, you can just break when reentry is 'n'
    while True:
        symbol1 = input('Choose a calculation: ')
        num2 = float(input('Enter another number: '))
        result = operations[symbol1](num1, num2)
        print(f'{num1} {symbol1} {num2} = {result}')
        reentry = input('Do you wish to continue doing operations? Type "y" or "n": ').lower()

        # If reentry is anything different from 'y' or 'no', ask again.
        # When reentry matches 'y' or 'n', this loop will fail and proceed
        # To the next evaluation: is reentry == no?

        while reentry != 'y' and reentry != 'n':
            reentry = input('Do you wish to continue doing operations? Type "y" or "n": ').lower()

        # Right here, if it matches 'n', break from the loop
        if reentry == 'n':
            break
        else:
            num1 = result

calculation()
  • Related