Function | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Function

# Write a function that accepts three numbers and calculates their product and returns the result. #declared my variables n1 = int(input()) n2 = int(input()) n3 = int(input()) def mul_num(a):# define a function a = n1 * n2 * n3 my_result = a return my_result print(mul_num(a))# call a function Below code is working fine: a = [2,3,5] #mul =1 def mul_num(n): mul=1 for n in a: mul = mul * n return mul print(mul_num(a)) What I did wrong in the first piece of code?

2nd Feb 2022, 3:30 AM
Knowledge Is Power
Knowledge Is Power - avatar
3 Answers
+ 3
def mul_num(a):# define a function Replace by def mul_num(n1,n2,n3):
2nd Feb 2022, 4:50 AM
Oma Falk
Oma Falk - avatar
+ 1
a=0 Add this to the first code
2nd Feb 2022, 3:32 AM
NEZ
NEZ - avatar
+ 1
Pay attention to scope of variables. If you wish to use n1, n2, n3 from outside the function then they should be declared in the function as global. The parameter a has no purpose as a function input. It gets overwritten inside the function, so it may as well be removed from the parameter list. Here is one way to fix the first function: def mul_num():# define a function global n1, n2, n3 a = n1 * n2 * n3 Be sure to remove the argument also where the main program calls mul_num().
2nd Feb 2022, 4:49 AM
Brian
Brian - avatar