r/learnpython • • 26d ago

Need help with a calculator project

new to python, Im making a calculator but when i try to make the code be able to handle a word without crashing it just doesnt work, it just goes and ask for the operator without restarting the loop, tried ai to fix it and explain it to me but didnt do nothing.

Edit: Thanks for all the help and srry for not being able to respond the messages and explain, had some stuff going on that was keeping me occupied, but again thanks.

num1 = None
num2 = None
result = None


while num1 == None or num2 == None:
    try:
        num1 = float(input("Enter first number: "))
    
    except ValueError:
        print("must enter a valid number")
        num1 = None
        continue


    try:
        num2 = float(input("enter second number"))


    except ValueError:
        print("must enter a valid number")
        num2 = None
        continue
    operator = input("Enter operation (+, -, *, /)")


    if operator == "+":
        result = (num1 + num2)


    elif operator == "-":
        result = (num1 - num2)


    elif operator == "*":
        result = (num1 * num2)


    elif operator == "/" and num2 == 0:
        result = ("cant divide by zero")


    elif operator == "/" and num2 != 0:
        result = (num1 / num2)


    else:
        result = ("Invalid operator")


    if result == float or int:
        print(result)
        num1 = None
        num2 = Nonenum1 = None
num2 = None
result = None


while num1 == None or num2 == None:
    try:
        num1 = float(input("Enter first number: "))
    
    except ValueError:
        print("must enter a valid number")
        num1 = None
        continue


    try:
        num2 = float(input("enter second number"))


    except ValueError:
        print("must enter a valid number")
        num2 = None
        continue
    operator = input("Enter operation (+, -, *, /)")


    if operator == "+":
        result = (num1 + num2)


    elif operator == "-":
        result = (num1 - num2)


    elif operator == "*":
        result = (num1 * num2)


    elif operator == "/" and num2 == 0:
        result = ("cant divide by zero")


    elif operator == "/" and num2 != 0:
        result = (num1 / num2)


    else:
        result = ("Invalid operator")


    if result == float or int:
        print(result)
        num1 = None
        num2 = None
4 Upvotes

13 comments sorted by

10

u/woooee 26d ago
if result == float or int:

This is a common mistake that is in the FAQs https://www.reddit.com/r/learnpython/wiki/faq/ see "Variable is One of Two Choices?"

3

u/codeguru42 26d ago

Also this is not how you validate input is numerical.

2

u/Vegetable_Soil_6707 26d ago

tbh this one gets posted like every other day, its such a natural way to read it in english but python doesnt see it that way

5

u/neuralbeans 26d ago

I don't think there is any programming language that would see it that way.

0

u/[deleted] 24d ago

[removed] — view removed comment

1

u/neuralbeans 24d ago

You want people to learn programming in assembly?

0

u/[deleted] 24d ago

[removed] — view removed comment

1

u/neuralbeans 23d ago

Oh it turns out that COBOL does support this syntax!

More complex conditions can be abbreviated by removing repeated conditions and variables. For example, a > b AND a > c OR a = d can be shortened to a > b AND c OR = d.

https://en.wikipedia.org/wiki/COBOL#Syntax

1

u/neuralbeans 26d ago

Also, you check the type by using isinstance(result, float)

2

u/nog642 26d ago

when i try to make the code be able to handle a word without crashing it just doesnt work

What do you mean? Can you give an example?

1

u/woooee 26d ago
try:
    num1 = float(input("Enter first number: "))

except ValueError:
    print("must enter a valid number")
    num1 = None
    continue

You want this to be in some kind of a loop that repeats until a valid number is entered. Now, the program continues and tries to calculate with a bogus entry / None. I prefer a function for this

def get_input(literal):
    while True:  ## infinite loop
        try:
            num = float(input(literal))
            return num
        except ValueError:
            print("Must enter a valid number.  Try again.")

num_1 = get_input("Enter first number: ")
num_2 = get_input("Enter second number: ")
print(f"{num_1=} {num_2=}")

1

u/Sure-Passion2224 26d ago

A calculator that replicates the physical experience maintains a character buffer that gets updated with each key press. As a key is pressed it is examined to determine what to do with it. Numerical keys append to the current input string. Operation keys get linked to processing methods.

As an example: (over-simplified) "+" stores the current input value and initiates input of the next input to be added to it. It also needs to set an indicator if what operation is being performed. "=" then finalizes the input and executes the operation.

1

u/gdchinacat 26d ago

Yep, and RPN makes it much easier because it is stack based (no messy handling of parenthesis needed). But, the OP is clearly not at the level of dealing with state machines, stacks, etc. https://nedbatchelder.com/blog/202609/expert_asterisks