Skip to content

Python if in statement

  • by

Python if statement uses the in operator, it can see if a particular value is present. Python “if in statement” makes decisions.

Python if in

Simple example code If statements that check for values: if with in. The if statement has the in operator to see whether example str contains the ‘gene’ phrase.

exampleStr = "Python is a general-purpose programming language."

# Look for substring in source string
if 'gene' in exampleStr:
    print("Found! 'gene'.")
    print("Didn't find the substring.")


Python if in statement

If statement that sees if a list has a certain value

Use the in operator is to see if some list has a particular value

sickDays = [2, 1, 0, 0, 5, 8, 4, 9]

# Check for 9 absence days
if 9 in sickDays:
    print('Ouch, someone was sick 9 days in a row!')
    print("We don't have anyone sick 9 consecutive days.")

The in keyword in Python is used to check if a value exists in a sequence (like a list, tuple, or string). Here’s how you can use it in combination with the if statement:

# Check if an element exists in a list
my_list = [1, 2, 3, 4, 5]
if 3 in my_list:
    print("3 is in the list")

# Check if a character exists in a string
my_string = "hello"
if "e" in my_string:
    print("The letter 'e' is in the string")

# Check if a key exists in a dictionary
my_dict = {"a": 1, "b": 2, "c": 3}
if "b" in my_dict:
    print("'b' is a key in the dictionary")

These are some examples of how you can use the in statement within if conditions to check for membership in a sequence or collection.

Do comment if you have any doubts or suggestions on this Python if code.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading