File tree 1 file changed +36
-0
lines changed
1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change
1
+ """
2
+ == Raise base to the power of exponent using recursion ==
3
+ Input -->
4
+ Enter the base: 3
5
+ Enter the exponent: 4
6
+ Output -->
7
+ 3 to the power of 4 is 81
8
+ Input -->
9
+ Enter the base: 2
10
+ Enter the exponent: 0
11
+ Output -->
12
+ 2 to the power of 0 is 1
13
+ """
14
+
15
+
16
+ def power (base : int , exponent : int ) -> float :
17
+ """
18
+ power(3, 4)
19
+ 81
20
+ >>> power(2, 0)
21
+ 1
22
+ >>> all(power(base, exponent) == pow(base, exponent)
23
+ ... for base in range(-10, 10) for exponent in range(10))
24
+ True
25
+ """
26
+ return base * power (base , (exponent - 1 )) if exponent else 1
27
+
28
+
29
+ if __name__ == "__main__" :
30
+ print ("Raise base to the power of exponent using recursion..." )
31
+ base = int (input ("Enter the base: " ).strip ())
32
+ exponent = int (input ("Enter the exponent: " ).strip ())
33
+ result = power (base , abs (exponent ))
34
+ if exponent < 0 : # power() does not properly deal w/ negative exponents
35
+ result = 1 / result
36
+ print (f"{ base } to the power of { exponent } is { result } " )
You can’t perform that action at this time.
0 commit comments