in关键字和Python示例

in 关键字

in是python的一个关键字(区分大小写),用于检查元素是否以给定的顺序存在,例如字符串,列表,元组等。

in关键字也与for循环一起使用以迭代序列。

in关键字的语法

    if element in sequence:	    statement(s)

    for element in sequence:	    statement(s)

示例

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

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

    Output:
    Yes

in关键字的Python示例

示例1:检查元素是否在列表中不存在。

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

if "Mumbai" in cities:
    print("Yes \"Mumbai\" exists in the list")
else:
    print("No \"Mumbai\" does not exist in the list")

if "Gwalior" in cities:
    print("Yes \"Gwalior\" exists in the list")
else:
    print("No \"Gwalior\" does not exist in the list")

输出结果

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

示例2:取一个字符串并逐个打印字符,直到找不到点(“。”)。

#python代码演示示例
#in关键字
#取一个字符串,一个接一个地打印字符
#直到找不到点('.')。
#字符串输入
string = input("Enter a string: ")

#打印字符直到找不到点为止
for ch in string:
    if ch=='.':
        break    print(ch)

输出结果

Enter a string: nhooo.com
n
h
o
o
o