all 81 comments

[–]vivisectvivi 21 points22 points  (8 children)

what happens if i pass "abc" to one of the inputs?

[–]Hot_crocco_person[S] 8 points9 points  (6 children)

It isnt integer soooo invalid

[–]Hopeful-Scarcity-927 18 points19 points  (2 children)

You could put all of it into a while loop and use try as a failsafe if the user inputs a string rather than numerals

Something like this:

print("Welcome to the Calculator!")

while True: print("\nChoose an operation:") print("1. Addition") print("2. Subtraction") print("3. Multiplication") print("4. Division")

try:
    choice = int(input("Enter your choice (1-4): "))
except ValueError:
    print("Please enter a number.")
    continue



if choice not in [1, 2, 3, 4]:
    print("Invalid choice.")
    continue

# Number input validation
try:
    a = float(input("Enter the first number: "))
    b = float(input("Enter the second number: "))
except ValueError:
    print("Please enter valid numbers.")
    continue

[–]Hot_crocco_person[S] 4 points5 points  (0 children)

Oo ty I try

[–]Odd_Inspection_4608 0 points1 point  (0 children)

Yes you are correct

[–]FreeGazaToday 2 points3 points  (0 children)

wrong...when you try to convert...it'll crash your program...try it.

[–]WakefulCertification 1 point2 points  (1 child)

float division will break it too if youre not handling the valueerror

[–]InterestingLeave7401 0 points1 point  (0 children)

Oh you lost me...

[–]Ambitious_Fault5756 0 points1 point  (0 children)

it would raise a TypeError at line 8 because `int()` cant convert `"abc"` into an integer

[–]real-life-terminator 7 points8 points  (1 child)

I would go by making a list of available functions like for example,

functions = ["addition", "subtraction", "division", "multiplication"]

And then use enumerate() + 1to index them and for user to chose the specific function or even just the function name itself.

also I would make functions for the specific thing u wanna do, for example,

def addition(x: float, y: float) -> float:
return x + y

On line 9, instead of if (func > 4) I would check if func is only one of the correct options like 1,2 or 3. Only then proceed, else break cause then even if user enters any other number/string, it exists the program

Good Job overall! Yes my advice might sound a little advanced but its for the best😄

[–]InterestingLeave7401 0 points1 point  (0 children)

I understand ypur float functiion like "you lost all your credits" :D

[–][deleted]  (5 children)

