I\'m learning python and had a quick question.
I have to write a code to find the cube root, which I\'ve done. I want to give the user the option of calculating an
There is also another way, similar to @xgord answer. Use a a while loop. What i wrote is longer but simpler to me
repeat = False
while not repeat:
# game code
play = input("Play again? (y/n)")
if play == "y":
repetition = False
else:
exit()
As an alternative to the function route, you could do it in a while loop, though it would be cleaner to use functions. You could do:
choice = 'y'
while choice.lower() == 'y':
#code for the game
choice = raw_input ('run again? (y/n)')
You can put all inside a function:
def my_func():
x = int(raw_input('Enter an integer: '))
## start guessing with 0
ans = 0
while ans*ans*ans < abs(x):
ans = ans + 1
print 'current guess =', ans
print 'last guess = ', ans
print 'ans*ans*ans = ', ans*ans*ans
##if its a perfect cube
if ans*ans*ans == abs(x):
## perfect, but negative
if x<0:
ans = -ans
print 'Cube root of ' + str(x)+ ' is ' + str(ans)
## If its not a cube at all
else:
print x, 'is not a perfect cube'
## Now to start a new calculation
again = raw_input('Find another perfect cube? (Y/N)')
if again == "N":
quit
if again == "Y":
my_func()
if __name__ == '__main__':
my_func()