Python 中的加法函数未按预期工作 [英] Addition function in Python is not working as expected

查看:39
本文介绍了Python 中的加法函数未按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试创建一个函数,我想用它来进行数学运算,例如(加法和乘法),我可以提示值,并且当我插入值时,结果没有按预期返回.在此处输入图片描述

I tried to create a function using which I want to do mathematical operations like (Addition and Multiplication), I could able to prompt the values and when I insert the values result is not returning as expect. enter image description here

代码

def addition(num1,num2):    
    return num1+num2 def
multiplication(num1,num2):
    return num1*num2

print("1.addition") 
print("2.multiplication") 
choice  = int(input("Enter Choice 1/2"))


num1 = float(input("Enter First Number:")) 
num2 = float(input("Enter Second Number:")) 
sum = float(num1)+float(num2) 
multiply = float(num1)*float(num2) 
if choice == 1:     
    print("additon of {0} and {1} is".format(num1,num2, sum)) 
elif choice == 2:   
    print("additon of {0} and {1} is".format(num1,num2, multiply))

推荐答案

你不需要函数,也不需要 summultiply 变量,只需将操作放入str.format(),你错过了最后一个位置.

You don't need the functions nor the sum or multiply variables, just put the operation in str.format(), and you were missing the last position.

# def addition(num1,num2):  
#     return num1+num2
# def multiplication(num1,num2):
#     return num1*num2

print("1.addition")
print("2.multiplication") 
choice = int(input("Enter Choice 1/2"))

num1 = float(input("Enter First Number:"))
num2 = float(input("Enter Second Number:"))
# sum = float(num1)+float(num2)
# multiply = float(num1)*float(num2) 
if choice == 1: 
    print("additon of {0} and {1} is {2}".format(num1,num2, num1 + num2))
elif choice == 2:
    print("additon of {0} and {1} is {2}".format(num1, num2, num1 * num2))

并且知道您可以使用 fstrings (>= Python 3.6):

And know that you can use fstrings (>= Python 3.6):

if choice == 1:
   print(f"additon of {num1} and {num2} is {num1 + num2}")
elif choice == 2:
   print(f"additon of {num1} and {num2} is {num1 * num2}")

旧式格式:

if choice == 1:
   print("additon of %s and %s is %s" % (num1,num2, num1 + num2))
elif choice == 2:
   print("additon of %s and %s is %s" % (num1, num2, num1 * num2))

或字符串连接:

if choice == 1:
   print("additon of " + num1 + " and " + num2 + " is " + (num1 + num2))
elif choice == 2:
   print("additon of " + num1 + " and " + num2 + " is " + (num1 * num2))

每个人都以不同的方式做事,有时了解所有人是有用的.

Each person does it a different way and it's useful to know all of them sometimes.

这篇关于Python 中的加法函数未按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