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

Kursinnehåll

Introduction to Python(ihor)

Introduction to Python(ihor)

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's membership operators check whether a sequence exists within an object, such as strings, lists, or tuples. The in operator returns True if the sequence is found, while the not in operator returns True if it is not.

12345678
# Define a string containing all the vowels vowels = "aeiou" # Check if the character 'n' is present in the `vowels` string print('n' in vowels) # Check if the character 'a' is not present in the `vowels` string print('a' not in vowels)
copy

In addition to checking membership, it's often necessary to verify the type of a variable before performing certain operations. For example, dividing a non-numeric value would cause an error. Python provides two ways to check the type: is and isinstance()

12345678
# Initial number num = 3.5 # Checking if num is an integer using `is` operator print(type(num) is int) # Check if the variable is an integer using the 'isinstance' function print(isinstance(num, int)) # The second approach
copy

Both methods return False because 3.5 is a float, not an int. The is operator checks for exact type matching, while isinstance() also supports checking against multiple types or inheritance.

question mark

What does the in operator do in Python?

Select the correct answer

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 3. Kapitel 5
Vi beklagar att något gick fel. Vad hände?
some-alt