Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.7k 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 Vigges Developer Community for programmer and developer-Open, Learning and Share
...