0

New to Python and programming, following an exercise from a book.

The program should take a value and keep printing "to the power of '+1' " on every new line, using WHILE.

My code:

x = 2

def powerof2_table_while(victim):
  line=1
  result=victim**(line)
  while result < 100:
""" want to write:    1.: 2 to the power of 1 is 2
               2.: 2 to the power of 2 is 4
               3.: 2 to the power of 3 is 8 """
    print (line,".:\t", victim, "to the power of\t",line,"\t is", result)
    line=line+1
    return line
  return line

resultat=powerof2_table_while(x)
print(resultat)

Instead of returning the table of line + victim to the power of (line) it gives back only the first line and then stops.

May I humbly ask for a help? Thanks a lot!

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
Jewenile
  • 195
  • 1
  • 15
  • You have multiple returns and one is inside the loop, So it will return on the first iteration. What exactly were you expecting to return? A value or a list of values? Given the function prints stuff, do you even need a return value? – Paul Rooney Feb 06 '17 at 09:09
  • you are having `return` in the `while` look which is causing your function to exit after the first iteration. Also check [Why would you use the return statement in Python?](http://stackoverflow.com/questions/7129285/why-would-you-use-the-return-statement-in-python) – Moinuddin Quadri Feb 06 '17 at 09:09
  • Answering myself. Like this it works. Result must be IN the while loop. http://www.fsiforum.cz/upload/soubory/nezarazene/code__rep.png Thanks everybody anyway! – Jewenile Feb 06 '17 at 09:10
  • I added the returns to the code because I assumed that it doesnt get the results of the indented blocks back out of them. – Jewenile Feb 06 '17 at 09:11

2 Answers2

1

You have return line inside your loop. As soon as the code hits a return it, well, returns; meaning the function ends and the loop does not continue.

You don't need that return; remove it.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • Hey Daniel! I saw that yo edited my post to correct formatting. May I ask for a short help with this so that my future posts dont lack this and dont disturb the other users? – Jewenile Feb 06 '17 at 09:13
  • @Jewenile Just select the part of code block and click the `{}` button in the editor – Moinuddin Quadri Feb 06 '17 at 09:15
  • 1
    There's a big yellow help box right next to the space where you enter your code which tells you what to do. – Daniel Roseman Feb 06 '17 at 09:17
0

As well as the unnecessary return, you also never update the result variable, you should move this inside of the while loop to avoid the infinite loop and incorrect outputs

result=victim**(line)
  while result < 100:

should be

result=0
while result < 100:
    result=victim**(line)
Sayse
  • 42,633
  • 14
  • 77
  • 146