I am new to coding with Python, (only a few days), and I have encountered many issues already, However, one seems to be persistent. Every time I create a condition I end up with a long list of if-else statements. I searched the website but could not figure out how to find a solution to my specific issue.
I am building a simple unit converter. The code is below:
def get_unit1():
while True:
unit1 = input("Which unit would you like to convert from?: ")
if unit1 == 'km':
return unit1
elif unit1 == 'hm':
return unit1
elif unit1 == 'da':
return unit1
elif unit1 == 'm':
return unit1
elif unit1 == 'dm':
return unit1
elif unit1 == 'cm':
return unit1
elif unit1 == 'mm':
return unit1
elif unit1 == 'ml':
return unit1
elif unit1 == 'yd':
return unit1
elif unit1 == 'ft':
return unit1
elif unit1 == 'in':
return unit1
else:
print("Wrong input, try again.")
def get_unit2():
while True:
unit2 = input("Which unit would you like to convert to?: ")
if unit2 == 'km':
return unit2
elif unit2 == 'hm':
return unit2
elif unit2 == 'da':
return unit2
elif unit2 == 'm':
return unit2
elif unit2 == 'dm':
return unit2
elif unit2 == 'cm':
return unit2
elif unit2 == 'mm':
return unit2
elif unit2 == 'ml':
return unit2
elif unit2 == 'yd':
return unit2
elif unit2 == 'ft':
return unit2
elif unit2 == 'in':
return unit2
else:
print("Wrong input, try again.")
The condition is working perfectly fine, it's just that it is long. When I shrink the condition using OR operator for example:
if unit1 == 'km'or'hm'or'da'or'm'or'dm'or'cm'or'mm'or'ml'or'yd'or'ft'or'in':
return unit1
It does work too but when I put the wrong input it accepts it and later the program crashes.
I tried using a list but ended up creating a long code of "if x in list" statements.
Thanks in advance!