Docsity

Python Crash Course Part 2, Exercises of Programming Languages

Partial preview of the text

Download Python Crash Course Part 2 and more Exercises Programming Languages in PDF only on Docsity!

PART 2

NOVEMBER 23, 2023

JK Edu corp Avenue #1, New York

Course Content

Chapter 1: Introduction

 Brief overview of Python  Why learn Python?  Setting up Python (installation)

Chapter 2: Basics of Python

2.1 Variables and Data Types  What are variables?  Common data types (integers, floats, strings, booleans) 2.2 Operators  Arithmetic operators  Comparison operators  Logical operators 2.3 Control Flow  if statements  else statements  elif statements  while loops  for loops

Chapter 3: Data Structures

3.1 Lists  Creating lists  Indexing and slicing  Modifying lists 3.2 Dictionaries  Creating dictionaries  Accessing and modifying dictionary elements 3.3 Sets  Creating sets  Set operations 3.4 Tuples

 What are generators?  Creating and using generators 9.3 Virtual Environments  Why use virtual environments?  Creating and managing virtual environments

Chapter 10: Introduction to Libraries and Frameworks

 Overview of popular Python libraries (NumPy, Pandas, Matplotlib)  Introduction to popular frameworks (Django, Flask)

Chapter 11: Best Practices and Tips

 Writing clean and readable code  PEP 8 and coding conventions  Debugging techniques

Chapter 12: Final Projects and Further Learning

 Small projects to apply knowledge  Additional resources for further learning

CHAPTER 7:

INTRODUCTION

7.3 The else Block The else block is executed if no exceptions are raised in the try block. Example: Using the else Block try: num = int(input("Enter a number: ")) result = 10 / num except ValueError as ve: print(f"ValueError: {ve}") except ZeroDivisionError as zde: print(f"ZeroDivisionError: {zde}") result = float('inf') else: print(f"Result: {result}")  The else block contains code that should run only if no exceptions occur. 7.4 The finally Block The finally block is always executed, regardless of whether an exception occurs or not. It is commonly used for cleanup operations. Example: Using the finally Block try: file = open("example.txt", "r") content = file.read() result = 10 / int(content) except FileNotFoundError as fnfe: print(f"FileNotFoundError: {fnfe}") except ValueError as ve: print(f"ValueError: {ve}") except ZeroDivisionError as zde: print(f"ZeroDivisionError: {zde}")

result = float('inf') else: print(f"Result: {result}") finally: file.close() # Ensure the file is closed, regardless of exceptions  The finally block is often used for cleanup operations like closing files or releasing resources. 7.5 Raising Exceptions You can raise exceptions manually using the raise statement. Example: Raising an Exception def validate_age(age): if age < 0: raise ValueError("Age cannot be negative") return age try: user_age = validate_age(-5) except ValueError as ve: print(f"Error: {ve}")  The raise statement is used to signal that an exception should be raised. 7.6 Custom Exceptions Creating custom exceptions allows you to provide more context and structure to your error handling. Example: Creating a Custom Exception class CustomError(Exception): def init(self, message="A custom error occurred"): self.message = message super().init(self.message)

CHAPTER 8: OBJECT-

ORIENTED

PROGRAMMING (OOP)

Chapter 8: Object-Oriented Programming (OOP)

Object-Oriented Programming (OOP) is a programming paradigm that uses objects, which are instances of classes, to design and organize code. Python is an object-oriented programming language, and understanding OOP concepts is fundamental to writing scalable and maintainable code. 8.1 Classes and Objects 8.1.1 Defining Classes A class is a blueprint for creating objects. It defines attributes (properties) and methods (functions) that the objects created from the class will have. Example: Defining a Class class Dog: def init(self, name, age): self.name = name self.age = age def bark(self): print(f"{self.name} says Woof!")  The init method is a special method called a constructor, which is executed when an object is created.  self refers to the instance of the class and is used to access the class's attributes. 8.1.2 Creating Objects Once a class is defined, objects (instances) can be created from it. Example: Creating Objects from the Dog Class

Creating instances of the Dog class

