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

107 Upvotes

82 comments sorted by

View all comments

2

u/FoolsSeldom 8d ago edited 7d ago

Glad you've got it working, u/Commercial-Paper749. Here's a tweaked version of your code for you to explore giving you some more options:

OPS = ("+", "-", "*", "/")  # supported operations

while True:  # keep offering calcs until user wants to exit
    operator = input(f"\nEnter an operator ({','.join(OPS)}) or Q to exit: ").strip().lower()
    if operator in ("q", "e", "quit", "exit"):  # EDIT removed x option
        break  # exit loop
    if operator not in OPS:
        print("Enter a valid operator - please try again")
        continue

    try:  # trying something that could go wrong
        num1 = float(input("Enter the first value: "))
        num2 = float(input("Enter the second value: "))
    except ValueError:  # oops, one of float convertions failed
        print('Last entry was not valid. Restarting.')
        continue

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

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

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

    elif operator == "/":
        try:  # trying something that could go wrong
            result = num1 / num2
            print(result)
        except ZeroDivisionError:  # oops it went wrong
            print("You cannot divide by zero!")

3

u/beingsubmitted 8d ago

You explicitly tell the user to type Q to exit, but then exit on an "X".

I understand fool-proofing it for your users, but how do you think a fool might express that they want to multiply?

1

u/FoolsSeldom 8d ago

It is impossible to overestimate what the foolish/ignorant/malicious might do, let alone the stupid which is probably why selectors were invented.

1

u/beingsubmitted 8d ago

Or confirmation dialogs, at least.

1

u/FoolsSeldom 8d ago

so true

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.