Click here to Skip to main content
15,891,204 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm studying the basics of Python watching the 4,5 hours YouTube video from freeCodeCamp.
I reached the for-loops, and after seeing one of examples of how we can use them I wanted to write a code doing the same thing but not using the for-loop (I often do such things, that helps me understand the material I'm covering better). I tried to write a code, and according to everything I know about Pyhton (not much), this must work. But as the result I get that neither "i" nor "result1" is used and the output is "None".

What I have tried:

Python
<pre>
def raise_to_power_1(base1, power1):
    i = 0
    result1 = 1
    if i < power1:
        result1 = result1 * base1
        i = i + 1
    else:
        return result1
Posted
Updated 12-Feb-20 23:39pm
v2

for is a loop: it repeats the code inside the loop body until the condition is no longer true.
Your code doesn't - it performs it once, and then either returns 1 or just spontaneously ends without any return value.

I think you need to either study your videos rather better (and most YouTube development tutorial videos are total garbage) or try learning from a better source - a book or course perhaps - which explains what a loop is rather than assuming you can replace it without any such structure!
 
Share this answer
 
Comments
Rodion Mikhailov 13-Feb-20 5:20am    
I see, so then it must work well with while-loop:

def raise_to_power2(base2, power2):
    i = 0
    result2 = 1
    while i < power2:
        result2 = result2 * base2
        i = i + 1
    print(result2)


raise_to_power2(5, 6)
OriginalGriff 13-Feb-20 6:30am    
That's better!
Your algorithm needs an iteration your implementation doesn't provide. Try
Python
def raise_to_power_1(base1, power1):
  i = 0
  result1 = 1
  while True:
    if i < power1:
      result1 = result1 * base1
      i = i + 1
    else:
      return result1

print(raise_to_power_1(5,2))


Or even (since: "To iterate is human, to recurse, divine")
Python
def raise_to_power_1(base1, power1):
  if ( power1 == 0):
    return 1
  return base1 * raise_to_power_1(base1, power1-1)

print(raise_to_power_1(5,2))
 
Share this answer
 
v3
Don't wast your time on Youtube, Python.org provides a full tutorial at The Python Tutorial — Python 3.7.6 documentation[^].
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900