Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

It happens to me many times that I want to establish several conditions regarding the same variable but I don't know how to do it so that I don't have to put "and" many times

Example:

a = input("Number: ")

if a != "this" and a != "that" and != "there":

    print("Hi")

#I don't want to use so many and in this code

1 Answer

0 votes
by (36.8k points)

You could use a set object and check for if the value is not present in the set.

if a not in {1, 2, 3, 4}:

    print("Hi!")

Sets are good to use since they are unordered, and therefore are relatively quick to check for if something is or isn't in one.

If the numbers are all an equal distance away, you can use a range instead of specifying each of the numbers. However, this will be slower, especially with a larger range.

if a not in range(1, 4):

    print("Hi")

If you want to know more about the Data Science then do check out the following Data Science which will help you in understanding Data Science from scratch 

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...