Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

python - Only Output True or False in Code (loops)

I wanted to do a code that takes in an integer input, then finds if it is divisible by a two-digit prime number. If it is, it returns True, otherwise False. I already have made a function that identifies whether a number is prime or not called isPrime (which I used here):

num=int(input())
for i in range (10,num):
    if isPrime(i,2):
        if num%i==0:
            print(True)
        else:
            print(False)

I know that this prints all of the True's and False's from 10 to the inputted integer, so what I wanted to ask is how do I edit this so that if one of those outputs is True, it will only output True, but if none of those are True, it will output False?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use any:

num=int(input())
print(any(num%i==0 for i in range (10,num) if isPrime(i,2)))

any returns True when it finds the first "Truthy" value in an iterable otherwise False


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...