Click here to Skip to main content
15,921,113 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have big problem with one task. I'm a beginner by the way.
write a program that will calculate successive powers of the number 2 in the range 0 to 8 (inclusive).
display the result as:
0: 1
1: 2
2: 4
3: 8
4: 16
etc.
Please guy, help me, i'm a beginner, but this quest is quite difficult for me right now.

What I have tried:

Python
i=0
i+=1
x=2**i
for i in range(0,8):
    print(x)
Posted
Updated 3-Nov-20 0:26am
v2

1 solution

Look at your code:
Python
x=2**i
for i in range(0,8):
   print(x)
the value in x doesn't change inside the loop, so you will get 2 to the power of one printed each time.

Move the calculation inside the loop, and it'll work:
Python
for i in range(0,8):
   x=2**i
   print(x)
Or better:
Python
for i in range(0,8):
   print(2**i)
And discard x completely!
 
Share this answer
 
Comments
Jonasz Urban 3-Nov-20 6:35am    
Best solutions are the simplest one.. thanks a lot mate!
OriginalGriff 3-Nov-20 6:50am    
You're welcome!
CPallini 3-Nov-20 6:37am    
5.
Jonasz Urban 3-Nov-20 7:04am    
and how about displaying the result as:
0:1
1:2
2:4
etc?
OriginalGriff 3-Nov-20 7:42am    
How do you think?

What would you do to print two numbers on the same line if it wasn't in a loop?

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