How to optionally repeat a program in python

匆匆过客 提交于 2020-01-30 11:13:05

问题


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 another cube root, or quitting.

Here's what I have come up with:

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":

what would go next, in case the person wants to do another problem and chose "Y"?


回答1:


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()



回答2:


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)')


来源:https://stackoverflow.com/questions/17203923/how-to-optionally-repeat-a-program-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!