如何阻止无限循环?

时间:2013-02-07 09:00:46

标签: python

问题:根据用户输入计算两个整数,第一个用户输入重复加倍,第二个除以2。在每一步,如果第二个数是奇数,则将第一个数的当前值加到自身,直到第二个数为零。

我的代码似乎没有完全运行,我得到一个无限循环我做错了什么?我正在使用python 2.7.3

##
## ALGORITHM:
##     1. Get two whole numbers from user (numA and numB).
##     2. If user enters negative number for numB convert to positive.
##     3. Print numA and numB.
##     4. Check if numB is odd if True add numA to numA.& divide numB by 2 using int division.
##        Print statement showing new numA and numB values.
##     5. Repeat steps 3 and 4 until numB is 0 or negative value. enter code here
##     6. Prompt user to restart or terminate? y = restart n = terminate
##
## ERROR HANDLING:
##     None
##
## OTHER COMMENTS:
##     None
##################################################################

done = False
while not done:

    numA = input("Enter first integer: ") # 1. Get two whole numbers from user (A and B)
    numB = input("Enter second integer: ") # 1. Get two whole numbers from user (A and B)
    if numB < 0:
        abs(numB) # 2. If user enters negative number for B convert to positive
    print'A = ',+ numA,'     ','B = ',+ numB
    def isodd(numB):
        return numB & 1 and True or False
    while numB & 1 == True:
        print'B is odd, add',+numA,'to product to get',+numA,\
        'A = ',+ numA,'     ','B = ',+numB,\
        'A = ',+ numA+numA,'     ','B = ',+ numB//2
    else:
            print'result is positive',\
            'Final product: ', +numA

    input = raw_input("Would you like to Start over? Y/N : ")
    if input == "N":
        done = True

2 个答案:

答案 0 :(得分:2)

问题:

  • 您无需撰写done = False; while not done:。只需无限循环(while True),然后在完成后使用break退出循环。

  • input 执行用户键入的代码(将其视为Python shell的功能)。您需要raw_input,它返回一个字符串,因此您需要将其传递给int

    numA = int(raw_input("..."))
    
  • abs(numB)将计算numB的绝对值,但不会对其执行任何操作。您需要将该函数调用的结果存储在numB numB = abs(numB)中。

  • 最近的Python版本中没有使用成语x and True or False;相反,使用True if x else false。但是,如果True其他x == True返回False与返回x相同,则返回while x == True

  • 您无需循环while x。只需循环numB

  • 您永远不会在内部循环中更改while True: A = int(raw_input("Enter first integer: ")) B = int(raw_input("Enter second integer: ")) if B < 0: B = abs(B) print 'A = {}, B = {}'.format(A, B) while B & 1: print 'B is odd, add {} to product to get {}'.format(A, A) A = # not sure what you're doing here B = # not sure what you're doing here else: print 'Finished: {}'.format(A) if raw_input("Would you like to Start over? Y/N : ").lower() == 'n': break 的值,因此它永远不会终止。


以下是我写的方式:

{{1}}

答案 1 :(得分:0)

这里的另一个问题是你试图在print语句中添加和除以数字,所以你不要在任何点改变整数numA和numB的值(也就是说,整数numA和numB将保留在整个计划中保持不变。)

要更改变量numA和numB,您必须:

  • 变量名=(某些函数作用于变量)

e.g。 numA = numA + 1将一个添加到numA