Free Python Course | Programming Tutorials
599 subscribers
9 photos
2 files
6 links
Join Noob to Pro in Python in 100 Days! ๐Ÿš€ Learn Python with daily lessons, practical examples, free code samples, exercises, and homework. Ideal for beginners and those looking to advance their skills. Start your journey to becoming a Python pro! ๐Ÿ
Download Telegram
Importing Modules
There are several ways to import modules in Python:

1. Import the entire module:
import mymodule

Access the moduleโ€™s functions or variables using mymodule.function_name().

2. Import specific functions or variables:
from mymodule import greet

In this case, you can directly use the greet() function without the module prefix.

3. Import with an alias:
import mymodule as mm

print(mm.greet("Bob")) # Output: Hello, Bob!


4. Import everything from a module:
from mymodule import *


This imports all functions and variables from the module. Use this carefully to avoid name conflicts.
Exploring Built-in Modules
Python comes with a wide range of built-in modules that provide functionality for common tasks. Some popular built-in modules include:


math: Mathematical functions
random: Random number generation
datetime: Working with dates and times
os: Interacting with the operating system
sys: System-specific parameters and functions

Example: Using the math Module
import math

print(math.sqrt(16)) # Output: 4.0
print(math.pi) # Output: 3.141592653589793


Example: Using the random Module
import random

print(random.randint(1, 10)) # Output: Random integer between 1 and 10


Example: Using the datetime Module
import datetime

now = datetime.datetime.now()
print(now) # Output: Current date and time
What is a Package?
A package is a collection of modules organized in directories that provide a hierarchical structure. Packages allow you to organize your project into multiple modules and sub-packages.

Creating a Package
A package is simply a directory that contains one or more modules and a special file named __init__.py. The __init__.py file is required to make Python treat the directory as a package. It can be empty or contain initialization code for the package.

Package Structure:
mypackage/
__init__.py
module1.py
module2.py


Example: Creating a Package
1. Create a directory named mypackage.
2. Inside the directory, create the following files:
mypackage/__init__.py:
# This is the initialization file for the package

mypackage/module1.py:
def add(a, b):
return a + b

mypackage/module2.py:
def subtract(a, b):
return a - b


3. Now you can import the package modules in your Python code:
Example:
from mypackage import module1, module2

print(module1.add(10, 5)) # Output: 15
print(module2.subtract(10, 5)) # Output: 5
โค1
Installing and Using External Packages (PIP)
Python has a huge collection of third-party packages available via the Python Package Index (PyPI). You can install these packages using the pip tool.

Installing a Package with PIP
To install an external package, use the command:
pip install package_name


Example: Installing and Using the requests Library
pip install requests


Once installed, you can use the requests module to make HTTP requests:
import requests

response = requests.get("https://jsonplaceholder.typicode.com/posts/1")
print(response.json())

This will print the JSON response from the given URL.
Finding and Installing External Packages
To find packages:
- Visit the Python Package Index (PyPI) to browse and search for Python packages.

To install a package globally (available for all projects):
pip install package_name


To install a package locally in a virtual environment:
1. Create a virtual environment:
python -m venv myenv

2. Activate the virtual environment:
# Windows
myenv\Scripts\activate

# Mac/Linux
source myenv/bin/activate

3. Install the package:
pip install package_name
Managing Dependencies with requirements.txt
In larger projects, you may want to specify which external packages (dependencies) your project needs. This is typically done using a requirements.txt file.

Creating requirements.txt
You can automatically generate this file with the following command:
pip freeze > requirements.txt

This command lists all installed packages and their versions in the requirements.txt file.

Installing Dependencies from requirements.txt
To install all the packages listed in a requirements.txt file, use the following command:
pip install -r requirements.txt
Practice Exercises for Day 12

Exercise 1: Simple Module

Create a Python module with functions for addition, subtraction, multiplication, and division. Import the module in another script and use its functions.

Exercise 2: Math and Random Modules
Use the built-in math and random modules to generate random numbers and calculate their square roots.

Exercise 3: Package Creation
Create a package with two modules: one for basic math operations (addition, subtraction) and one for advanced operations (power, square root). Import these modules in a script and use their functions.

Exercise 4: External Package
Install the requests module using pip and write a Python script to fetch and display data from a public API (e.g., a list of posts from JSONPlaceholder).

Exercise 5: Virtual Environment
Create a virtual environment, activate it, install the requests module, and use it in a Python script.
๐Ÿ‘1
Summary
In Day 12, we covered:

Modules: How to create and import modules to organize your code.
Packages: Organizing multiple modules into packages for better structure.
Built-in modules: Using standard Python modules like math, random, and datetime.
PIP: Installing external packages and managing project dependencies with requirements.txt.
Virtual environments: Isolating dependencies for different projects.

Mastering modules and packages is essential for writing scalable and maintainable Python programs. It helps in organizing code, avoiding repetition, and using reusable components. Keep practicing to solidify your understanding!
โค2
Day 13: Object-Oriented Programming (OOP) - Classes and Objects
Welcome to Day 13 of the "Noob to Pro in Python" course! Today, weโ€™ll dive into Object-Oriented Programming (OOP), a powerful paradigm in Python. OOP helps in structuring programs using objects, which can contain both data and methods. We'll begin with understanding classes and objects, which are the foundation of OOP.
โค1
Introduction to Object-Oriented Programming (OOP)
Object-Oriented Programming (OOP) is a programming paradigm that focuses on using objects and classes. In OOP:

A class is a blueprint for creating objects.
An object is an instance of a class.

Key Concepts of OOP:
Class: A blueprint for creating objects.
Object: An instance of a class.
Attributes: Data (variables) stored in an object.
Methods: Functions that are defined inside a class and describe the behavior of the objects.
Instantiation: The process of creating an object from a class.
Creating Classes
In Python, classes are defined using the class keyword. Inside the class, we define attributes and methods.

