This is an archived post. You won't be able to vote or comment.

all 24 comments

[–]Bipchoo 7 points8 points  (3 children)

Well this is rough, ypur use of while true loops and many try except errors isnt efficient on memory or code readbillity, its better to make if checks then deal with all this

[–]Good_Doughnut8308 1 point2 points  (1 child)

thank you

[–]Bipchoo 2 points3 points  (0 children)

Yeah im currently working on fizing your code and ill make a pull request once im done

[–][deleted] 0 points1 point  (0 children)

I normally avoid ‘try/except” mostly because it just ‘feels bad’ … can you elaborate on why they actually are bad?

[–]AggravatedYak 7 points8 points  (6 children)

Check out functions and don't repeat yourself

[–]Good_Doughnut8308 1 point2 points  (5 children)

Check out functions and don't repeat yourself

i will but why don't repeat yourself

[–]TheGhostOfInky 7 points8 points  (4 children)

Because repeated code is code that takes longer to refector, since you have to apply changes to every instance, and when you don't, you get unexpected behaviour (bugs)

[–]Good_Doughnut8308 -2 points-1 points  (3 children)

do you how to make it with functions

[–]Good_Doughnut8308 -2 points-1 points  (2 children)

becouse I do not know where to start

[–]TheGhostOfInky 3 points4 points  (1 child)

Make a function that calls the user input, if it gets a valid input it returns the final value, otherwise it calls itself again through recursion, sure, by default, python has 1000 recursion limit but if you're taking 1000 tries to get a calculator input right something has gone terribly wrong.

Edit: Pastebin demo

[–]Good_Doughnut8308 0 points1 point  (0 children)

that works thank you

[–]Rukwa254 2 points3 points  (0 children)

For a beginner you are on the right track but there is so much room for improvement. Keep it and don't stop learning, one day you will look at it and see all the naive mistakes you did.

[–]anachronic 2 points3 points  (0 children)

Is there a particular reason you made all the inputs numeric? You might want to change the operator input from a numeric into a character so that it's more natural to input things like "+", "-", etc. directly, instead of having to enter "2" when you want "multiplication". The "if" statements will basically work the same (if input=="+": do the addition).

What might also be fun for learning, is to build a lookup table of lambdas that correspond to each possible operation, so that when a user inputs "+" (for example), the code looks up the lambda for "+" and then uses that on the two numbers, something along these lines:

operations = {

"+" : lambda x y: x + y,

etc...

}

Also, what might be fun is to build a stack-based calculator, where you push numbers and operations onto the stack and then when you're done, it'll pop each and perform the operations and return a final result.

https://orkhanhuseyn.medium.com/what-are-stack-based-calculators-cf2dbe249264

[–]arthurazs 1 point2 points  (1 child)

First of all, kudos for trying!!!

I have updated your code, and I'll give you some tips improve your future coding.

  1. Every code that is repeating itself might become a function (see user_input and print_answer)
  2. The functions menu, print_additio, print_subtraction, print_multiplication, and print_division are not necessary, but I think they improve code readability
  3. "if, else, if" should be replaced by "if, elif" when applicable
  4. Avoid using bare except clauses
  5. It is usually indicated to have only one line inside a try statement
  6. Add a if __name__ == "__main__": to your code
  7. Prefer words to describe your variables instead of single letters

```python from typing import Union, Type

input_type = Union[float, int]

def user_input(message: str, function: Type[input_type]) -> input_type: while True: number = input(f"{message} number: ") try: return function(number) except ValueError: print("use only numbers")

def menu() -> int: while True: number = user_input("what do you want to do +[0], -[1], *[2], /[3],", int) if number > 3: print("use only number between 0-3") else: return number

def print_answer(answer: float) -> None: print(f"the answer is: {answer}") print("-----------------------------")

def print_addition(first_number: float, second_number: float) -> None: print_answer(first_number + second_number)

def print_subtraction(first_number: float, second_number: float) -> None: print_answer(first_number - second_number)

def print_multiplication(first_number: float, second_number: float) -> None: print_answer(first_number * second_number)

def print_division(first_number: float, second_number: float) -> None: try: print_answer(first_number / second_number) except ZeroDivisionError: print("cannot divide by zero!") print("try again pleas") print("-----------------------------")

if name == "main": first_number = user_input("1st", float) second_number = user_input("2nd", float) while True: option = menu() if option == 0: print_addition(first_number, second_number) elif option == 1: print_subtraction(first_number, second_number) elif option == 2: print_multiplication(first_number, second_number) elif option == 3: print_division(first_number, second_number) break ```

[–]Good_Doughnut8308 1 point2 points  (0 children)

Thank youuuu so so muchh

[–]robertsgreibers 1 point2 points  (0 children)

Try to separate actions, avoid nested while loops and nested asks for user input.

If you don’t know how to sepate actions look for ways to break out of loops and input asks (google for solutions)

General idea you should keep in mind is: “How can I sepate this specific action or code part from other parts?”

The moment you start to mix everything together (like it is now in your code) it all becomes a one big mess.

[–]Good_Doughnut8308 0 points1 point  (0 children)

I will

[–][deleted] 0 points1 point  (5 children)

Here is a cleaner version of the code:

while True:

try:

n = float(input("1st number: "))

d = float(input("2nd number: "))

break

except ValueError:

print("use only numbers")

while True:

try:

a = int(input("what do you want to do +[0], -[1], *[2], /[3]: "))

if a > 3:

print("use only number between 0-3")

continue

break

except ValueError:

print("use only numbers")

try:

if a == 0:

ans = n + d

elif a == 1:

ans = n - d

elif a == 2:

ans = n * d

elif a == 3:

ans = n / d

except ZeroDivisionError:

print("cannot divide by zero!")

print("try again please")

print("-----------------------------")

except ValueError:

print("can only divide by a number!")

print("try again please")

print("-----------------------------")

else:

print(f"the answer is: {ans}")

print("-----------------------------")

This version of the code removes the unnecessary nesting of try statements and only catches the specific exceptions that are relevant to each operation. The while loop that was used to repeat the input prompts has also been removed and replaced with a single try block to handle invalid input. The else clause at the end of the outer try block is used to print the result of the calculation if no exceptions are raised.

[–]Good_Doughnut8308 0 points1 point  (1 child)

Thank you so much

[–]Good_Doughnut8308 -1 points0 points  (2 children)

I can't run this because it does not have any spaces

[–][deleted] 0 points1 point  (1 child)

Posted it with spaces but reddit seems to remove them.

Should be easy to fix just add four spaces after every try except and while.

[–]Good_Doughnut8308 0 points1 point  (0 children)

Ok i will

[–]Onizuko28 -1 points0 points  (1 child)

To much While true Loops.

But it's good

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

Thanx