[英]How can I simplify my if condition in python?
我想知道是否有一種更簡單的方法來編寫if
語句的條件。 類似於item1, item2 == "wood":
我目前有以下代碼:
item1 = input("item1: ")
item2 = input("item2: ")
if item1 == "wood" and item2 == "wood":
print("You created a stick")
這不是一筆巨大的節省,但是您可以取出"wood" and
item1 = input("item1: ")
item2 = input("item2: ")
if item1 == item2 == "wood":
print("You created a stick")
在這種情況下,可以保持原樣。 但是,如果您具有三個或更多元素,請嘗試使用列表:
items = [] # Declare a list
# Add items to list
for x in range(1, 4):
items.append(input("item" + str(x) + ": "))
if all(item == "wood" for item in items):
print("You created a stick")
您有兩種方法。 您可以對兩個變量使用“ ==”。
item1 = input("item1: ")
item2 = input("item2: ")
if item1 == item2 == "wood":
print("You created a stick")
您也可以使用for循環。 但是為此您必須首先使用列表,因此如果您使用大量輸入,這將有所幫助。
list1=[]
item1 = (input("item1: "))
item2 = (input("item1: "))
list1.append(item1)
list1.append(item2)
if all(item=="wood" for item in list1):
print("You created a stick")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.