Python Forum
BEGINNER: My calculator doesnt work
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
BEGINNER: My calculator doesnt work
#6
@perfingo is not very explicit enough that eval() could be dangerous, so be careful when using it

as an alternative to avoid using huge if/elif/else block is to use operator module

from operator import add, mul, sub, truediv 
ops = {'+':add, 'plus':add, '-':sub, 'minus':sub,
       "multiplication":mul, "*":mul, "/":truediv, "divide":truediv}

num1 = float(input ("Insert number: "))
operator = input ("What operation do you want to do: ").lower()
num2 = float(input ("And the second number: "))

try:
    print(f'result: {ops[operator](num1, num2)}')
except KeyError:
    print("Sorry, operator not identified, please try again")
output(multiple runs)
Output:
Insert number: 5 What operation do you want to do: + And the second number: 4 result: 9.0
Output:
Insert number: 5 What operation do you want to do: minus And the second number: 3 result: 2.0
Output:
Insert number: 4 What operation do you want to do: % And the second number: 3 Sorry, operator not identified, please try again
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Messages In This Thread
BEGINNER: My calculator doesnt work - by iskov - Oct-09-2019, 06:12 AM
RE: BEGINNER: My calculator doesnt work - by buran - Oct-09-2019, 06:16 AM
RE: BEGINNER: My calculator doesnt work - by iskov - Oct-09-2019, 07:02 AM
RE: BEGINNER: My calculator doesnt work - by buran - Oct-09-2019, 07:45 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  print doesnt work in a function ony 2 303 Mar-11-2024, 12:42 PM
Last Post: Pedroski55
  Need some help trying to get my Python mortgage amortization calculator to work prope IamSirAskAlot 4 15,767 Feb-12-2024, 10:53 PM
Last Post: BerniceBerger
  Pydoc documentation doesnt work Cosmosso 5 4,382 Nov-25-2023, 11:17 PM
Last Post: vidito
  pip install requests doesnt work misodca 8 6,154 Jul-07-2023, 08:04 AM
Last Post: zyple
  Beginner: Code not work when longer list raiviscoding 2 823 May-19-2023, 11:19 AM
Last Post: deanhystad
  Ldap3 Python print(conn.entries) doesnt work ilknurg 15 5,774 Dec-28-2022, 11:22 AM
Last Post: shad
  pip install pystyle doesnt work person_probably 2 2,119 Sep-23-2022, 02:59 PM
Last Post: person_probably
  Why doesnt chunk generation work? LotosProgramer 1 1,949 Apr-02-2022, 08:25 AM
Last Post: deanhystad
  if conditions in the for indentation doesnt work ? Sutsro 6 3,934 Jun-15-2021, 11:45 PM
Last Post: bowlofred
  I have two Same Code but One of them Doesnt Work beginner721 6 3,094 Jan-22-2021, 10:56 PM
Last Post: beginner721

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020