0

我正在学习 python 并且有一个快速的问题。

我必须编写代码来找到立方根,我已经完成了。我想为用户提供计算另一个立方根或退出的选项。

这是我想出的:

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

如果这个人想要做另一个问题并选择“Y”,接下来会发生什么?

4

3 回答 3

1

您可以将所有内容放在一个函数中:

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()
于 2013-06-20T01:33:31.497 回答
1

作为函数路由的替代方案,您可以在 while 循环中执行此操作,尽管使用函数会更干净。你可以这样做:

choice = 'y'
while choice.lower() == 'y':
    #code for the game
    choice = raw_input ('run again? (y/n)')
于 2013-06-20T01:42:19.430 回答
0

还有另一种方式,类似于@xgord 的回答。使用一个while循环。我写的更长但对我来说更简单

repeat = False
while not repeat:
      # game code

play = input("Play again? (y/n)")
    if play == "y":
        repetition = False
    else:
        exit()
于 2020-08-27T13:46:31.087 回答