r/pythonhelp • u/Neat_Chip4684 • Aug 31 '21
HOMEWORK Help with Python exponential function
So, I started my coding adventure yesterday and started from "4 hours full course for beginners of python". I had problems understanding how below code works, it's exponential function and I can't really understand It.After defining a function, we make container called "result" where we store below list of numbers and I can't understand how its gonna make 2^3=8? How can list of numbers be multiplied by 2? Someone can help?


3
Upvotes
5
u/sentles Aug 31 '21
The variable
resultis an integer, not a list. That integer starts at 1.The loop that is run afterwards iterates through
range(pow_num). This is similar to a list, which contains every integer starting with 0 and ending withpow_num-1. You showcased this with the code below, where you run a loop iterating throughrange(3). In the first iteration,indexcontains 0, in the second it contains 1 and in the third, 2, thus the output.In the example posted,
range(pow_num)is only used to run the loop exactlypow_numtimes. The values thatindexcontains each iteration are never used.The variable
resultstarts at 1. Each iteration,resultis multiplied bybase_num(and the result is saved inresultagain). Since there will be a total ofpow_numiterations, in total,resultwill be multiplied bybase_numexactlypow_numtimes. Because it starts at 1, the final result will be 1*base_num*...*base_num = base_numpow_num.The below table showcases the value of
resultafter each iteration, if we runraise_to_power(2, 3):resultresult = 1result = result*base_num = 1*2 = 2result = result*base_num = 2*2 = 4result = result*base_num = 4*2 = 8Remember that this stops after the third iteration because it is iterating through
range(3), which is similar to[0, 1, 2], so it will run once for each number, for a total of three iterations.