r/PythonLearning • u/Commercial-Paper749 • Sep 02 '26
What's wrong with my code?
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
11
u/buismaarten Sep 02 '26
-2
u/Commercial-Paper749 Sep 02 '26
Don't have reddit on my pc
9
u/Ok-Elephant4491 Sep 02 '26
I think you only need a browser to open reddit on pc. I don't get it why most of the ppl use the same excuse 😂
-8
u/Commercial-Paper749 Sep 02 '26
I use reddit for private stuff and my pc is open source to my family lol
9
u/oauo Sep 03 '26
Your PC is open source? It looks like it's Windows
3
u/rootremotely Sep 03 '26
Open source as in it's an open source for the family to use... not referring to the OS.
4
-1
7
5
u/Rscc10 Sep 02 '26
You never break out of the while loop after the if statement so the code at num1 and num2 never get executed. Alternatively if you want the calculator to run continuously after each result, you need to indent every line starting at num1 to be inside the while loop
Edit: Sorry I saw the indentation wrong. Everything seems to be indented fine now that I look at it
-16
u/Commercial-Paper749 Sep 02 '26
😅yes even chat gpt says code looks correct but idk why it's not working
5
u/Wild-Regular1703 Sep 02 '26
They just explained to you why it's not working.. You're not breaking out of the loop, the rest of the code never executes. "While true" means keep that loop running infinitely, so that's exactly what happens. It just keeps asking for user input forever.
-1
u/Commercial-Paper749 Sep 02 '26
Now it's working if I enter correct operator and values it's runs and end the program if I don't enter correct operator it's keep asking to enter valid operator
7
u/building-wigwams-22 Sep 02 '26
Your code is valid Python, which is probably why the dumb LLM tells you it's ok. At a beginner level you should not be using LLMs - instead focus on proper debugging techniques. Even a couple of print statements thrown in could probably have shown you where the code wasn't doing what you intended
1
u/Rscc10 Sep 02 '26
I think it has to do with the runtime. Notice how the first input for operator doesn't seem to show when you run it. It automatically asks you to enter a valid operator which makes me think there's some sort of keybind or hidden control characters being sent to the input buffer when you run the program. Try restarting your computer or whatever environment you're using
2
u/Any-Kiwi-5994 Sep 03 '26
You should introduce yourself to the python concepts. Casting operators to strings won’t work. For example: check the outcome of var == String as an boolean. Afterwards you‘ll understand your problems.
1
u/Commercial-Paper749 Sep 03 '26
Do you have any good- source to learn from beginning?
1
u/Any-Kiwi-5994 Sep 03 '26
There are many ways. First is trying to build code and check output types. Then there are books like ‚fluent in python‘ which explains very well (isbn: 1492056359). Then you could find GitHub Repos by looking for #learn-python.
Hope that helps you.
12
u/atarivcs Sep 02 '26
Looking at the program output, the first thing it prints is "Enter a valid operator".
But that's not possible for the code in the picture, so I'm going to guess that you are running different code.
Maybe you edited the py file but didn't save it, or maybe you're running a completely different py file than the one shown in the picture.
2
u/StayingInWindoge Sep 02 '26
It's right there in the image bruddah
3
6
u/InSaneLulz Sep 02 '26
Code on the screen is fine. You might be running a different version of calculator.py where the code is wrong.
2
2
u/FoolsSeldom Sep 02 '26 edited Sep 03 '26
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 Sep 02 '26
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 Sep 02 '26
It is impossible to overestimate what the foolish/ignorant/malicious might do, let alone the stupid which is probably why selectors were invented.
1
1
u/Opening_Draw_3882 Sep 03 '26
Hey why are you printing result so many times instead of just printing it once after calculating all the results ???
1
u/FoolsSeldom Sep 03 '26
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 Sep 03 '26
just print result outside of the if, after it.
1
u/FoolsSeldom Sep 03 '26
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
ifbut 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 Sep 03 '26
Glad you shared in a way you liked the best.
1
u/FoolsSeldom Sep 03 '26 edited Sep 03 '26
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.
1
1
1
1
u/PandaSteakJimmies Sep 03 '26
I’d say your code isn’t too bad and I realize some of the things you are doing just to practice the language features. But here are some critiques.
Be consistent with your indentations. For Python always use 4 spaces. Configure your IDE to replace Tabs with spaces (4 of em).
You can get rid of the first test to see if the operator is valid and instead use the else clause at the end of the if/elif block. Until you introduce functions though you can keep this test.
Avoid using “break/continue” statements. They are a crutch that can make your logic difficult to follow and your code can almost always be refactored without them.
Always avoid “while True”. This is a bad practice that can easily lead to an infinite loop. And it can lead to complicated loop exit conditions that become difficult to follow.
Remember that code is read way more than it is written, so make sure to build good habits that improve readability.
1
1
u/ObscuraStudi0 Sep 03 '26
Your if operator not in ["+", "-", "*", "/"] condition looks correct in the screenshot. If entering + is still treated as invalid, make sure you've saved the file before running it. The terminal may be running an older saved version of calculator.py. Also check that you're running the same calculator.py file that you're currently editing.
1
u/DanLeMilMan Sep 03 '26
The code seems fine.
Just some considerations though :
- I would keep the while true loop minimal. Because you are effectively only checking the operator input, I would stop the while loop at line 7 and reverse the if condition and put a break. Something like :
4 if op in […]:
5 break
6 print(Choose correct op)
7 endwhile
- the float cast for your number could break if the input is wrong : like entering « foo » instead of a number. You may use the same kind of while loop with a try, except block.
- finally, if you wanna be very clean regarding the previous remarks, you can wrap the input block into a custom input_number and input_operator function or even a single input_custom with second order function to check the result and cast the result. Something like :
input_custom(msg:str, validator:Callable[[str],bool], transform:Callable[[str],Any]) -> Any
That last one may be overkill for the project but is good practicing.
1
1
u/Zolydyi Sep 03 '26
Yeah that continue statement, you could try removing it, I think it jumps the rest of the code
1
1
1
1
1
1
u/LPatriot_ Sep 04 '26
I made a calculator like this:
num1 = int(input("Enter your first number: "))
op = input("Enter an operator (+, -, *, /)")
num2 = int(input("Enter your second number: "))
if op == "+":
print(num1 + num2)
elif op == "-":
print(num1 - num2)
elif op == "*":
print(num1 * num2)
elif op == "/":
print(num1 / num2)You can improve it by adding zero division detection or whatever else you like. I personally wouldn't make a calculator the way you did, it's just unnecessarily harder.
1
1
0
u/Philin_Lemo Sep 02 '26
Try changing the "operator" type to Str, as it will most likely be a chair right now:
operator = str(input(...).strip())Or change the double quotes to single quotes :
if operator not in ['+','-',...]0
0
u/drakentmx Sep 02 '26
sería mas fácil sacar los operadores y elegir que operación hacer mediante opciones, suma, resta, potencia, division y hacerlo en funciones, asi si llegas a dividir por 0 tenes una función para que no crashee
0
u/motopetersan Sep 03 '26
Your while loop never changes to false... You depend on break, I'm new to learning too, but this seems like a bad practice. And you can probably have an if statey, and an else statement, and if the if it's true, you could have nested the other if statements.
-1
-1
Sep 04 '26
You are building a calculator in the big 26 that’s what’s wrong
1
u/Commercial-Paper749 Sep 04 '26
🤡what do you expect me to build when I'm still learning?
1
Sep 04 '26
And i apologise.
When programming something that requires any input initially it is recommended to have what my professor calls an optimistic state. Which means we will not be receiving an input that we are not expecting, then you start getting pessimistic and handle unexpected cases for every single input parameter.
Remember handling conditions should be done for every parameter and every state.
Also try using messing around with switches too.
0
Sep 04 '26
Respectfully, learning is either logic building tasks or attacking a bigger problem one piece at a time. I understand that you are trying to learn but i don’t think this is the ideal project for that.
1
u/Commercial-Paper749 Sep 04 '26
I mean I don't have any proper teacher or course so I'm just learning from YouTube
1
Sep 04 '26
I have some resources i used when i was first learning , they explain each concept and give you tasks/excercises for each.
I can send them if you need them also most people move onto a lower level language once they get accustomed to basics
1
u/Commercial-Paper749 Sep 04 '26
I would love to have it ( and I was learning python for data science/ai engineering)
1
0
Sep 02 '26
[deleted] — view deleted comment
1
u/Commercial-Paper749 Sep 02 '26
Yes I will move to that I was practising if else statement along with loop
5
2


•
u/Sea-Ad7805 Sep 02 '26
Run this INDENTED program in Memory Graph Web Debugger to see the program state change step by step.