Python编程:15显示为偶数,并且在以下程序中不考虑范围中的最后一个数字。我是编程新手,如果有错误就道歉: - )
我的计划:
for num in range (10,20):
for i in range (2,num):
if num%i == 0:
print('%d is an even number' %(num))
break
else:
print (num, 'is an odd number')
结果:15显示为偶数,不考虑20在范围内提供。
10 is an even number
11 is an odd number
12 is an even number
13 is an odd number
14 is an even number
15 is an even number
16 is an even number
17 is an odd number
18 is an even number
19 is an odd number
答案 0 :(得分:0)
范围的工作方式类似于(start,end-1)。所以如果你想要20
,你必须写range(10,21)
我想你要检查给定数字是偶数还是奇数。
下面是代码
for num in range (10,21):
if num%2 == 0:
print (num,'is an even number')
else:
print (num, 'is an odd number')
答案 1 :(得分:0)
15%3==0
- 这是你的问题。它不应该是num%i
,应该是num%2
答案 2 :(得分:0)
这是在python控制台中运行程序时发生的情况:
In [1]: for num in range (10,20):
...: for i in range (2,num):
...: if num%i == 0:
...: print('%d is an even number' %(num))
...: break
...: else:
...: print (num, 'is an odd number')
...:
10 is an even number
(11, 'is an odd number')
(11, 'is an odd number')
(11, 'is an odd number')
(11, 'is an odd number')
(11, 'is an odd number')
(11, 'is an odd number')
(11, 'is an odd number')
(11, 'is an odd number')
(11, 'is an odd number')
12 is an even number
(13, 'is an odd number')
(13, 'is an odd number')
(13, 'is an odd number')
(13, 'is an odd number')
(13, 'is an odd number')
(13, 'is an odd number')
(13, 'is an odd number')
(13, 'is an odd number')
(13, 'is an odd number')
(13, 'is an odd number')
(13, 'is an odd number')
14 is an even number
(15, 'is an odd number')
15 is an even number
16 is an even number
(17, 'is an odd number')
(17, 'is an odd number')
(17, 'is an odd number')
(17, 'is an odd number')
(17, 'is an odd number')
(17, 'is an odd number')
(17, 'is an odd number')
(17, 'is an odd number')
(17, 'is an odd number')
(17, 'is an odd number')
(17, 'is an odd number')
(17, 'is an odd number')
(17, 'is an odd number')
(17, 'is an odd number')
(17, 'is an odd number')
18 is an even number
(19, 'is an odd number')
(19, 'is an odd number')
(19, 'is an odd number')
(19, 'is an odd number')
(19, 'is an odd number')
(19, 'is an odd number')
(19, 'is an odd number')
(19, 'is an odd number')
(19, 'is an odd number')
(19, 'is an odd number')
(19, 'is an odd number')
(19, 'is an odd number')
(19, 'is an odd number')
(19, 'is an odd number')
(19, 'is an odd number')
(19, 'is an odd number')
(19, 'is an odd number')
为什么呢?因为你在一个循环中有一个循环而你正在做:
In [2]: range(2, num) # given num == 10:
Out[2]: [2, 3, 4, 5, 6, 7, 8, 9]
暗示您将遇到15%3的情况:
In [3]: 15%3
Out[3]: 0