Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何选择在python中重复程序_Python_Loops_Python 2.x - Fatal编程技术网

如何选择在python中重复程序

如何选择在python中重复程序,python,loops,python-2.x,Python,Loops,Python 2.x,我正在学习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 gu

我正在学习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":
x=int(原始输入('输入整数:'))
##从0开始猜测
ans=0
而ans*ans*ans如果x可以将所有内容放入函数中:

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()
def my_func():
x=int(原始输入('输入整数:'))
##从0开始猜测
ans=0
而ans*ans*ans如果将x作为函数路由的替代方法,则可以在while循环中执行,尽管使用函数会更简洁。你可以做:

choice = 'y'
while choice.lower() == 'y':
    #code for the game
    choice = raw_input ('run again? (y/n)')

还有另一种方法,类似于@xgord answer。 使用while循环。我写的东西更长,但对我来说更简单

repeat = False
while not repeat:
      # game code

play = input("Play again? (y/n)")
    if play == "y":
        repetition = False
    else:
        exit()

你可以把所有的东西都放在一个函数中,然后再次运行这个函数。我对编程还是很陌生,我怎么才能做到呢?我会调用这个函数而不是
all
,因为
all
是一个python内置函数。