Reputation: 645
I was wondering if there was a way to do something like this is Python. Any ideas?
inches = ["inches", "inch", "in"]
centimeters = ["centimeters", "centimeter", "cm"]
allUnits = [inches, centimeters]
unit = input("Enter unit here... ")
if unit not in allUnits:
print("Invalid unit!")
Upvotes: 0
Views: 80
Reputation: 11
If you really need to use array of arrays you can do like that. Inspired by C++.
def isInArray(array, unit):
for i in range(len(array)):
for j in array[i]:
if j == unit:
return True;
return False
unit = input("Enter unit here... ")
if not isInArray(allUnits, unit):
print("Invalid unit!")
Upvotes: 0
Reputation: 21285
You're close:
inches = ["inches", "inch", "in"]
centimeters = ["centimeters", "centimeter", "cm"]
allUnits = [*inches, *centimeters] # notice the `*`
unit = input("Enter unit here... ")
if unit.lower() not in allUnits:
print("Invalid unit!")
Should do the trick.
The *
operator unwinds the lists into their constituent elements. Which can then be used to create a new list. So you can flatten the two lists into one that way.
I also added unit.lower()
to make the string comparison case-independent.
Upvotes: 2
Reputation: 544
Just add lists:
inches = ["inches", "inch", "in"]
centimeters = ["centimeters", "centimeter", "cm"]
allUnits = inches + centimeters
unit = input("Enter unit here... ")
if unit not in allUnits:
print("Invalid unit!")
Upvotes: 1