我是编码新手,我编写了一个程序,使用 for 循环和一个范围来检查该范围内的数字是奇数还是偶数。但是我想排除数字 0
for num in range (0, 11):
if num %2 == 0:
print (num,' is an even number!')
else:
print (num,' is an odd number!')
我期望所有数字的输出,但不是 0。有人可以帮助我吗?
潇潇雨雨
浏览 532回答 3
3回答
吃鸡游戏
正如答案已经提到的,range(1, 11)将按1 2 3 4 5 6 7 8 9 10要求生产。但是,您可以通过执行以下操作排除特定数字:all_numbers = range(0, 11)exclude_set = {0} # a set containing the value 0numbers = (num for num in all_numbers if num not in exclude_set)如果您有一组您知道是错误的数字,这可能会很有用,但否则会有一个连续的范围。"""Represent retail stores in a chain"""store_numbers = range(1, 51)# stores 14, 17, and 32 have been closed, soclosed_stores = {14, 17, 32}valid_stores = (store for store in store_numbers if store not in closed_stores)
范围包括第一个参数,但不包括第二个参数。范围内的第一个数字应该是您要开始的数字。将您的代码更改为for num in range(1, 11): if num % 2 == 0: print(num, ' is an even number!') else: print(num, ' is an odd number!')