Ask your own question, for FREE!
Computer Science 8 Online
OpenStudy (anonymous):

Using a for loop, write a program that prints out the decimal equivalents of 1/2, 1/3, 1/4,..., 1/10. I wrote as below : >>> x = [1/2.0, 1/3.0, 1/4.0, 1/5.0] >>> y = 0 >>> for i in x: ... y = y + 1 ... print x ... [0.5, 0.3333333333333333, 0.25, 0.2] [0.5, 0.3333333333333333, 0.25, 0.2] [0.5, 0.3333333333333333, 0.25, 0.2] [0.5, 0.3333333333333333, 0.25, 0.2] But output prints for every turn. Is it possible to print once ? Note: This is in python

OpenStudy (opcode):

I am not the well versed in Python, so I cannot help you with editing the output results, but would it not be simpler to do it as such?: ``` # !/usr/local/bin/python2.7 print "Decimal equivalents of 1/2, 1/3, 1/4, ..., 1/10:\n"; for i in range(2,11): print 1.0/i # You can see the output here: https://ideone.com/YzLwf2 ``` It still meets the requirements of using a for loop. :-) Sorry I could not be of more help. :-P

OpenStudy (anonymous):

I guess you should print out i instead of print out x

OpenStudy (opcode):

@sunlan how would printing out 'i' work in his code?

OpenStudy (anonymous):

this is what I write: x = [1/2.0, 1/3.0, 1/4.0, 1/5.0] y=0 for i in x: y += 1 print i and this is the print out: >>> 0.5 0.333333333333 0.25 0.2 >>>

OpenStudy (anonymous):

My understanding is that @sanwire just wants to print out once. Maybe he could dedent the print statement. But that way the for-loop he wrties will have no use.

OpenStudy (opcode):

Ah, I see how that works now. Cool. :-)

OpenStudy (anonymous):

Actually I think that the for-loop should be like the one you write :-)

OpenStudy (rsmith6559):

Your print statement is inside your loop, so it executes every time the loop executes. Move it out so that it just prints after the loop. Acutally, the only statements that you need in your program is: x = [1/2.0, 1/3.0, 1/4.0, 1/5.0] print x The division is done during the declaration of x.

OpenStudy (anonymous):

Thanks everyone for helping me out... I know that there is a range function out there. Just to write without range, I have tried for loop and the only problem with my solution i felt is, the output repetition.. looks like sunlan code might work.. let me test and update results.. :-)

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!