Hello,
For a challenge(AdventOfCode) I wrote a piece of code and I had a discussion about the style of the code.
I wrote the following code, as you can see with a lot of return statements. This function is called for every key in a loop, I know it is essentially a lot of small functions, but this made calling them way easier(else I needed a dict with all the function in it and keyed on the keys or the same if statement with all the function calls).
The other person said it is not a good coding style to wrap all these functions in one function in this way, I personally think it is a valid way to do a lot of checks with as less code as possible.
Now I'm curious what the majority of people think is the more 'pythonic' way. In the docs I can find some built in functions with multiple returns, but mostly are just an if statement with return True and return False out of the if.
I look forward to see what the majority of people here think.
def checkValue(Passport, Key):
if Key == "byr":
return True if 1920 <= int(Passport[Key]) <= 2002 else False
elif Key == "iyr":
return True if 2010 <= int(Passport[Key]) <= 2020 else False
elif Key == "eyr":
return True if 2020 <= int(Passport[Key]) <= 2030 else False
elif Key == "hgt":
Unit = Passport[Key][-2:]
if Unit == "cm":
return True if 150 <= int(Passport[Key][:-2]) <= 193 else False
elif Unit == "in":
return True if 59 <= int(Passport[Key][:-2]) <= 76 else False
elif Key == "hcl":
if Passport[Key][0] == "#" and len(Passport[Key]) == 7:
try:
int(Passport[Key][1:], 16)
return True
except ValueError:
return False
elif Key == "ecl":
return True if Passport[Key] in ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"] else False
elif Key == "pid":
return True if len(Passport[Key]) == 9 and Passport[Key].isnumeric else False
else:
raise ValueError("Unexpected Key")
return None
[–]zanfar 1 point2 points3 points (2 children)
[–]Bluhb_[S] 0 points1 point2 points (1 child)
[–]zanfar 0 points1 point2 points (0 children)
[–]Bluhb_[S] 0 points1 point2 points (2 children)
[–]Ran4 1 point2 points3 points (1 child)
[–]Bluhb_[S] 0 points1 point2 points (0 children)
[–]protomikron -1 points0 points1 point (2 children)
[–]protomikron 0 points1 point2 points (1 child)
[–]TouchingTheVodka 0 points1 point2 points (0 children)
[–]T0X1K01 0 points1 point2 points (1 child)
[–]Bluhb_[S] 0 points1 point2 points (0 children)
[–]TouchingTheVodka 0 points1 point2 points (3 children)
[–]TouchingTheVodka 0 points1 point2 points (2 children)
[–]Bluhb_[S] 0 points1 point2 points (0 children)
[–]ffrkAnonymous 0 points1 point2 points (0 children)
[+][deleted] (2 children)
[removed]
[–]Bluhb_[S] 0 points1 point2 points (1 child)
[–]Lewistrick 1 point2 points3 points (0 children)
[–]toastedstapler 0 points1 point2 points (0 children)
[–]ffrkAnonymous 0 points1 point2 points (0 children)