Python Class Notes
1. Introduction to Python
What is Python?
Python is a high-level, interpreted programming language.
It is easy to read and write, known for its simple syntax.
Python supports multiple programming paradigms including procedural, object-oriented, and functional programming.
Features of Python
Simple and easy to learn.
Open-source and cross-platform.
Extensive standard library.
High-level language (abstracts memory management).
Dynamically typed (no need to declare variable types).
2. Basic Syntax
Comments
Single-line comment: # This is a comment
Multi-line comment: """
This is a
multi-line comment
"""
Variables
Variables in Python are dynamically typed.
Example: x = 10, name = "Alice"
Print Statements
print() function displays output.
print("Hello, World!")
3. Data Types
Numbers
Integers (int), floating point numbers (float), and complex numbers (complex).
num1 = 10 # Integer
num2 = 3.14 # Float
num3 = 2 + 3j # Complex
Strings
Strings are sequences of characters enclosed in single, double, or triple quotes.
str1 = "Hello"
str2 = 'World'
str3 = """This is
a multi-line
string"""
Lists
Ordered, mutable collection of elements.
my_list = [1, 2, 3, "apple"]
Tuples
Ordered, immutable collection of elements.
my_tuple = (1, 2, 3, "banana")
Dictionaries
Unordered, mutable collection of key-value pairs.
my_dict = {"name": "Alice", "age": 25}
Sets
Unordered collection of unique elements.
my_set = {1, 2, 3, 4}
4. Control Flow
If-else Statements
x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")
Elif Statements
x = 20
if x > 30:
print("x is greater than 30")
elif x == 20:
print("x is equal to 20")
else:
print("x is less than 20")
Loops
for loop (iterates over sequences): for i in range(5):
print(i)
while loop (runs until a condition is False): i = 0
while i < 5:
print(i)
i += 1
5. Functions
Defining Functions
def greet(name):
print(f"Hello, {name}")
greet("Alice") # Output: Hello, Alice
Return Values
def add(a, b):
return a + b
result = add(2, 3)
print(result) # Output: 5
Arguments
Positional arguments: def subtract(a, b):
return a - b
print(subtract(5, 3)) # Output: 2
Default arguments: def greet(name="World"):
print(f"Hello, {name}")
greet() # Output: Hello, World
greet("Bob") # Output: Hello, Bob
Keyword arguments: def print_person(name, age):
print(f"{name} is {age} years old.")
print_person(age=25, name="Alice") # Output: Alice is 25 years old.
6. Modules and Libraries
Importing Modules
import math
print(math.sqrt(16)) # Output: 4.0
Import Specific Function
from math import sqrt
print(sqrt(25)) # Output: 5.0
Creating Your Own Modules
Save your Python functions in a .py file, e.g., mymodule.py.
Import it into other programs: import mymodule
mymodule.some_function()
7. Object-Oriented Programming (OOP)
Classes and Objects
A class is a blueprint for creating objects.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
p = Person("Alice", 25)
p.greet() # Output: Hello, my name is Alice and I am 25 years old.
Inheritance
Inheritance allows one class to inherit attributes and methods from another class.
class Employee(Person):
def __init__(self, name, age, job):
super().__init__(name, age)
self.job = job
def work(self):
print(f"{self.name} is working as a {self.job}")
e = Employee("Bob", 30, "Engineer")
e.work() # Output: Bob is working as a Engineer
Polymorphism
Methods in derived classes can override methods in base classes.
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def speak(self):
print("Dog barks")
d = Dog()
d.speak() # Output: Dog barks
8. Exception Handling
Try-Except Block
try:
x = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
Finally Block
try:
x = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
finally:
print("This will always execute.")
9. File Handling
Opening a File
file = open("sample.txt", "w")
file.write("Hello, Python!")
file.close()
Reading a File
file = open("sample.txt", "r")
content = file.read()
print(content) # Output: Hello, Python!
file.close()
Using with Statement
Automatically handles file closure.
with open("sample.txt", "r") as file:
content = file.read()
print(content)
10. Libraries and Frameworks
Popular Libraries:
NumPy: For numerical computations.
Pandas: For data manipulation and analysis.
Matplotlib: For data visualization.
Flask/Django: Web frameworks.
Installation of Libraries
pip install numpy
11. Conclusion
Python is a powerful and versatile language used for web development, data analysis, machine learning, automation, and more. It's beginner-
friendly but also robust enough for professionals. Mastering Python can open doors to many fields in software development.