简体   繁体   中英

Trying to understand how to use the any() function

I want to pick many given numbers and compare them to a number I chose, how do i do this using the any or all command , I tried this and it didn't work, any input would be appreciated:

import random

v = int(input("What number are you looking for ?"))
a1 = int(input("What is the first number"))
a2 = int(input("What is the second number"))
a3 = int(input("What is the third number"))
a = random.choice([a1,a2,a3])
b = random.choice([a1,a2,a3])
c = random.choice([a1,a2,a3])
if any ([a, b, c]) == v:
   print('We got a hit')

Entering the following, I can't get the if to evaluate to True :

What number are you looking for ?5
What is the first number1
What is the second number2
What is the third number5
>>> 

How am I using any wrong here ? Since the last number is 5 I should of gotten a hit but I get nothing.

Because you're using any wrong. To achieve what you want, supply the condition to any :

if any(v == i for i in [a, b, c]):
   print('We got a hit')

This will check that there's a value in the list [a, b, c] which equals v .

Your approach:

any([a, b, c]) == v

Will first use any to check if any of the elements inside the iterable ( [a, b, c] ) supplied has a truthy value (and it does, all of them do if they're positive integers) and returns the appropriate result True indicating that. So:

any([a, b, c])

will return True . Your condition then becomes:

True == v

which obviously evaluates to False .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM