#πŸ”’ Simple Calculator Practice

12 messages Β· Page 1 of 1 (latest)

copper hawk
#

I'm a beginner at this so just getting the practice in.
Would like to hear some ways that this could improve from more experienced guys,allthough it's not much code, i know.

radiant riverBOT
#

@copper hawk

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

sonic kestrel
#

You can save the result to a variable result, and in the end print The result is ..., without doing it in every if. So, instead of

num = int(input())
if num < 10:
     print(f"The result is {num + 10}")
else:
    print(f"The result is {num - 10}")```You can have ```py
num = int(input())
result = 0
if num < 10:
    result = num + 10
else:
    result = num - 10
print(f"The result is {result}")```
#

Which is way cleaner imho

copper hawk
molten mason
#

I honestly don't see a point in trying to make "better" since it already works

#

but ig you can store the expressions in a dictionary

#
first = int(input("Type the first number > "))
second = int(input("Type the second number > "))
question = input("What do you want to do?[+ or - or * or /]: ")

operations = {
  "+": lambda a, b: a + b,
  "-": lambda a, b: a - b,
  "*": lambda a, b: a * b,
  "/": lambda a, b: a / b
}

try:
    print(f"The result is {operations[question](first, second)}")
except ZeroDivisionError:
    print(f"Can't divide {first} by 0")
#

this code does the same thing sort of

#

@copper hawk

radiant riverBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.