TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Python Data Class Exercises for Beginners
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python ExamplesPython Tutorials

Python Data Class Exercises for Beginners

Last updated: Nov 05, 2023 12:06 am
By Harsh S.
Share
9 Min Read
Python Dataclass Exercises with solutions for beginners
SHARE

In this tutorial, we bring you a set of Python dataclass exercises. It includes the full source code for the first two problems. The solutions are self-explanatory, yet you’ll see a summary of all the important steps.

Python dataclass exercises

Our exercises offer a hands-on exploration of Python’s dataclasses, showcasing their various features. There are a total of four data class problems that we are putting forth before you. These are not merely partial pieces of code but full-fledged Python programs. For the first two problems, we’ve provided the solution, while for the rest, you’ll have the chance to practice and write the logic yourself. Get ready to enhance your Python skills and dive into the world of data classes!

Moreover, while working on these exercises, you can follow our tutorial on Python data classes and brush up on your concepts. At any point, we are happy to support your learning process. Do contact us via comments or use the contact form from our blog.

Exercise-1:

As an illustration, create a simple program that manages student records, including their name, age, grades, and an automatically calculated average grade.

Solution:

Here’s the code:

from dataclasses import dataclass, field
from typing import List

@dataclass(order=True)
class Student:
    name: str
    age: int
    grades: List[float] = field(default_factory=list)
    average_grade: float = field(init=False)

    def __post_init__(self):
        self.average_grade = sum(self.grades) / len(self.grades) if self.grades else 0.0

    def promote(self):
        self.age += 1

    def add_grade(self, grade):
        self.grades.append(grade)

    def __str__(self):
        return f"Student(name='{self.name}', age={self.age}, grades={self.grades}, average_grade={self.average_grade})"

# Create instances of the Student class
student1 = Student("Emma", 18, [85.5, 92.0, 78.5])
student2 = Student("Noah", 17, [90.0, 88.5])

# Access attributes
print(student1.name)           # Output: Emma
print(student2.age)            # Output: 17
print(student1.grades)         # Output: [85.5, 92.0, 78.5]
print(student2.average_grade)  # Output: 89.25

# Modify attributes
student1.promote()
student1.add_grade(95.0)
print(student1.age)            # Output: 19
print(student1.grades)         # Output: [85.5, 92.0, 78.5, 95.0]
print(student1.average_grade)  # Output: 87.75

# Equality comparison and ordering
student3 = Student("Luca", 18, [85.5, 92.0, 78.5])
print(student1 == student3)    # Output: True
print(student1 < student2)     # Output: False

# Default values and object representation
student4 = Student("Eve", 20)
print(student4)                # Output: Student(name='Eve', age=20, grades=[], average_grade=0.0)

Summary

In this program, we define a dataclass named Student that represents student records. It has attributes for name, age, grades, and average_grade. The grades attribute is initialized as an empty list, and the average_grade attribute is calculated using the __post_init__ method.

We also include methods like promote() to increase the student’s age and add_grade to add grades to the list. The __str__ method is overridden to provide a customized string representation of the object.

The code demonstrates various features of dataclasses, such as default values for attributes, the usage of the field function from the typing module, ordering based on attributes, and more.

Feel free to run this code and explore the functionalities of data classes in Python. It provides a concise and efficient way to work with data-centric classes, reducing boilerplate code and enhancing code readability and maintainability.

Exercise-2:

Write a program that represents a library management system using data classes in Python. We’ll define classes for books and library members, allowing us to add books to the library, lend books to members, and keep track of book availability.

Solution:

from dataclasses import dataclass, field
from typing import List

@dataclass
class Book:
    title: str
    author: str
    available: bool = True

@dataclass
class Member:
    name: str
    books_borrowed: List[Book] = field(default_factory=list)

    def borrow_book(self, book):
        if book.available:
            book.available = False
            self.books_borrowed.append(book)
            print(f"{self.name} has borrowed the book '{book.title}' by {book.author}.")
        else:
            print(f"Sorry, the book '{book.title}' is currently unavailable.")

    def return_book(self, book):
        if book in self.books_borrowed:
            book.available = True
            self.books_borrowed.remove(book)
            print(f"{self.name} has returned the book '{book.title}' by {book.author}.")
        else:
            print(f"Error: '{book.title}' is not borrowed by {self.name}.")

