how to code a python calculator

你。 提交于 2020-04-17 19:28:39

问题


I want to code a python calculator, but it goes wrong. Okay, I'll show you my code.

from time import sleep
print('Calculator v1.0 (Python 3.6.2)')
ans = input('Hello! Are you here for calculating?(y/n)')
if ans == 'y':
     print('OK! LOADING...')
     sleep(3)
elif ans == 'n':
     print('Oh, you're not going ahead... OK.')
     quit()

num1 = input('Input 1st number')
method = input('Input symbol(+,-,*,/):')
num2 = input('Input 2nd number')
ans = num1+method+num2
print('Answer is ', ans)

And my output....

Calculator v1.0 (Python 3.6.2)
Hello! Are you here for calculating?(y/n)y
OK! LOADING...
Input 1st number1
Input symbol(+,-,*,/):+
Input 2nd number1 
Answer is 1+1.

I want this output:

Calculator v1.0 (Python 3.6.2)
Hello! Are you here for calculating?(y/n)y
OK! LOADING...
Input 1st number1
Input symbol(+,-,*,/):+
Input 2nd number1 
Answer is 2

Somebody HELP!!!!!!!!!


回答1:


When you do num1+method+num2 it runs as a concatenation of a string for the method with a number (num1 & num2). What you need to do is actually operate on the two numbers by having different conditions.

from time import sleep
print('Calculator v1.0 (Python 3.6.2)')
ans = input('Hello! Are you here for calculating?(y/n)')
if ans == 'y':
     print('OK! LOADING...')
     sleep(3)
elif ans == 'n':
     print("Oh, you're not going ahead... OK.")
     quit()

num1 = int(input('Input 1st number'))
method = input('Input symbol(+,-,*,/):')
num2 = int(input('Input 2nd number'))

if (method == '+'):
    ans = num1 + num2
elif (method == '-'):
    ans = num1 - num2
elif (method == '*'):
    ans = num1 * num2
elif (method == '/'):
    ans = num1 / num2

print('Answer is ', ans)

I changed it so method is an actual operation on the two numbers and used something called "casting" to change the user input of num1 and num2 to integers.




回答2:


The typical way to do this without eval is to use a dictionary instead of a giant if/elif/else:

import operator # A module of functions that work like standard operators.

# A table of symbols to operator functions. 
op = {'+':operator.add,
      '-':operator.sub,
      '*':operator.mul,
      '/':operator.truediv}

# Make sure to convert the input to integers.
# No error handling here.  Consider if someone doesn't type the correct input.
# This is why eval() is bad.  Someone could type a command to delete your hard disk.  Sanitize inputs!
# In the below cases you will get an exception if a non-integer or
# invalid symbol is entered.  You can use try/except to handle errors.
num1 = int(input('Input 1st number: '))
method = op[input('Input symbol(+,-,*,/):')]
num2 = int(input('Input 2nd number: '))

ans = method(num1,num2)

print('Answer is ', ans)

Output:

Input 1st number: 5
Input symbol(+,-,*,/):/
Input 2nd number: 3
Answer is  1.6666666666666667



回答3:


I would use the python eval function:

ans = eval(num1+method+num2)

However you must be aware that this is a huge security risk, as it easily allows for code injection from a malicious user.




回答4:


Your operator is just a string, and you are only concatening strings. Check this answer Python:: Turn string into operator on how to convert the input string to operator.




回答5:


The variable 'ans' is a string, because it was used in the original input. Thus, when you try to add numbers and strings, it produces a string. That's not the only problem though, the way you are trying to do the calculations is entirely wrong. What you need is an if-elif-else statement for the operation.

Something like this should do it:

from time import sleep
print('Calculator v1.0 (Python 3.6.2)')
isCalc = input('Hello! Are you here for calculating?(y/n)')
if isCalc == 'y':
     print('OK! LOADING...')
     sleep(3)
elif ans == 'n':
     print("Oh, you're not going ahead... OK.") # watch out for apostrophes in strings
     quit()

num1 = input('Input 1st number: ')
method = input('Input symbol(+,-,*,/): ')
num2 = input('Input 2nd number: ')
ans = 0
if method == '+':
     ans = num1 + num2
elif method == '-':
     ans = num1 - num2
elif method == '*':
     ans = num1 * num2
elif method == '/':
     ans = num1 / num2

print('Answer is ', ans)

Of course, make sure to fix spacing and stuff. I haven't tested this but it should work.




回答6:


Here problem is, it is treating method as a string and it is not able to perform operation specified method. For this, you need to compare the value of the method with an operator.

from time import sleep
print('Calculator v1.0 (Python 3.6.2)')
ans = input('Hello! Are you here for calculating?(y/n)')

if ans == 'y':
   print('OK! LOADING...')
   sleep(3)
elif ans == 'n':
   print('Oh, you are not going ahead... OK.')
   quit()

num1 = int(input('Input 1st number\t'))
method = input('Input symbol(+,-,*,/):\t')
num2 = int(input('Input 2nd number\t'))

if method == '+':
    ans = num1 + num2
if method == '-':
    ans = num1 - num2
if method == '*':
    ans = num1 * num2
if method == '/':
    ans = num1 / num2

print('Answer is ', ans)



回答7:


print('Calculator v1.0 (Python 3.6.2)')

ans = input('Hello! Are you here for calculating?(y/n)')

if ans == 'y':
     print('OK! LOADING...')
     sleep(3)

elif ans == 'n':
     print("Oh, you're not going ahead... OK.")
     quit()

num1 = int(input('Input 1st number'))
method = input('Input symbol(+,-,*,/):')
num2 = int(input('Input 2nd number'))


if (method == '+'):
    ans1 = num1 + num2

elif (method == '-'):
    ans1 = num1 - num2

elif (method == '*'):
    ans1 = num1 * num2

elif (method == '/'):
    ans1 = num1 / num2

print('Answer is ', ans1)



回答8:


try my calculator, it is 100x better and 10x easier

from math import *

def example():
    example_i = input("\nExample: ")
    math(example_i)

def math(example_i):
    print(example_i,"=",eval(example_i))
    example()
example()



回答9:


print("Calculator v1.0 (Python 3.6.2)")
yes_or_no=input("Hello! Are you here for calculating?(y/n)")

if yes_or_no == 'y':
 while True:
  noone=input("Input 1st number : ")
  method=input("Input symbol(+,-,*,/) : ")
  notwo= input("Input 2nd number : ")
  nuummbbeer=(noone+method+notwo)

  given_number=nuummbbeer
  given_number_in_string=str(given_number)

  position_of_multiplication=(given_number_in_string.find("*"))
  position_of_addition=(given_number_in_string.find("+"))
  position_of_substraction=(given_number_in_string.find("-"))
  position_of_division=(given_number_in_string.find("/"))



  if position_of_multiplication >= 0:

    position_of_multiplication=(given_number_in_string.find("*"))
    first_no=float(given_number_in_string[0:position_of_multiplication])
    second_no=float(given_number_in_string[position_of_multiplication+1:16])
    print(f"answer is : {first_no*second_no}")
    a=input("")

  elif position_of_addition >= 0:

     position_of_addition=(given_number_in_string.find("+"))
     first_no=float(given_number_in_string[0:position_of_addition])
     second_no=float(given_number_in_string[position_of_addition+1:16])
     print(f"answer is : {first_no+second_no}")
     s=input("")

  elif position_of_substraction >= 0:

     position_of_substraction=(given_number_in_string.find("-"))
     first_no=float(given_number_in_string[0:position_of_substraction])
     second_no=float(given_number_in_string[position_of_substraction+1:16])
     print(f"answer is : {first_no-second_no}")
     s=input("")

  elif position_of_division >= 0:

     position_of_division=(given_number_in_string.find("/"))
     first_no=float(given_number_in_string[0:position_of_division])
     second_no=float(given_number_in_string[position_of_division+1:16])
     print(f"answer is : {first_no/second_no}")
     s=input("")



else:
   print("Exiting")


来源:https://stackoverflow.com/questions/46752268/how-to-code-a-python-calculator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!