How to optionally repeat a program in python

前端 未结 3 1592
滥情空心
滥情空心 2020-12-12 06:23

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

相关标签:
3条回答
  • 2020-12-12 06:55

    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()
    
    0 讨论(0)
  • 2020-12-12 07:05

    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)')
    
    0 讨论(0)
  • 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()
    
    0 讨论(0)
提交回复
热议问题