Why Code Output was Inverted

Hi. Please help me understand why the line in the below code shows the certain output.
Thank you.

string=str(1/3)
dummy=''
for character in string:
    dummy=character+dummy  # why did dummy become 3333333333333333.0 at this point?
print(dummy[-1])

Think carefully about the logic. The first time through the loop, character is '0' and dummy was '', so it becomes '0', right? Then, the second time through, character is '.'… what will happen if you put that before dummy and assign it back? Work through it step by step, and you can see the result clearly.

Use print to understand code. Add print(dummy) after dummy = ... to see what happens.

Hi,

try this way. Run the code to get the results then follow along for each iteration. I have included the results in equation form on how the first six results would appear. Notice how the ‘dummy’ result from the previous equation becomes the new ‘dummy’ value on the right side of the equation for the subsequent iteration.

Your will need to cross reference the values of the ‘string’ characters as you are stepping through the equation.

string=str(1/3)
print('\nString is: ', string)
dummy=''

print('\ndummy = character + dummy')
print('\n0 = 0 + " "         -- First iteration')
print('.0 = . + 0          -- Second iteration')
print('3.0 = 3 + .0        -- Third iteration')
print('33.0 = 3 + 3.0      -- Fourth iteration')
print('333.0 = 3 + 33.0    -- Fifth iteration')
print('3333.0 = 3 + 333.0  -- Sixth iteration')

print('\n')
print('Notice how the values are being stacked backwards, one-by-one during each iteration.')      
for character in string:
    
    dummy=character+dummy  # why did dummy become 3333333333333333.0 at this point?
    print(dummy)
    
print('\n')
print('dummy is: ', dummy)
print('The value of the character 1 position from the right (dummy[-1]) is: : ', dummy[-1])

Thank you for explaining. Slipped my mind that character should go before dummy accdg to the formula. Again, thanks!

I appreciate your thorough and detailed step-by-step explanation.
I get it now.

Thank you so much!

1 Like