Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

While loop still continues

When the user inputs anything but a number for the first input, the program should quit. But instead it just keeps going.

I tried to put many if … break statements in the main function after the "a" to break it, but nothing helped.

def is_number(str):
    try:
        float(str)
        return True
    except ValueError:
        return False
       

def is_valid_operator(operator):
    operators = ('+', '-', '*', '/')
    return operator in operators



def ask_for_a_number(force_valid_input):
    while force_valid_input is True:
        a = input('Please provide a number: ')
        if is_number(a):
            return float(a)
        else:
            if not force_valid_input:
                return None
            print("This doesn't look like a number, try again!")

def ask_for_an_operator(force_valid_input):
    while force_valid_input is True:
        operator = input('Please provide an operator: ')
        if is_valid_operator(operator):
            return operator
        else:
            if not force_valid_input:
                return None
            print('Unknown Operator')



def calc(operator, a, b):
    if not is_number(a) or not is_valid_operator(operator) or not is_number(b):
        return None
    result = 0
    if operator == '+':
        result = a + b
    elif operator == '-':
        result = a - b
    elif operator == '*':
        result = a * b
    elif operator == '/':
        if b != 0:
            result = a / b
        else:
            print('Error: Divide by zero is not allowed')
            return None

    return result

def main():
    while True:
        a = ask_for_a_number(force_valid_input = True)
        operator = ask_for_an_operator(force_valid_input = True)
        b = ask_for_a_number(force_valid_input = True)
        result = calc(operator, a, b)
        if result is not None:
            print(f'The result is {result}')
    
    


if __name__ == '__main__':
    main()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You check whether a is a number or not, but then don’t do anything if it isn’t one. So check the value of a

a = ask_for_a_number(force_valid_input = True)
if not a:
    return
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading