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

Course Content

Introduction to Python

Introduction to Python

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

book
Membership Operators and Type Comparisons in Python

Python also provides membership operators, which check whether a sequence exists within an object. In Python, sequence objects include strings, lists, tuples, and more. These will be explored in the next section.

The membership operators are in and not in. The in operator returns True if the sequence exists within the object. For example, let's check if the letter 'n' is in the word 'codefinity'.

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

A True result means the letter was found in the word. Conversely, the not in operator checks if a sequence is absent from an object.

Sometimes, it's necessary to verify an object's type. For example, when dividing an input by 2, the value must be numerical; otherwise, the operation will fail. There are two ways to check a value's type:

  • Using is: type(var) is int returns True only if var is an integer.
  • Using isinstance(): isinstance(var, int) does the same but works with multiple types.
123456
# 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 shown, both methods return False because 3.5 is a float, not an int.

Everything was clear?

How can we improve it?

Thanks for your feedback!

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