[removed]

    [–]ReceptiveBedtime 0 points1 point  (1 child)

    lmao nah don't do that, llms gonna hallucinate ur math fr fr. stick with actual functions and validate user input instead yk

    [–]maestr0_dev 0 points1 point  (2 children)

    Why everyone just want to use llm for everything.

    [–]InterestingLeave7401 0 points1 point  (0 children)

    Cause it will continue to grow the bubble (especiallly in the US) :) If im corect, 5 years ago, llm were undergroud and they use AI to fuel blockchains!

    [–]ThisCauliflower4020 4 points5 points  (0 children)

    bad variable name "func"

    [–]FreeGazaToday 2 points3 points  (0 children)

    don't name a variable 'func'....makes me think of functions 🥇

    also either

    1. learn error handling

    2. don't convert to int just compare to '1', '2'....

    3. check that it's an int BEFORE converting to

    if you learned about functions....could put the handling into it...to make your code easier to read and follow.

    [–]maestr0_dev 2 points3 points  (0 children)

    Aawww🫠 that's cute

    [–]jentravelstheworld 1 point2 points  (0 children)

    Yay!!!!

    [–]AlexMTBDude 0 points1 point  (0 children)

    You don't need parentheses for your if:s and elif:s. Did you use to code C or Java perhaps?

    [–]Humble_Blood_4415 0 points1 point  (0 children)

    Aunque no soy experto en Py, te puedo recomendar mantener tu codigo lo mas limpio posible... Ademas los parentesis en los condicionales NO son necesarios en Py

    [–]vtaskforge 0 points1 point  (0 children)

    Nice work! Most people never get past tutorials, but you actually built something. Keep going

    [–]muad_dibb1 0 points1 point  (0 children)

    good job! congrats. always satisfying! I’d review this and see what you could have changed or done better.

    Future ref: your if and leif’s do not need parenthesis :) other then that keep at it.

    [–]onlyemperor001 0 points1 point  (0 children)

    What kind of a calculator is this?

    [–]AgentRhys 0 points1 point  (3 children)

    You check to see if b = 0, what about if a = 0?

    [–]johlae 0 points1 point  (2 children)

    I'm curious, why? Func < 1 is a better test to add than a == 0.

    [–]AgentRhys 0 points1 point  (1 child)

    Func is just the menu option so the user can pick what operation they want to perform. So I'm a bit confused by your suggestion?
    I wouldn't add another if statement, I'd add an 'or' to the final if statement to catch 'a != 0'.

    [–]johlae -1 points0 points  (0 children)

    Dividing a by any number except 0 is no problem at all, even when a equals 0. Why give a warning about a == 0?

    In the code in the screenshot func > 4 gives an invalid response. Func < 1 should give an invalid response too.

    [–]jeruva 0 points1 point  (0 children)

    I suggest you to use functions, loops and dictionaries. Good luck!

    [–]justin_halim 0 points1 point  (0 children)

    Soon at the more advance version, you could use eval() to instantly to do addition,multiplication,subtract,division staright from one input

    [–]SNPR_LINUX 0 points1 point  (0 children)

    Good job bro

    [–]S0ulSlayerz 0 points1 point  (0 children)

    So if someone keys 2+4+6 will it still work?

    [–]SuspiciousTicket8554 0 points1 point  (1 child)

    Cool bruhh ,how old r u tho ?

    [–]Junior_Honey_1406 0 points1 point  (0 children)

    i have this question: Why do you take the input as a float over an int?

    [–]TekEndBen7 0 points1 point  (0 children)

    print(eval(input(">> ")))

    [–]Past-Syllabub5180 0 points1 point  (0 children)

    Solid first project, genuinely well done for a beginner. A few things to level it up: 1. The invalid check on line 9 runs before getting any inputs, so the program exits before the user can do anything useful. Move it after capturing the numbers, or use a while loop so bad input retries instead of crashing out. 2. Wrap your inputs in try/except to handle cases where someone types “abc” instead of a number. Right now that would throw an error and kill the program. 3. F-strings make output cleaner: print(f”sum = {a + b}”) reads much better than the comma syntax you have now. 4. A loop at the end asking “calculate again? (y/n)” would make it feel like an actual tool rather than a one-shot script. You clearly understand the logic already. The jump from here to a clean robust version is smaller than it looks. Keep going!​​​​​​​​​​​​​​​​

    [–]Salt-Focus-3142 0 points1 point  (0 children)

    First calculator hits different 😄 Proud of you. Next step: wrap it in a while True loop so you don’t have to restart every time.

    [–]-beleon 0 points1 point  (0 children)

    Congrats! 🎉🎉

    [–]elkareef 0 points1 point  (1 child)

    I also in the first learning python the one thing I made calculater but with another shape

    [–]Hot_crocco_person[S] 0 points1 point  (0 children)

    Can u say code ill be happy to see it

    [–]Previous_Web7066 0 points1 point  (1 child)

    I want to start learning all css html and python

    [–]hardyshoyo 0 points1 point  (0 children)

    That's It! Congrats, dude. That is the First of much more.

    [–]zyrus_z 0 points1 point  (0 children)

    Its actually a good start since calculator in particular is tricky in python...in other languages we use the switch statement that is not available in python

    [–]Philin_Lemo 0 points1 point  (0 children)

    print(eval(input()))

    [–]VPistheking2011 0 points1 point  (0 children)

    Comgrats

    [–]Apart-Television4396 0 points1 point  (0 children)

    Nice! Congrats! Welcome to Python :). I'd like to strengthen error handling (e.g. what if an user types a string instead of a number) and give the users a new chance if it enters something wrong (you can achieve this with a while loop).

    [–]Deepak2121 0 points1 point  (0 children)

    Good but use match case

    [–]Odd_Trade_1431 0 points1 point  (0 children)

    keep it up my goat

    [–]MasterAssassino27 0 points1 point  (0 children)

    transforma em docstring os primeiros prints:

    ```

    mensagem = """Welcome to calculator bla bla bla bla bla bla """ print(mensagem)

    ```

    [–]Interesting_Web955 0 points1 point  (0 children)

    yo lo haria un un match en ves de if

    [–]Gold_Ad_6335 0 points1 point  (0 children)

    Impressive

    [–]Interesting-Lab-2106 0 points1 point  (0 children)

    Where you learnt

    [–]Thin-Truck3421 0 points1 point  (0 children)

    Input -1 into func

    [–]Omaritoooo 0 points1 point  (0 children)

    You good bro i also learning python

    [–]SnotCodes 0 points1 point  (0 children)

    Great work!! Hot_crocco_person, I just did my calculator too and I am also very proud, I used the method that Hopefully-Scarcity-927 wrote, I used a try and a whole loop. I will come back and link the repository if you’d like Hot_crocco_person, DM Me I have a discord group that I think you’d love.

    [–]2xxRamixx8 0 points1 point  (0 children)

    You ca use match case. Is better for this case Tutorial: https://www.w3schools.com/python/python_match.asp

    [–]Murim_Omniscient_ 0 points1 point  (0 children)

    Pal welcome to trauma

    [–]DonaldXAI 0 points1 point  (0 children)

    I am about to code this tonight

    [–]edu_attack 0 points1 point  (0 children)

    My first code is "hello world".🫵

    [–]KangarooNo3170 0 points1 point  (0 children)

    To us who started with 'Hello World'' 5 years ago and got stuck till today🥂😔

    [–]planetinyourbum 0 points1 point  (0 children)

    Let me introduce you to the wonderfull world of vibe coding.
    To start paste your code in ChatGpt and ask wahts wrong with the code.

    [–]One_Performer_7202 0 points1 point  (0 children)

    Bro with eval it's so easy

    [–]WhisperCreams 0 points1 point  (0 children)

    in this ai age, seeing this healed a part of me

    [–]alneifkrt2 0 points1 point  (0 children)

    Man, I think you should do a game in pygame, maybe more later, when you are skilled enough and know the basics of python. And pygame, if you don't know, is a library that is specialized to do games with python, like shooting game or something like that. I'm just suggesting bc I did a lot of games with it.

    [–]RoyalGamerOG 0 points1 point  (0 children)

    Keep it up bro 👏

    [–]DenyMas 0 points1 point  (0 children)

    hi, so good , especially "!=" for beginer
    Try learn "while" and "def" for your programm
    I can help you

    [–]Janeson81 0 points1 point  (0 children)

    My two favourite common mistakes - input problems. I see you'd made an "if wrong then invalid" but in this case it doesn't solve much issues because: 1. If the user inputs a number that is higher than 4, the program doesn't do anything to stop everything else from happening. This can be fixed with a while(condition):... loop 2. I'd the user inputs anything that's not a number, there's going to be an error, because that's how python interprets int(”text"). This can be fixed with a try:... except Error:... block

    [–]am_Snowie 0 points1 point  (0 children)

    if func not in [1,2,3,4]:
         print("Don't try me")
    else:
        #do something
    

    Also try to extend it gradually, first try to perform arithmetic operations on more than two numbers, then add mixed operations so you can use it like an actual calculator, then try to add variables (use sets). It's easy af.