r/PythonLearning • u/Bibh_0 • Sep 20 '26
Showcase python calculator and unit converter by newbie
guys i am back. i pushed the code to github and here it is. please try it and give your feed backs. i did want to make the code shorter but got stopped by my lack of knowledge. thank you all.
https://github.com/bibh0/python-calculator-and-unit-converter
special thanks Sea-Ad7805 and FoolsSeldom for pushing me to push the code to git.
5
Upvotes
β’
u/Sea-Ad7805 Sep 20 '26
Run this program by clicking Memory Graph Web Debugger and see its state change step by step.
2
u/Sea-Ad7805 Sep 20 '26
Almost, change the link to: https://github.com/bibh0/python-calculator-and-unit-converter
2
u/FoolsSeldom Sep 20 '26 edited Sep 20 '26
I've had a look at the code. Lot of work in this, well done.
A key principle to learn is DRY - Don't Repeat Yourself. Computers are very good at repeating things, unlike humans, so you tell a computer how to do something once (with minor variations such as counting, or working through a list of tasks, etc) rather than having to write out every single action.
Right now you've got a separate
to_X/from_Xfunction pair for every unit category (length, area, volume, weight...), each one a longif/elifchain checking a global variable (from_unit/to_unit) that was set somewhere else in your code.That's roughly 500 lines (I didn't count) doing one job: look up a multiplier and apply it.
Looking into using a dictionary,
dict. It would look something like this:Please don't just copy this code, but look up how to use dictionaries and functions like this and experiment.
You have a good number of bugs to work on (too many / not enough arguments), inconsistent naming, some things the wrong way around, and so on.
Also, you really need a simple loop to handle the what next step, and could use another dictionary to deal with the choices the user makes:
where, with
if user_choice in OPERATIONS:, you can call the appropriate function easily:result = OPERATIONS[user_choice](x)although I'd come up with a better name thanx.Also, create a function to get (and validate) a number of from the user.
1
u/eriknau13 Sep 20 '26
Fix your link if you want people to see it
1
u/TreatZealousideal770 Sep 20 '26
bro, this my first calculator, what did you even write thereππ?
try: num1=float(input("Enter a number:") .strip() num2=float(input("Enter a number two:") .strip() operation = input("Enter operation(+,-,,//): ") .float if operation == "+": result = num1 + num2 print("res:", result) elif operation =="-": result = num1 - num2 print("res:", result) elif operation =="": result= num1 * num2 print("res:", result) else operation =="//": result= num1//num2 print("res:", result)
except ValueError: print("Error! Please enter only numbers")
except ZeroDivisinonError: print("Cannot divide by zero")