Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.2k 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 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...