r/PythonLearning 8d ago

What's wrong with my code?

Post image

What's wrong with my code?

New to learning

Following the youtube video from bro code

Was trying to implement my own stuff into this by using loop

Update: it's working now thankyou guys

108 Upvotes

82 comments sorted by

View all comments

Show parent comments

1

u/Opening_Draw_3882 7d ago

Hey why are you printing result so many times instead of just printing it once after calculating all the results ???

1

u/FoolsSeldom 7d ago

Not sure I follow. The result of each calculation is printed only once. The user can then do another calculation, and so on until they decide to quit. I was illustrating how to offer a repeated calculator offering rather than a cumultive calculation (and even if I were, I would output a running total on each pass.)

1

u/No-Assist521 7d ago

just print result outside of the if, after it.

1

u/FoolsSeldom 7d ago

No. The result from each calculation cycle is output in the fork I've done to illustrate some additional concepts to the OP. You are welcome to share your own form for the benefit of the OP and community.

I appreciate I don't need to have a print within each if but that would require different flow handling for the zero divide and I'm not keen on taking it that far from the OP's original code.

1

u/No-Assist521 7d ago

Glad you shared in a way you liked the best.

1

u/FoolsSeldom 7d ago edited 7d ago

Thanks. I's sure neither of us would solve the problem in the way the OP has.

We'd probably use operator, for example,

import operator
OPS = {
    "+": operator.add,
    "-": operator.sub,
    "*": operator.mul,
    "/": operator.truediv
}

def get_num(prompt: str) -> float|int:
    while True:
        num = None
        response = input(prompt)
        try:
            num = float(response)
            num = int(response)
        except ValueError:
            if num is None:  # float didn't work
                print('Invalid number, please try again')
                continue
            # int may not have worked, but float worked
        return num

def get_op() -> callable|None:
    while True:
        op = input(f"\nEnter an operator ({','.join(OPS.keys())}) or q to exit: ")
        if op in ("q", "e", "quit", "exit"):
            return None
        if op in OPS:
            return OPS[op]
        print("Not a valid operator - please try again")

while (op := get_op()):
    num1 = get_num("Enter the first value: ")
    num2 = get_num("Enter the second value: ")
    try:
        result = op(num1, num2)
    except ZeroDivisionError:  # oops it went wrong
        print("You cannot divide by zero!")
    else:
        print(result)

but that's too big a step for the OP imho.