# Create instances of the Book class
book1 = Book("Python Crash Course", "Eric Matthes")
book2 = Book("Clean Code", "Robert C. Martin")
book3 = Book("The Alchemist", "Paulo Coelho")

# Create instances of the Member class
member1 = Member("Emma")
member2 = Member("Noah")

# Perform book borrowing and returning
member1.borrow_book(book1)
member1.borrow_book(book2)
member2.borrow_book(book2)
member2.borrow_book(book3)

member1.return_book(book2)
member2.return_book(book1)
member2.return_book(book3)

Summary:

In this program, we create two data classes: Book and Member. The Book class represents a book with attributes for the title, author, and available status. The Member class represents a library member with a name and a list of books_borrowed as attributes.

The Member class includes methods borrow_book() and return_book() to handle book borrowing and returning operations. When a member borrows a book, the book’s availability is updated, and the book is added to the member’s list of borrowed books. Similarly, when a member returns a book, the book’s availability is updated, and the book is removed from the member’s list.

In the main part of the code, we create instances of books and members. We then simulate book borrowing and returning operations by calling the corresponding methods on the member objects. The program outputs messages indicating successful borrowings or returns, as well as any errors encountered.

This code demonstrates how data classes can be used to model and manage objects in a library management system. It provides a simple and effective way to organize data and perform operations with minimal code, making it easier to understand and maintain the library management system.

Python dataclass exercises for practice

Here are a few more problem statements using Python dataclasses that you can try to solve:

Problem 1: Create a program to manage a student database. Each student has a name, and roll number while having enrolled for a list of subjects. Implement functionalities to add new students, display student details, and calculate the average marks of a student.

Problem 2: Design a program for a car rental agency. Create a car dataclass with attributes like make, model, year, and rental status. Implement methods to rent a car, return a car, and display the available cars.

Problem 3: Develop a program to simulate a banking system. Create dataclasses for customers and accounts. Each customer has a name and contact details, and each account has an account number, balance, and account type. Implement functionalities to create a new customer, open a bank account, perform deposits and withdrawals, and display account details.

Problem 4: Build a program for a movie ticket booking system. Create dataclasses for movies, theaters, and bookings. Each movie has a title, genre, and duration. Each theater holds a name and shows a list of currently playing movies. Implement functionalities to book a ticket, check seat availability, and display movie showtimes.

Above all, these problem statements cover a range of scenarios. Also, you can even tailor the complexity level and requirements accordingly. These exercises provide opportunities for beginners to apply data classes in real-world scenarios and practice their Python programming skills.

Summary – Python dataclass exercises

Finally, you have run through all of the above data classexercises and certainly learned a few things. If you liked it, don’t mind it sharing on social media.

By the way, if you haven’t had the chance to explore our blog’s set of 40 Python exercises for beginners, now is the perfect time to dive in. The collection comprises 10 basic, 10 intermediate, 10 advanced, and 10 expert-level exercises, catering to learners of all skill levels. Don’t miss this opportunity to challenge yourself and elevate your Python proficiency!

Happy Learning!

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

Selenium Python Extent Report Guide

10 Python Tricky Coding Exercises

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
Loading
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Harsh S. Avatar
By Harsh S.
Follow:
Hello, I'm Harsh, I hold a degree in Masters of Computer Applications. I have worked in different IT companies as a development lead on many large-scale projects. My skills include coding in multiple programming languages, application development, unit testing, automation, supporting CI/CD, and doing DevOps. I value Knowledge sharing and want to help others with my tutorials, quizzes, and exercises. I love to read about emerging technologies like AI and Data Science.
Previous Article Python dataclasses tutorial for beginners Get Started with DataClasses in Python
Next Article Putlocker Alternatives - Free and Safe Alternative Sites for Streaming Top 10 Free & Safe Putlocker Alternatives in 2024

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x