根据用户输入计算

  • 本文关键字:计算 用户 python
  • 更新时间 :
  • 英文 :

a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))

calc = ('Please enter your calculation, + to add, - to subtract, * to multiply and / to divide:')
if calc == ('+'):
def add(a,b):
add = a + b
return add
print("The Sum is: ", str(a)+str(b))

if calc == ('-'):
def sub(a, b):
diff = a - b
return diff
print("The Difference is: ", str(a)+str(b))
if calc == ('*'):
def mul(a, b):
multi = a*b
return multi
print("The product is: ", str(a)+str(b))
if calc == ('/'):
def div(a, b):
divi = a/b
return divi
print("The division is: ", str(a)+str(b))

所以,如果我输入2为a, 4为b,然后打印说添加,它应该只显示6,但它粘在一起为24,所有的显示,所以加法减法,等等,所有的都是24,请帮助我。编辑:它不会问我是否要加、减、乘或除

您似乎没有在每个块中调用函数,只是定义它。代码中似乎也有一些缩进错误,并且缺少用于设置calc值的输入关键字。试试下面的代码,看看它是否有效。

a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))

calc = input('Please enter your calculation, + to add, - to subtract, * to multiply and / to divide:')
if calc == ('+'):
def add(a,b):
add = a + b
return add
print("The Sum is: ", add(a, b))

if calc == ('-'):
def sub(a, b):
diff = a - b
return diff
print("The Difference is: ", sub(a, b))
if calc == ('*'):
def mul(a, b):
multi = a*b
return multi
print("The product is: ", mul(a, b))
if calc == ('/'):
def div(a, b):
divi = a/b
return divi
print("The division is: ", div(a, b))

你应该简化你的操作,只保留a和b的操作,去掉函数:

a = int(input("Enter the first number: ")) 
b = int(input("Enter the second number: "))
calc = input('Please enter your calculation, + to add, - to subtract, * to multiply and / to divide: ')
if calc == ('+'): 
add = a + b 
print("The Sum is:", add)
if calc == ('-'): 
diff = a - b 
print("The Difference is: ", diff)
if calc == ('*'): 
multi = a * b 
print("The product is: ", multi)
if calc == ('/'): 
divi = a / b 
print("The division is: ", divi)

问题是你不打印任何函数的结果,你打印两个数字的连接,你应该在if语句中调用函数,而不是声明它。

首先,应该在if语句之外定义函数。

def add(a,b):
return a+b

def multiply(a,b):
return a*b
def substract(a,b):
return a-b
def divide(a,b):
"Note here that b should be different from 0"
return a/b

a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))

calc = input('Please enter your calculation, + to add, - to subtract, * to multiply and / to divide:')

if calc == ('+'):   print("The Sum is: ", add(a,b))
if calc == ('-'):   print("The Difference is: ", substract(a,b))
if calc == ('*'):   print("The multiplication is: ", multiply(a,b))
if calc == ('/'):   print("The division is: ", divide(a,b))

我希望这个对你有帮助!

必须在输入前输入

  • calc = input('请输入您的计算,+表示加,-表示减,*表示乘,/表示除')

  • 在产品条件条件中添加"*">

  • 从每个if条件的print条件中删除str函数

最新更新