[英]Iterating variable when if statement comes up false
我用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循環的開頭,那將是很好的。
謝謝!
您可以使用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
這個如何?
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)
我認為代碼的結構是錯誤的,您可以嘗試以下方法:
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循環在每次迭代中測試數字,當數字正確時,它將退出
您可以通過將檢查放入函數中來清理它:
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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.