編寫一個 Python 程序來檢查給定的項是否存在於元組中。我們使用 in 運算符來查找元組中存在的項。
# Check Element Presnet in Tuple
numTuple = (4, 6, 8, 11, 22, 43, 58, 99, 16)
print("Tuple Items = ", numTuple)
number = int(input("Enter Tuple Item to Find = "))
result = number in numTuple
print("Does our numTuple Contains the ", number, "? ", result)
雖然上面的例子返回真或假,我們需要一個有意義的消息。因此,如果元組中存在條目,我們使用 if 語句和 in 運算符(numTuple 中的 If 數字)來打印不同的消息。
# Check Element Presnet in Tuple
numTuple = (4, 6, 8, 11, 22, 43, 58, 99, 16)
print("Tuple Items = ", numTuple)
number = int(input("Enter Tuple Item to Find = "))
if number in numTuple:
print(number, " is in the numTuple")
else:
print("Sorry! We haven't found ", number, " in numTuple")
Tuple Items = (4, 6, 8, 11, 22, 43, 58, 99, 16)
Enter Tuple Item to Find = 22
22 is in the numTuple
>>>
Tuple Items = (4, 6, 8, 11, 22, 43, 58, 99, 16)
Enter Tuple Item to Find = 124
Sorry! We haven't found 124 in numTuple
>>>
使用 For 循環檢查元組中是否存在項目的 Python 程序
在這個 Python 示例中,我們使用 if 語句(if val == number)對照給定的數字檢查每個元組項。如果為真,則結果為真,編譯器將從 for 循環中斷開。
# Check Element Presnet in Tuple
numTuple = (4, 6, 8, 11, 22, 43, 58, 99, 16)
print("Tuple Items = ", numTuple)
number = int(input("Enter Tuple Item to Find = "))
result = False
for val in numTuple:
if val == number:
result = True
break
print("Does our numTuple Contains the ", number, "? ", result)
Tuple Items = (4, 6, 8, 11, 22, 43, 58, 99, 16)
Enter Tuple Item to Find = 16
Does our numTuple Contains the 16 ? True
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/248581.html