如何停止无限循环?
问题:根据用户输入计算两个整数,第一个数不断翻倍,而第二个数则不断减半。在每一步,如果第二个数是奇数,就把第一个数加到自己身上,直到第二个数变为零。
我的代码似乎没有完全运行,而且出现了无限循环,我到底哪里出错了?我使用的是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
这里还有一个问题,就是你在打印语句中尝试对数字进行加法和除法运算,但这样做并不会改变整数numA和numB的值(也就是说,numA和numB在整个程序运行过程中都是固定不变的)。
如果想要改变numA和numB的值,你需要这样做:
- 变量名 = (对变量进行某种操作的函数)
比如说,numA = numA + 1
这样可以给numA加1。
2
问题:
你不需要写
done = False; while not done:
。只需无限循环 (while True
),然后在完成时用break
退出循环就可以了。input
是执行用户输入的代码(可以想象成 Python 交互式环境的工作方式)。你需要用raw_input
,它会返回一个字符串,所以你需要把它传给int
:numA = int(raw_input("..."))
abs(numB)
会计算numB
的绝对值,但不会对它做任何事情。你需要把这个函数的结果存储到numB
中,方法是numB = abs(numB)
。表达式
x and True or False
在最近的 Python 版本中不再使用;可以用True if x else False
来替代。不过,返回True
如果x == True
否则返回False
,其实和直接返回x
是一样的,所以直接返回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