+ 3

Need more info on functions

Please someone help on describing step by step: def power(x,y): if y==0: return 1 else: return x * power(x, y-1) print(power(2,3)) Output is: 8

18th Jun 2018, 7:02 AM
Dolan
Dolan - avatar
8 ответов
+ 4
power takes the first argument as the number, while the second argument as the power. so this is what is happening behind the scenes 2 * power(2, 3-1) 2 * power(2,2) 2* 4 8
18th Jun 2018, 7:17 AM
ghali lawal
ghali lawal - avatar
+ 3
ghali Thank you my friend for your kind help. actually I heard about built-in function <pow(x,y)> but here, power is not defined to be as (x**y)!! that’s why it’s not clear to me.
18th Jun 2018, 8:17 AM
Dolan
Dolan - avatar
+ 2
ghali lawal how do you count (2 * power (2,2))?! how power(2,2) will be 4?!
18th Jun 2018, 7:56 AM
Dolan
Dolan - avatar
+ 2
Jay Matthews how do u simplify (return x * power(x, y-1)) for example if we have (2,3), the result would be: return 2 * power(2, 3-1) then, we have return 2 * power(2,2). how do you get the result of (power 2,2) to be multiplied by x(which is 2)!?
18th Jun 2018, 8:00 AM
Dolan
Dolan - avatar
+ 2
Dolan power(2,2) is 4, lemme evaluate: power(2,2) = 2 ** 2 = 4 power(3,2) = 3 ** 2 = 9 in short, you are squaring the number on the left
18th Jun 2018, 8:12 AM
ghali lawal
ghali lawal - avatar
+ 2
Dolan, power doesnt need to be defined, it is a built in function, so when whenever you call it, it automatically does power(x**y), hope you get it
18th Jun 2018, 8:19 AM
ghali lawal
ghali lawal - avatar
+ 2
Jay Matthews , Untill here is quite clear, but here we don’t have the built-in fiction <pow(x,y)> and x ** y is not defined to the (power) function. it is (power) not (pow). that’s why it is not clear.
18th Jun 2018, 8:24 AM
Dolan
Dolan - avatar
+ 1
ghali lawal , Thank you.
18th Jun 2018, 8:20 AM
Dolan
Dolan - avatar