r/PythonLearning 1d 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

85 Upvotes

78 comments sorted by

u/Sea-Ad7805 1d ago

Run this INDENTED program in Memory Graph Web Debugger%3A%20%22).strip()%0A%0A%20%20%20%20if%20operator%20not%20in%20%5B%22%2B%22%2C%20%22-%22%2C%20%22%22%2C%20%22%2F%22%5D%3A%0A%20%20%20%20%20%20%20%20print(%22Enter%20a%20valid%20operator%22)%0A%20%20%20%20%20%20%20%20continue%0A%0A%20%20%20%20num1%20%3D%20float(input(%22Enter%20the%20first%20value%3A%20%22))%0A%20%20%20%20num2%20%3D%20float(input(%22Enter%20the%20second%20value%3A%20%22))%0A%0A%20%20%20%20if%20operator%20%3D%3D%20%22%2B%22%3A%0A%20%20%20%20%20%20%20%20result%20%3D%20num1%20%2B%20num2%0A%20%20%20%20%20%20%20%20print(result)%0A%20%20%20%20elif%20operator%20%3D%3D%20%22-%22%3A%0A%20%20%20%20%20%20%20%20result%20%3D%20num1%20-%20num2%0A%20%20%20%20%20%20%20%20print(result)%0A%20%20%20%20elif%20operator%20%3D%3D%20%22%22%3A%0A%20%20%20%20%20%20%20%20result%20%3D%20num1%20*%20num2%0A%20%20%20%20%20%20%20%20print(result)%0A%20%20%20%20elif%20operator%20%3D%3D%20%22%2F%22%3A%0A%20%20%20%20%20%20%20%20result%20%3D%20num1%20%2F%20num2%0A%20%20%20%20%20%20%20%20print(result)%0A%20%20%20%20%20%20%20%20%0A%20%20%20%20break&timestep=1&play) to see the program state change step by step.

11

u/atarivcs 1d ago

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 1d ago

It's right there in the image bruddah

2

u/Altruistic-Sorbet702 1d ago

Look at the console bruddah, he didn't run the file sent in the pic but a modified version of it

2

u/StayingInWindoge 12h ago

You right, bruddah, I'm blind.

9

u/buismaarten 1d ago

5

u/CalligrapherOk4612 1d ago

r/quotingsourcecodetextisevenharder

-3

u/Commercial-Paper749 1d ago

Don't have reddit on my pc

8

u/Ok-Elephant4491 1d ago

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 😂

-10

u/Commercial-Paper749 1d ago

I use reddit for private stuff and my pc is open source to my family lol

6

u/rootremotely 1d ago

ctrl+shift+n (for chrome, that is)

6

u/oauo 1d ago

Your PC is open source? It looks like it's Windows

3

u/rootremotely 22h ago

Open source as in it's an open source for the family to use... not referring to the OS.

5

u/oauo 21h ago

I know that, I was making a joke

2

u/rootremotely 13h ago

Booo to you and your joke, boooooo!

-1

u/Commercial-Paper749 22h ago

You didn't got the joke

2

u/oauo 21h ago

You seem to have not noticed I was making a joke myself

6

u/InSaneLulz 1d ago

Code on the screen is fine. You might be running a different version of calculator.py where the code is wrong.

4

u/Rscc10 1d ago

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 1d ago

😅yes even chat gpt says code looks correct but idk why it's not working

7

u/building-wigwams-22 1d ago

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

5

u/Wild-Regular1703 1d ago

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 1d ago

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

1

u/Rscc10 1d ago

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/KnowledgeWhole9623 1d ago

Nothing, it's doing exactly what you told it to do

1

u/Ender_Locke 1d ago

computers are notorious for this

2

u/Any-Kiwi-5994 1d ago

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 1d ago

Do you have any good- source to learn from beginning?

1

u/Any-Kiwi-5994 16h ago

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.

1

u/FoolsSeldom 1d ago edited 1d 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 1d 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 1d 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 1d ago

Or confirmation dialogs, at least.

1

u/FoolsSeldom 1d ago

so true

1

u/Opening_Draw_3882 1d ago

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

1

u/FoolsSeldom 1d 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 1d ago

just print result outside of the if, after it.

1

u/FoolsSeldom 1d 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 1d ago

