[英]How to stop infinite loop?
问题:根据用户输入计算两个整数,第一个用户输入重复加倍,而第二个除以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
问题:
你不需要写done = False; while not done:
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 if x else false
。 但是,如果x == True
True
则返回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
这里的另一个问题是你试图在print语句中添加和除以数字,所以你不要在任何点改变整数numA和numB的值(也就是说,整数numA和numB在整个过程中保持不变程序)。
要更改变量numA和numB,您必须具有:
例如numA = numA + 1
将一个添加到numA
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.