Course Content
Introduction to Python
Introduction to Python
Membership Operators and Types Comparison
So far, we've discussed the primary comparison operators commonly used for numbers and strings. Python also offers membership operators that allow you to determine if a certain sequence exists within an object.
In Python, sequence objects include strings, lists, tuples, and more. We'll delve into these in the next section.
The membership operators are in
and not in
. If the sequence exists within an object, the in
operator will return True
. For instance, let's see if the letter 'n'
is in the word 'codefinity'
.
# Initial string site = "codefinity" # Using membership operator print("n" in site)
A True
result indicates that the letter was found in the given word. Conversely, the not in
operator checks if a certain sequence does not exist within an object.
At times, we might need to verify whether an object is of a particular type. For instance, if we're writing a program to divide an input value by 2
, we need to ensure the value is numerical; otherwise, the operation won't work. There are two methods to determine if a value is of a specific type:
- One approach is to compare a variable's type to the desired type using the
is
operator. For instance,type(var) is int
will returnTrue
only if thevar
variable's value is an integer; - Alternatively, you can use the
isinstance()
function. This function requires two arguments: the first is the value whose type you wish to verify, and the second is the type to compare against. For example,isinstance(var, int)
will also returnTrue
only if the value in thevar
variable is an integer.
To illustrate, let's determine if 3.5
is an integer.
# Initial number num = 3.5 # Checking if num is an integer print(type(num) is int) # the first approach print(isinstance(num, int)) # the second approach
As demonstrated, both methods returned False
because 3.5
is a float
and not an integer (int
).
Everything was clear?