dog1 = Dog("Buddy", 3) dog2 = Dog("Max", 5)

Accessing attributes

print(dog1.name) # Output: Buddy print(dog2.age) # Output: 5

class Beagle(Dog): def bark(self): print(f"{self.name} says Aroo!")

Creating an instance of the Beagle class

beagle = Beagle("Cooper", 4)

Calling the overridden method

beagle.bark() # Output: Cooper says Aroo! 8.3 Encapsulation and Polymorphism 8.3.1 Encapsulation Principles Encapsulation is the bundling of data and methods that operate on the data within a single unit, i.e., a class. It restricts access to some of the object's components, emphasizing the idea of data hiding. Example: Encapsulation class BankAccount: def init(self, balance=0): self._balance = balance # Use a single underscore to indicate a protected attribute def deposit(self, amount): self._balance += amount def withdraw(self, amount): if amount <= self._balance: self._balance -= amount else: print("Insufficient funds") def get_balance(self): return self.balance  Using a single underscore ( **** ) before an attribute indicates that it's intended to be protected.

8.3.2 Polymorphism in Python Polymorphism allows objects of different classes to be treated as objects of a common base class. It promotes flexibility and modularity in code. Example: Polymorphism

Function accepting objects of different types

def make_sound(animal): animal.make_sound()

Base class with a common method

class Animal: def make_sound(self): pass

Subclasses implementing the method differently

class Dog(Animal): def make_sound(self): print("Woof!") class Cat(Animal): def make_sound(self): print("Meow!")

Using polymorphism

dog = Dog() cat = Cat() make_sound(dog) # Output: Woof! make_sound(cat) # Output: Meow! Understanding OOP concepts like classes, objects, inheritance, encapsulation, and polymorphism is crucial for designing scalable and maintainable code. Practice creating classes, using inheritance, and applying encapsulation and polymorphism to enhance your object-oriented programming skills in Python.

Chapter 9: Advanced Topics

In this chapter, we will explore advanced topics in Python that go beyond the basics. These topics are essential for writing more efficient and organized code. 9.1 Decorators 9.1.1 Understanding Decorators Decorators in Python are a powerful and flexible way to modify or extend the behavior of functions or methods. They allow you to wrap another function, enabling you to perform actions before and after the wrapped function is called. Example: Basic Decorator def my_decorator(func): def wrapper(): print("Something is happening before the function is called.") func() print("Something is happening after the function is called.") return wrapper @my_decorator def say_hello(): print("Hello!")

Calling the decorated function

say_hello()  The @my_decorator syntax is a shorthand for say_hello = my_decorator(say_hello). 9.1.2 Creating Decorators Decorators can take arguments, making them versatile for various use cases. Example: Decorator with Arguments def repeat(n): def decorator(func): def wrapper(*args, **kwargs):

for _ in range(n): func(*args, **kwargs) return wrapper return decorator @repeat(3) def greet(name): print(f"Hello, {name}!")

Calling the decorated function

greet("Alice")  The @repeat(3) syntax applies the decorator with an argument n=3 to the greet function. 9.2 Generators 9.2.1 What are Generators? Generators in Python provide an efficient way to create iterators. Unlike lists, generators generate values on-the-fly, saving memory and improving performance. Example: Creating a Generator def countdown(n): while n > 0: yield n n -= 1

Using the generator in a loop

for i in countdown(5): print(i)  The yield statement is used to produce a value from the generator, and the state of the generator is saved.

Example: Installing Dependencies in a Virtual Environment

Installing a package in the virtual environment

pip install package_name  When the virtual environment is activated, the pip command installs packages only within the virtual environment. Understanding decorators, generators, and virtual environments is crucial for more advanced Python programming. Decorators enable you to enhance the behaviour of functions, generators provide a memory-efficient way to work with sequences of data, and virtual environments keep your project dependencies isolated and manageable. Incorporating these advanced topics into your skill set will contribute to writing cleaner, more modular, and efficient Python code.

CHAPTER 10: INTRODUCTION TO LIBRARIES AND FRAMEWORKS