'how to have 2 different messages depending on user input using using the while function?

i created a code that solves mathematic problems by the user. The problems have to involve addition, subtraction, division or multiplication. the code runs without any errors but the issue is I want the code to give two distinct messages for the user.

  1. when the user runs the code for the first time "Please enter the problem in this format (number1 operator number2) or type 'stop' to exist"
  2. when the user enters the problem in the wrong format "invalid enter please try again with the right format or enter 'stop' to exist'
while True:
    while True:
        problem = input("Please enter the problem in this format (number1 operator number2) or type 'stop' to exist: ").split()
        if problem[0] == 'stop':
            break
        if len(problem) != 3:
            continue
        n1,op,n2 = problem
        if any( not (n.isnumeric() or n.count('.')==1 and n.replace('.','').isnumeric()) for n in (n1,n2) ):
            continue
        if op not in ('+','-','*','/','//','**'):
        #this is the tuple of operators which tell the computer which operature the user is using
            continue
        break
    if problem[0] == 'stop':
        break
    match op:
        case '+': result = float(n1)+float(n2)
        case '-': result = float(n1)-float(n2)
        case '*': result = float(n1)*float(n2)
        case '**': result = float(n1)**float(n2)
        case '/': result = float(n1)/float(n2)
            #this will give a float answer. Ex: 1 / 9 = 0.11
        case '//': result = float(n1)//float(n2)
            #this will give an integer answer. Ex: 1 / 9 = 0
    print(f'{result:,.2f}')
    


Solution 1:[1]

an improved version of your code

print("Please enter the problem in this format (number1 operator number2) or type 'stop' to exist: ")
while True:
    problem = input("").split()
    operators = ['+','-','*','/','//','**']

    if problem[0] == 'stop':
        break
    if len(problem) != 3:
        print('invalid entry please try again with the right format or enter stop to exist')
    else:
        if (problem[0].isdigit() == True) and(problem[1] in operators) and (problem[2].isdigit() == True):

            n1 = float(problem[0])
            n2 = float(problem[2])

            if problem[1] == '+':
                result = n1 + n2
            elif problem[1] == '-':
                result = n1 - n2
            elif problem[1] == '*':
                result =  n1 * n2
            elif problem[1] == '**':
                result = n1**n2
            elif problem[1] == '/':
                result = n1/n2
            elif problem[1] == '//':
                result = n1//n2

            print('\n', result, '\n')
        else:
            print('invalid entry please try again with the right format or enter stop to exist')

Output

Please enter the problem in this format (number1 operator number2) or type 'stop' to exist: 
4

invalid entry please try again with the right format or enter stop to exist
4 + 1

5.0 

stop #exit the program

Solution 2:[2]

import sys


def main():
    # Define user_input variables n1, operator, and n2:
    n1, operator, n2 = None, None, None
    operators = ['+', '-', '/', '*', '**']
    while True:  # main loop
        while True:  # Input loop
            user_input = input(
                "Please enter the problem in this format (num operator num) or type 'stop' to quite:\n> ").split()
            if ''.join(user_input) == 'stop':
                print('Goodbye!')
                sys.exit()
            # Check user_input length
            if len(user_input) != 3:
                print(f'This function takes three arguments, {len(user_input)} were given.')
                continue  # continue asking for input
            # Now that the user_input length has been checked, lets assign n1, n2, and operator.
            n1, operator, n2 = user_input[0], user_input[1], user_input[2]
            if not n1.isdigit() or not n2.isdigit():
                print(f" '{n1}' or '{n2}' was not a valid digit!")
                continue  # continue asking for input
            if operator not in operators:
                print(f"'{operator}' was an invalid operator!")
                continue  # continue asking for input
            else:
                break  # break from user_input loop:
        # Join results for evaluation.
        result = ''.join((n1, operator, n2))
        print(f'You entered {n1} {operator} {n2} = {eval(result)}')


if __name__ == '__main__':
    main()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Fareed Khan
Solution 2