Skip to content

Instantly share code, notes, and snippets.

@arx8x
Last active November 20, 2022 09:20
Show Gist options
  • Save arx8x/5eb8ce1f956144e99892809769eb094a to your computer and use it in GitHub Desktop.
Save arx8x/5eb8ce1f956144e99892809769eb094a to your computer and use it in GitHub Desktop.
notes to myself (in case I move away from python and come back after a long while) and for beginners
# Might not seem like a big deal in the example but in
# big projects where there's a lot of control flows branching out
# into unmanageable mess, this will be useful.
# Biggest takeaway is, try to terminate/break/eliminate an edge case in a block and
# continue the expected control flow in the same indentation level (previous block)
a = {
'name': 'John Doe',
'age': '33',
'location': None,
'approved': False
}
b = {
'name': 'Jesper Kyd',
'age': None,
'location': 'Kochi',
'approved': False
}
c = {
'name': 'Darcy',
'age': 25,
'location': 'Venice',
'approved': False
}
# construct list using above variables and iterate them
for person in [a, b, c]:
# using walrus operator to assign and eval at the same time
if not (age := person.get('age')):
print(f"skipping {person['name']} (no age)")
# control breaks here
continue
# re-assign and eval at the same time using walrus
if (age := int(age)) > 30:
tail = "rejected"
person['approved'] = False
else:
tail = "approved"
person['approved'] = True
# tail variable is assigned based on approval status
# the rest of the string concat is the same for rejected
# or approved. So that logic only needs to be in once place
print(f"Person {person['name']} ({age}) {tail}")
# since age is casted to int now, it can be used for math
print(f"Year of birth is {2022 - age}\n")
a = {
'name': 'John Doe',
'age': '33',
'location': None,
'approved': False
}
b = {
'name': 'Jesper Kyd',
'age': None,
'location': 'Kochi',
'approved': False
}
c = {
'name': 'Darcy',
'age': 25,
'location': 'Venice',
'approved': False
}
for person in [a, b, c]:
age = person.get('age')
if not age:
print(f"skipping {person['name']} (no age)")
else:
age = int(age)
if age > 30:
person['approved'] = False
print(f"Person {person['name']} ({age}) approved")
else:
person['approved'] = True
print(f"Person {person['name']} ({age}) rejected")
print(f"Year of birth is {2022 - age}\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment