Given this Python program:
num = input("Enter a number: ")
result = 1024
for i in range(num):
result = result / 2
print result
If the number you enter is 4, why is the output of this program 64?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Trace through the program to see what happens.
range(num)here isrange(4), which gives the values 0, 1, 2, and 3.When i = 0, we divide 1024 by 2 to get 512.
When i = 1, we divide 512 by 2 to get 256.
When i = 2, we divide 256 by 2 to get 128.
When i = 3, we divide 128 by 2 to get 64.
And voila! There’s your 64.
More generally, each iteration of the loop will divide
resultby 2, so after num iterations of the loop,resultwill be 1024 / 2num. Since 1024 = 210, this means that the result is 210 / 2num = 210 – num. That said, ifnum > 10, becauseresultis an integer, Python will round down to zero. In other words:range(num)is the empty range and the program prints 1024.Hope this helps!