Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Membership Operators and Types Comparison | Conditional Statements
Introduction to Python
course content

Course Content

Introduction to Python

Introduction to Python

1. First Acquaintance
2. Variables and Types
3. Conditional Statements
4. Other Data Types
5. Loops
6. Functions

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'.

1234
# Initial string site = "codefinity" # Using membership operator print("n" in site)
copy

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 return True only if the var 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 return True only if the value in the var variable is an integer.

To illustrate, let's determine if 3.5 is an integer.

12345
# 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
copy

As demonstrated, both methods returned False because 3.5 is a float and not an integer (int).

Everything was clear?

Section 3. Chapter 5
We're sorry to hear that something went wrong. What happened?
some-alt