【问题标题】:How to optionally repeat a program in python如何有选择地在python中重复一个程序
【发布时间】:2013-06-20 01:27:42
【问题描述】:

我正在学习 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”,接下来会发生什么?

【问题讨论】:

  • 你可以把所有的东西都放在一个函数里,然后再次运行这个函数。
  • 我对编程还是很陌生,我究竟要如何做到这一点?

标签: python loops python-2.x


【解决方案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()

【讨论】:

  • 我会将该函数称为 all 以外的其他名称,因为 all 是 python 内置函数。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

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

    repeat = False
    while not repeat:
          # game code
    
    play = input("Play again? (y/n)")
        if play == "y":
            repetition = False
        else:
            exit()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-20
      • 1970-01-01
      • 2015-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多