Home » Python

in keyword with example in Python

Python in keyword: Here, we are going to learn about the in keyword with example.
Submitted by IncludeHelp, on April 15, 2019

Python in keyword

in is a keyword (case-sensitive) in python, it is used to check whether an element exists in the given sequence like string, list, tuple, etc.

in keyword is also used with the for loop to iterate the sequence.

Syntax of in keyword

    if element in sequence:
	    statement(s)

    for element in sequence:
	    statement(s)

Example:

    Input:
    cities = ["New Delhi", "Mumbai", "Chennai", "Banglore"]

    # condition
    if "Mumbai" in cities:
        print("Yes")
    else:
        print("No")

    Output:
    Yes

Python examples of in keyword

Example 1: Check whether an element exits in a list of not.

# python code to demonstrate example of 
# in keyword

# Check whether an element exits in a list of not

# create a list
cities = ["New Delhi", "Mumbai", "Chennai", "Banglore"]

# check if "Mumbai" is present in the list or not
if "Mumbai" in cities:
    print("Yes \"Mumbai\" exists in the list")
else:
    print("No \"Mumbai\" does not exist in the list")

# now check...
# "Gwalior" is present in the list or not
if "Gwalior" in cities:
    print("Yes \"Gwalior\" exists in the list")
else:
    print("No \"Gwalior\" does not exist in the list")

Output

Yes "Mumbai" exists in the list
No "Gwalior" does not exist in the list

Example 2: Take a string and print the characters one by one until a dot (".") is not found.

# python code to demonstrate example of 
# in keyword

# Take a string and print the characters one by one 
# until a dot ('.') is not found.

# string input
string = input("Enter a string: ")

# print characters until dot is not found
for ch in string:
    if ch=='.':
        break
    print(ch)

Output

Enter a string: IncludeHelp.com
I
n
c
l
u
d
e
H
e
l
p





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.