27
loading...
This website collects cookies to deliver better user experience
Animal Registry | ||
---|---|---|
ID | Scientific Name | Common Name |
3Y99 | Canis Lupus Familiaris | Siberian Husky |
MT5R | Cebinae | Capuchin Monkey |
8D6U | Octopoda | Octopus |
YG0E | Anthophila | Bee |
JN14 | Dinastinae | Rhinoceros Beetle |
WVTA | Python Regius | Ball Python |
HAZP | Gorilla | Gorilla |
Debes instalar PrettyTable mediante Pip.
Intenta, en la consola, con:
pip install prettytable
from prettytable import PrettyTable
import random
import string
import sys
animal_dic = {}
if __name__ == "__main__":
main()
La explicación de como if _name_ == "_main_" funciona está fuera del alcance de este articulo.
# ~~~~~~~~~~~~~~~~~~ Functions(): ~~~~~~~~~~~~~~~~~~~
def main():
# ~~~~~~~~~~~~~~ User's choise ~~~~~~~~~~~~~~~
while True:
instrucctions()
user_input = input("\nWhat do you want to do? "
"(a, d, u, l, e): ").lower()
if user_input == "a":
add_animal()
elif user_input == "d":
delete_animal()
elif user_input == "u":
update_animal()
elif user_input == "l":
print_register()
elif user_input == "e":
exit_program()
elif not user_input:
print("please, enter something!")
# ~~~~~~~~~~~~~ Functions ~~~~~~~~~~~~~~
def instrucctions():
print('\nAnimal registry program:'
'\n1: Enter A or a to add new animal.'
'\n2: Enter D or d to delete a animal'
'\n3: Enter U or u to update animal.'
'\n4: Enter L or l to check list of animals. '
'\n5: Enter E or e to exit the program.')
def print_registry():
x = PrettyTable(["ID", "Scientific Name", "Common Name"])
for animal_data in animal_dic:
x.add_row([animal_data, animal_dic[animal_data]["scientific_name"],
animal_dic[animal_data]["common_name"]])
print(x.get_string(title="Animal registry"))
{'name': 'Adam'}
{'name': 'Adam', 'last': 'Smith'}
{0: {'book': 'Wealth of Nations', 'author': 'Adam Smith'},
1: {'book': 'Economic Sophisms',' author': 'Frédéric Bastiat'}}
for animal_data in animal_dic:
x.add_row([animal_data, animal_dic[animal_data]["scientific_name"],
animal_dic[animal_data]["common_name"]])
x.add_row([animal_data, animal_dic[animal_data]["scientific_name"],
animal_dic[animal_data]["common_name"]])
print(x.get_string(title="Animal registry"))
def random_id():
random_string = ''.join(random.choices(string.ascii_uppercase
+ string.digits, k=4))
return random_string
La explicación de como funciona esta función está fuera del alcance de este articulo.
def add_animal():
animal_id = random_id()
scientific_name = input("\nPlease enter the scientific name: ").title()
common_name = input("\nPlease enter the common name: ").title()
data = {animal_id: {'scientific_name': scientific_name,
'common_name': common_name}}
if not scientific_name and not common_name:
print("You must write something!")
else:
animal_dic.update(data)
data = {animal_id: {'scientific_name': scientific_name,
'common_name': common_name}}
Actualizamos nuestro diccionario anidado y lo almacenamos en una variable llamada "data". De modo que:
animal_id = Es el random ID que retorna nuestra función. Es la key/clave externa de este
diccionario anidado.
'scientific_name': que está entre comillas, es la key/llave interna.
scientific_name: que una variable, es la value/valor interno. Ingresado por el usuario.
El siguiente bloque de código establece una condición donde si el usuario no ingresa
ni un nombre científico ni un nombre común, imprima un mensaje de que debe hacerlo.
Por ultimo, en el 'else': si se han ingresados al menos uno de los dos input()
actualizaremos el "animal_dic" con los datos escritos por el usuario.
def delete_animal():
animal_id = input("\nEnter the animal ID you want delete: ").upper()
if animal_id in animal_dic:
choice = input("Delete (y/n)").lower()
if choice == "yes" or choice == "y":
del animal_dic[animal_id]
print(f"{animal_id} registry has been deleted!")
else:
print("ID not found. Check list pressing 'L'")
def update_animal():
animal_id = input("\nEnter the animal ID you want update: ").upper()
# If external key in dictionary, if key is equal to ID (animal_id)
for animal in animal_dic:
if animal == animal_id:
choice = input(f"Update registry {animal_id}? (y/n): ").lower()
if choice == "yes" or choice == "y":
# Changing names
scientific_name = input("Write a new scientific name: ").title()
common_name = input("Write a new common name: ").title()
if not scientific_name and not common_name:
print("You must write something!")
else:
# Updating
animal_dic[animal]['scientific_name'] = scientific_name
animal_dic[animal]['common_name'] = common_name
print("registry updated!")
print_registry()
else:
print("ID not found. Check list pressing 'L'")
def exit_program():
sys.exit("Goodbye!")