Glad you shared in a way you liked the best.

1

u/FoolsSeldom 1d ago edited 1d 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.

1

u/arconic23 1d ago

You could further improve on the input. What happens if you enter **?

1

u/acana95 1d ago

You need to give us whats not working 😅

1

u/Kenny_070 1d ago

Remove continue and put else: break

1

u/PandaSteakJimmies 1d ago

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

u/gabovaz 1d ago

For starters, it could be a screenshot, not a photo..

1

u/__dee_bugger__ 1d ago

The code is perfectly fine..just try saving it and rerun it..its working perfectly in my pc

1

u/ObscuraStudi0 1d ago

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 1d ago

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

u/HistoryTrue5864 1d ago

Why is there a need to use while true if you will run it once

1

u/Zolydyi 18h ago

Yeah that continue statement, you could try removing it, I think it jumps the rest of the code

1

u/SlimeRemuru 17h ago

you need to write 4 spaces before the break so just do it

1

u/kernel2000 13h ago

use .replace( "\n", "") strip removes whitespace but not newlines i think

1

u/No-Inevitable-6476 9h ago

Use the Python visualizer to debug the code easily.

1

u/Artistic_World1790 5h ago

You are building a calculator in the big 26 that’s what’s wrong

1

u/Commercial-Paper749 4h ago

🤡what do you expect me to build when I'm still learning?

1

u/Artistic_World1790 4h ago

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 4h ago

I mean I don't have any proper teacher or course so I'm just learning from YouTube

1

u/Artistic_World1790 4h ago

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 4h ago

I would love to have it ( and I was learning python for data science/ai engineering)

1

u/Artistic_World1790 4h ago

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.

1

u/Shot-Rutabaga-3181 3h ago

I am also learning this shit while loop

1

u/CryptographerOwn9908 2h ago

O código está com um erro na validação dos operadores e no tratamento da entrada do usuário: * Lista de operadores inválida: Na linha 4, a lista ["+", "-", "*", "/"] contém uma vírgula dentro das aspas no elemento "-" (está escrito "-" ou "-,"). Por isso, ao digitar apenas +, o código não reconhece e exibe "Enter a valid operator". * Semicolons e Aspas no input: Algumas linhas de if/elif possuem ponto e vírgula ; no final do comando, e há parênteses faltando ao fechar os input() nas linhas 8 e 9 (falta um ) no final de cada uma). * Divisão por zero: Na linha 21, se o usuário digitar 0 para num2 ao usar a divisão /, o programa vai quebrar com um erro de ZeroDivisionError. Código Corrigido

Python calculator

while True: operator = input("Enter an operator (+, -, , /): ").strip() if operator not in ["+", "-", "", "/"]: print("Enter a valid operator") continue

num1 = float(input("Enter the first value: "))
num2 = float(input("Enter the second value: "))

if operator == "+":
    result = num1 + num2
    print(result)
elif operator == "-":
    result = num1 - num2
    print(result)
elif operator == "*":
    result = num1 * num2
    print(result)
elif operator == "/":
    if num2 != 0:
        result = num1 / num2
        print(result)
    else:
        print("Cannot divide by zero")
        continue
break

1

u/LPatriot_ 1h ago

I made a calculator like this:

```print("Calculator")

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.

0

u/Philin_Lemo 1d ago

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

u/ed_xc01 1d ago

Time to put hash tables into practice. You need to understand that, instead of using if-else statements, you can create a list that, depending on what the user says, executes a specific function.

```python def sumar(a, b): return a + b

def restar(a, b): return a - b

funciones = { "suma": sumar, "resta": restar }

operacion = input("Elige suma o resta: ") a = int(input("Primer número: ")) b = int(input("Segundo número: "))

if operacion in funciones: resultado = funciones[operacion](a, b) print("Resultado:", resultado) else: print("Operación no válida") ```

5

u/No_Cattle_9565 1d ago

Somehow these variable names are making me uncomfortable

2

u/Sharp_Platypus6545 1d ago

Was thinking of the same approach😅

1

u/Commercial-Paper749 1d ago

Yes I will move to that I was practising if else statement along with loop

0

u/drakentmx 1d ago

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 1d ago

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

u/Flimsy-Ad-8235 1d ago

Use gpt di dumb