user2517985
user2517985

Reputation: 143

How can I simplify my if condition in python?

I would like to know if there's a simpler way to write the condition of the if statement. Something like item1, item2 == "wood":. I currently have this code:

item1 = input("item1: ")
item2 = input("item2: ")

if item1 == "wood" and item2 == "wood":
    print("You created a stick")

Upvotes: 1

Views: 555

Answers (3)

qfwfq
qfwfq

Reputation: 2516

This isn't a huge savings but you could take out "wood" and

item1 = input("item1: ")
item2 = input("item2: ")

if item1 == item2 == "wood":
    print("You created a stick")

Upvotes: 7

You have two ways. you can use "==" for two variables.

item1 = input("item1: ")
item2 = input("item2: ")

if item1 == item2 == "wood":
    print("You created a stick")

And also you can do using a for loop. But for that you have to use a list first.So this would help if you are using huge number of inputs.

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")

Upvotes: 0

Mateen Ulhaq
Mateen Ulhaq

Reputation: 27191

In this particular case, it's fine to leave it as is. But if you have three or more elements, try using a list:

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")

Upvotes: 1

Related Questions