Basic syntax of class:
class ClassName:
# Class attributes and methods


Example: Creating a simple class
class Dog:
# Class attributes (shared by all instances)
species = "Canis familiaris"

# Constructor method to initialize instance attributes
def __init__(self, name, age):
self.name = name # Instance attribute
self.age = age # Instance attribute

# Method to display dog's information
def display_info(self):
print(f"My dog {self.name} is {self.age} years old.")

In this example:
Class attribute: species is shared by all instances of the class.
Instance attributes: name and age are unique to each instance.
The __init__() method is the constructor that is automatically called when an object is created.
Creating Objects (Instances)
Objects are created (instantiated) by calling the class with its required arguments.

Example: Creating an Object
dog1 = Dog("Buddy", 4)  # Creating an object of the Dog class
dog1.display_info() # Output: My dog Buddy is 4 years old.

Here, dog1 is an instance of the Dog class with its own name and age attributes.
Instance Variables and Class Variables
Instance variables are unique to each object. They are defined inside the constructor (__init__()).
Class variables are shared by all objects of the class. They are defined directly inside the class but outside any method.

Example: Class and Instance Variables
class Car:
# Class variable (shared by all instances)
wheels = 4

def __init__(self, model, color):
# Instance variables (unique to each instance)
self.model = model
self.color = color

car1 = Car("Toyota", "Red")
car2 = Car("Honda", "Blue")

print(car1.wheels) # Output: 4
print(car2.wheels) # Output: 4
print(car1.model) # Output: Toyota
print(car2.color) # Output: Blue
Methods in Classes
Methods are functions that belong to a class. They are defined inside a class and take self as the first parameter. This self parameter allows the method to access instance variables and other methods within the class.

Example: Defining methods
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height

# Method to calculate area
def area(self):
return self.width * self.height

rect1 = Rectangle(10, 5)
print(f"Area of rectangle: {rect1.area()}") # Output: Area of rectangle: 50
The self Parameter
The self keyword refers to the current instance of the class. It is used to access instance variables and methods within the class.
The self parameter must be the first parameter of any method in the class.

Example: Using self
class Circle:
def __init__(self, radius):
self.radius = radius

def circumference(self):
return 2 * 3.1416 * self.radius

circle1 = Circle(7)
print(f"Circumference of circle: {circle1.circumference()}") # Output: 43.9824
Modifying and Accessing Attributes
You can modify and access attributes directly or through methods.

Example: Modifying Attributes
class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade

def update_grade(self, new_grade):
self.grade = new_grade

student1 = Student("Alice", "A")
student1.update_grade("B")
print(f"{student1.name} has a grade of {student1.grade}.") # Output: Alice has a grade of B.
Inheritance
Inheritance allows one class (child class) to inherit attributes and methods from another class (parent class). This allows code reuse and the creation of more specific classes from a general class.

Syntax of Inheritance:
class ParentClass:
# Parent class code

class ChildClass(ParentClass):
# Child class code (inherits from ParentClass)


Example: Inheritance
class Animal:
def __init__(self, name):
self.name = name

def speak(self):
print(f"{self.name} makes a sound.")

class Dog(Animal): # Dog inherits from Animal
def speak(self):
print(f"{self.name} barks.")

dog1 = Dog("Buddy")
dog1.speak() # Output: Buddy barks.

In this example, the Dog class inherits from the Animal class and overrides the speak() method.
๐Ÿ‘1
Method Overriding
When a method in a subclass has the same name as a method in the parent class, the method in the subclass overrides the method in the parent class. This allows the child class to modify or extend the behavior of the parent class method.

Example: Method Overriding
class Animal:
def speak(self):
print("Animal makes a sound.")

class Cat(Animal):
def speak(self):
print("Cat meows.")

cat1 = Cat()
cat1.speak() # Output: Cat meows.
๐Ÿ‘2
Day 14: Object-Oriented Programming (OOP) - Part 2: Inheritance and Polymorphism
Welcome to Day 14 of the "Noob to Pro in Python" course! Yesterday, we explored the basics of Object-Oriented Programming (OOP), covering classes, objects, methods, and attributes. Today, we will dive deeper into OOP, focusing on inheritance and polymorphismโ€”two powerful concepts that enable code reuse and flexibility.
Inheritance in Python
Inheritance allows a class (called a child class or subclass) to inherit attributes and methods from another class (called a parent class or superclass). This promotes code reuse and logical class relationships.

Example: Inheritance Syntax
class Parent:
def __init__(self, name):
self.name = name

def speak(self):
print(f"{self.name} is speaking.")

# Child class inheriting from Parent class
class Child(Parent):
def play(self):
print(f"{self.name} is playing.")

# Creating an object of the Child class
child1 = Child("Alice")
child1.speak() # Inherited method from Parent class
child1.play() # Child class method

In this example:
The Child class inherits the speak() method from the Parent class.
The Child class also has its own method, play().
The super() Function
The super() function allows a child class to call the constructor or methods of its parent class. This is useful when you want to extend the functionality of a parent class without duplicating code.

Example: Using super()
class Animal:
def __init__(self, species):
self.species = species

def sound(self):
print("Some generic animal sound.")

# Child class inheriting from Animal class
class Dog(Animal):
def __init__(self, name, species="Dog"):
super().__init__(species) # Calling parent class constructor
self.name = name

def sound(self):
super().sound() # Calling parent class method
print(f"{self.name} barks!")

dog1 = Dog("Buddy")
dog1.sound()

Here, the super() function calls the parent classโ€™s __init__() method to initialize the species attribute and also calls the parent class's sound() method from the child class.