Search code examples
pythonloopswhile-loopoperator-keywordevaluation

How to evaluate user's input in s loop?


I'm new in coding or programming so I hope for respect.

How can I create a program that continually accepts input from the user. The input shall be in this format operatornumber like -3

Like

num = 0

while((a := input("Enter operatornumber like -9;")) != "-0"):
    if (len(a) >= 2) and (a[0] in "/*-+"):
        num = eval(f"{num}{a}")
    else:
        print("Invalid input, try again.")
    
print(num)

But how can I make the first input of the user to only use the add (+) or subtract(-) operators but in the next input they can now use the other operators.

Like

Enter operatornumber like -9; +9 Enter operatornumber like -9; -8 Enter operatornumber like -9; -0 1

And how can I combine all the input like +9-9 is 1?


Solution

  • In the input statement, you're closing the "Enter operator and number like" msg. This is creating more problems after that line, where all green parts are considered as string now. Also, in while statement, "w" should be small letter, python is case sensitive. Try doing this:

    Number = input("Enter operator and number like '-9' ")
    Operator = ("+","-","/")
    while Number == (Operator + Number):
        if Number == "-0":
            Total = 0
            Total += Number 
    print(f"the result of {num} is {total} ")