我有这个程序,要求用户输入两个数字,并检查数字之间的每个数字是否可以用5和7进行除法。 如果范围内没有数字可以除以5和7,我希望程序输出“找不到数字”之类的内容。 例如,如果用户输入3和4,它将显示“找不到号码”
我尝试了几种不同的方法,但是都没有用。
start = int(input("Start: "))
stop = int(input("Stop: "))
for number in range(start, (stop+1),1):
if number % 5 == 0 and number % 7 ==0:
print("Number", number, "can be divided with 5 and 7")
print("Stop search")
break
elif number % 5 == 0 and number % 7 !=0:
print(number, "can't be divided with 7, next.")
elif number % 5 != 0:
print(number,"can't be divided with 5, next.")
答案 0 :(得分:7)
您可以将else:
子句与for循环一起使用。仅当整个for循环正常结束且未到达break
子句时才执行该命令。在极少数情况下,它很有用!
for number in range(start, (stop+1),1):
if number % 5 == 0 and number % 7 ==0:
print("Number", number, "can be divided with 5 and 7")
print("Stop search")
break
elif number % 5 == 0 and number % 7 !=0:
print(number, "can't be divided with 7, next.")
elif number % 5 != 0:
print(number,"can't be divided with 5, next.")
else:
print("No number that can be divided by both 5 and 7 found.")
答案 1 :(得分:0)
正如丹尼尔·罗斯曼(Daniel Roseman)所说,我也没有意识到else子句,所以我做了一个使用测试变量的破解方法
start = int(input("Start: "))
stop = int(input("Stop: "))
Test = 0
for number in range(start, (stop+1),1):
if number % 5 == 0 and number % 7 ==0:
print("Number", number, "can be divided with 5 and 7")
print("Stop search")
Test = 1
break
elif number % 5 == 0 and number % 7 !=0:
print(number, "can't be divided with 7, next.")
elif number % 5 != 0:
print(number,"can't be divided with 5, next.")
if Test == 0:
print("no number in range")
答案 2 :(得分:0)
为for循环添加一个布尔条件。
found = False
然后在发生for循环的停止条件时将此布尔值更改为true。
最后,根据发现的布尔条件执行操作,例如:
if !found:
# Print when the value was not found.
[edit] :RemcoGerlich发布的解决方案是更好的解决方案。
答案 3 :(得分:0)
您还可以将变量用作标志,以告诉您是否找到该号码:
found = False
for number in range(start, (stop+1),1):
if number % 5 == 0 and number % 7 ==0:
print("Number", number, "can be divided with 5 and 7")
print("Stop search")
found = True
break
elif number % 5 == 0 and number % 7 !=0:
print(number, "can't be divided with 7, next.")
elif number % 5 != 0:
print(number,"can't be divided with 5, next.")
if not found:
print("No number that can be divided by both 5 and 7 found.")