Python NamedTuple example: Employee information
Python NamedTuple Data Type: Exercise-1 with Solution
Write a Python program that defines a NamedTuple called Employee with fields like name, age, and country. Print each employee's name and country.
Sample Solution:
Code:
from collections import namedtuple
# Define the NamedTuple Employee
Employee = namedtuple("Employee", ["name", "age", "country"])
def main():
try:
# Create a list of Employee instances
employees = [
Employee("Klaes Susana", 35, "USA"),
Employee("Auxentius Cloe", 44, "Canada"),
Employee("Golzar Merob", 28, "UK"),
Employee("Tatjana Adhelm", 30, "Australia"),
]
# Print each employee's name and country
for employee in employees:
print("Employee Name:", employee.name)
print("Employee Country:", employee.country)
print() # Print an empty line for separation
except Exception as e:
print("An error occurred:", e)
if __name__ == "__main__":
main()
Output:
Employee Name: Klaes Susana Employee Country: USA Employee Name: Auxentius Cloe Employee Country: Canada Employee Name: Golzar Merob Employee Country: UK Employee Name: Tatjana Adhelm Employee Country: Australia
Flowchart:
Previous: Python Extended Data Type NamedTuple Exercises Home.
Next: Python NamedTuple example: Point coordinates.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/python-exercises/extended-data-types/python-extended-data-types-index-namedtuple-exercise-1.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics