如何让我的程序在Python中返回到开头?

时间:2012-03-03 17:16:20

标签: python

我是一个非常新的程序员,只是为了好玩而编程。我通常用一系列while循环来编写程序,以便在不同的时间到达程序的不同部分。这可能不是最好的方式,但我知道怎么做。

例如,我正在开发一个在shell中运行的小程序,用于解决方程。这是该计划的一部分,应该让你回到起点。

while loop==4:
    goagain = raw_input("Would you like to do the equation again? (Y/N)")
    if goagain == "Y":
        #Get values again
        loop=2
    elif goagain == "N":
        print "Bye!"
        #End program
        loop=0
    else:
        print"Sorry, that wasn't Y or N. Try again."

我将它设置为while while while = = 2,它获取要放入等式的值,而loop == 0,没有任何反应。

我遇到的问题是,当我的循环变回2时,程序就在那里结束。它不想在代码中返回我告诉它在loop == 2时做什么。

所以我需要知道的是如何让我的程序返回到该部分。我应该使用与while循环不同的方法吗?或者有没有办法让我的程序回到那个部分?

谢谢!

5 个答案:

答案 0 :(得分:5)

更好的方法是做这样的事情:

while True:
    goagain = raw_input("Would you like to do the equation again? (Y/N)")
    if goagain == "Y":
        #Get values again
        pass #or do whatever
    elif goagain == "N":
        print "Bye!"
        #End program
        break
    else:
        print"Sorry, that wasn't Y or N. Try again."

答案 1 :(得分:1)

只有当循环等于4时才会迭代。因此,对于示例,您给出了loop = 2和loop = 0将具有相同的效果。

答案 2 :(得分:1)

首先,循环条件指出: -

while loop == 4:

这意味着只要变量'loop'的值保持为4,就会执行循环。但是,因为你为循环分配了2,所以不满足条件,并且控制退出循环。一种解决方案是将条件改为: -

while loop == 2:

或者,另一种解决方案是删除语句,将语句分配为2循环。

但是,由于你在goagain中获得了Y / N值,更好的方法是: -

done = False
while not done:
  goagain = raw_input("Would you like to do the equation again? (Y/N)")
  if goagain == 'Y':
    #Get values
  elif goagain == "N":
    print "Bye!"
    #End program
    done = True
  else:
    print"Sorry, that wasn't Y or N. Try again."

答案 3 :(得分:0)

当用户输入Y时,为什么要将Loop更改为2?如果用户输入yes,则收集值然后执行方程求解器,然后循环返回。

while loop==4:
    goagain = raw_input("Would you like to do the equation again? (Y/N)")
    if goagain == "Y":
        #Get values again
        #Solve your equation here
    elif goagain == "N":
        print "Bye!"
        #End program
        loop=0
    else:
        print"Sorry, that wasn't Y or N. Try again."

答案 4 :(得分:0)

你可以这样做..这个程序将检查一个数字是否为素数并找到阶乘...

while input('Enter yes to start no to exit...: ') == 'yes':
    print('Enter your choice [1] to find prime no. and [2] to calc. factorial.')
    choice = int(input('Enter your choice: '))
    num = int(input('Enter number: '))
    def prime(number):
        if number == (1 or 2 or 3 or 5 or 7):
            print('%d is a prime number..:)' %number)
        else:
            for x in range(2,number):
                if number%x == 0:
                    print('%d is not a prime number..' %number)
                    break
                else:
                    print('%d is a prime number..' %number)
                    break
    def fact(number):
        fact = 1
        for x in range(1,number+1):
            fact = fact*x
        print('Factorial of %d is %d' %(number,fact))
    switch = { 1:prime , 2:fact}
    try:
        result = switch[choice]
        result(num)
    except KeyError:
        print("I didn't get that...")

打印( '再见...:)')