Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
478 views
in Technique[技术] by (71.8m points)

Addition function in Python is not working as expected

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

Code

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))
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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))

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}")

Old-style formatting:

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))

Or string concatenation:

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...