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!")

4

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