Home > Enterprise >  Creating a code that starts with the number 1 and then displays the result of half the previous numb
Creating a code that starts with the number 1 and then displays the result of half the previous numb

Time:09-02

Write Python code which starts with the number 1 and then displays the result of halving the previous number until the result is less than 0.001.

The expected output should be: 1.0 0.5 0.25 0.125 0.0625 0.03125 0.015625 0.0078125 0.00390625 0.001953125

ive tried a couple different things , still learning how to code , but i cant figure out what im missing

basenum = 1.000
endnum = 0.001
print(basenum)
while basenum > endnum:
    basenum //=2
    print(basenum)

how would i get it to work?

CodePudding user response:

Your problem is that you added an extra / in the line basenum //=2.
This should instead be basenum /= 2.

In Python, /= is similar to =, -=, and *=, where it modifies the variable on the left by the number on the right, in this case through divison.

Instead, //= is floor division. This is why you got the result of 1 and then 0, as 1 divide 2 is 0.5, which is then floored to 0.

Read more enter image description here

Using / operator: enter image description here

  • Related