I have quickly written some code for a task in which takes a name of an 'earthling', their age and then applies a random operator with a random value in between 0 and 100. If their new age is below 0 or above 120, they die. The operator, name, previous and new age must be printed to the screen.
Code:
import operator
import random
ops_table = { "+": operator.add, "-": operator.sub, "*": operator.mul }
def get_earthlings():
earthlings = [[], []]
print("Disclaimer: Input XXX as a name to end the naming loop.")
while True:
name = input("Please enter a name: ")
if name == "XXX":
break
while True:
try:
age = int(input("What is the age of " + name + "? "))
if age <= 120 and age >= 0:
break
else:
print("Please enter an age between 0 and 120.")
except ValueError:
print("Please input a valid integer. Try again.")
earthlings[0].append(name)
earthlings[1].append(age)
return earthlings
def random_op():
return ops_table[random.choice(list(ops_table))]
def is_dead(age):
if age > 120:
return True
return False
def get_op_name(operator):
for name, func in ops_table.items():
if func == operator:
return name
def main():
earthlings = get_earthlings()
for index, earthling in enumerate(earthlings[0]):
operator = random_op()
random_value = random.randint(0, 100)
new_age = operator(earthlings[1][index], random_value)
if is_dead(new_age):
print(earthling, "at previous age", earthlings[1][index], "(new age", str(new_age) + ") had operator '" + get_op_name(operator) + "' applied with paramater", random_value, "and died.")
else:
print(earthling, "at previous age", earthlings[1][index], "(new age", str(new_age) + ") had operator '" + get_op_name(operator) + "' applied with paramater", random_value, "and lived.")
if __name__ == "__main__":
main()
Is this code efficient? How can I improve it (other than adding comments)?