我在python中编写了这个程序:
num=51
if (num % 3 == 1):
if (num%4 == 2):
if (num%5 == 3):
if (num%6 ==4):
print num
else:
print "not right number, try again - error 1"
else:
print "not right number, try again - error 2"
else:
print "not right number, try again - error 3"
else:
print "not right number, try again - error 4"
哪种方法效果很好,除非我真的不想手动迭代num
,直到我得到我想要的答案(我写这个来解决我想要解决的数学问题 - 这不是虽然做作业。如果有人可以详细说明要更改所有else
语句以添加一个语句,将num
递增1并返回到for循环的开头,那就太棒了。
谢谢!
答案 0 :(得分:2)
您可以使用break
语句终止循环
num=1
while True:
if (num % 3 == 1):
if (num%4 == 2):
if (num%5 == 3):
if (num%6 ==4):
print num
break
else:
print "not right number, try again - error 1"
else:
print "not right number, try again - error 2"
else:
print "not right number, try again - error 3"
else:
print "not right number, try again - error 4"
num += 1
答案 1 :(得分:1)
这个怎么样?
def f(n):
for (a, b) in [(3, 1), (4, 2), (5, 3), (6, 4)]:
if(num % a) != b:
return (False, b)
return (True, n)
for num in range(100):
print '-' * 80
v = f(num)
if not v[0]:
print "{0} is not the right number, try again - error {1}".format(num, v[1])
else:
print "The first number found is --> {0}".format(v[1])
break
N = 1000000
numbers = [num for num in range(N) if f(num)[0]]
print "There are {0} numbers satisfying the condition below {1}".format(
len(numbers), N)
答案 2 :(得分:1)
我认为代码的结构是错误的,你可以试试这个:
num=51
def test(num):
# keep all the tests in a list
# same as tests = [num % 3 == 1, num % 4 == 2, ...]
tests = [num % x == y for x,y in zip(range(3,7), range(1,5))]
if all(tests): # if all the tests are True
return False # this while exit the loop
else:
# message to be formatted
msg = "{n} is not the right number, try again - error {err}"
# I tried to keep your error numbers
err = len(tests) - tests.count(False) + 1
# format the message with the number and the error
print msg.format(n=num, err=err)
return True
while test(num):
num += 1 # increment the number
print num, "is the right number"
while循环测试每次迭代时的数字,当数字正确时它将退出
答案 3 :(得分:0)
你可以把支票放在一个函数中来清理它:
def good_number(num):
if num % 3 == 1:
if num % 4 == 2:
if num % 5 == 3:
if num % 6 == 4:
return True
# Put your elses/prints here
# Replace 100 with your max
for num in range(100):
if good_number(num):
print('{} is a good number'.format(num))
# Or use a while loop:
num = 0
while not good_num(num):
num += 1
print('{} is a good number'.format(num))