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

Hi everybody i am trying to understand very well how work this program line by line. please help me 1)cubex = int(raw_input('Enter an integer: ')) 2)for ans in range(0, abs(x)+1): 3) if ans**3 == abs(x): 4) break 5)if ans**3 != abs(x): 6) print x, 'is not a perfect cube' 7)else: 8) if x < 0: 9) ans = -ans 10)print 'Cube root of ' + str(x) + ' is ' + str(ans) when the program reach at the line 3 and if the condition is true, it go to te line 4 to break to for loop, and what happen next? Python is a indented language so that mean it will execute de line 5 too, but in the case it got the true for the line 3, i think the next take should be the line 7! please if someone call help me to understand better this, i would be thankful!

OpenStudy (e.mccormick):

First, use \(\text{```}\) above and below a block of code to keep proper formatting when you post it here. See what it does to yours: ``` x = int(raw_input('Enter an integer: ')) for ans in range(0, abs(x)+1): if ans**3 == abs(x): break if ans**3 != abs(x): print x, 'is not a perfect cube' else: if x < 0: ans = -ans print 'Cube root of ' + str(x) + ' is ' + str(ans) ``` Nice and clean. OK, so first you take in a number. You do a for range to test the integers from 0 to the absolute value of the input. The break stops the for loop if things were found. The next if is for when the input is -1, 1, or 0. The else is to test for negative numbers in situations other that -1, 1, or 0. Finally you print out the cube root result no matter what.

OpenStudy (puzzler7):

If line 3 is true, the loop breaks, and line 5 is executed. Line 5 is not part of the for loop.

OpenStudy (anonymous):

thatś right, but the condition is not true so next is 7 and then 8, which might or might not be true and then the final print is done I think the last print statement should be under the if statement else: else: if x < 0: ans = -ans print 'Cube root of ' + str(x) + ' is ' + str(ans)

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!