试图解决黑客等级问题。为什么range在这个if语句中第二次不能工作(它可以工作第一个范围代码)。
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input().strip())
if n % 2 == 1:
print("Weird")
elif n % 2 == 0 and list(range(2, 6)): #This works
print("Not Weird")
elif n % 2 == 0 and list(range(6, 21)): #This doesn't work
print("Weird")
elif n % 2 == 0 and n > 20:
print("Not Weird")
有什么办法让它起作用吗?或者为了同样的目的而使用另一个内置功能的建议?
发布于 2021-11-30 10:23:44
and range(2,6)
总是计算为True
,因为您使用的是elif
,如果它与第一个条件匹配,它就不会继续。您可能打算使用n in list(range())
,但是如果您想检查数字是否在其他人之间,则使用<
或>
elif n % 2 == 0 and 1 < n < 6
https://stackoverflow.com/questions/70174248
复制