Python Notes
Python is a high-level, interpreted, and general-purpose programming language known for its simplicity and
readability. It supports multiple programming paradigms, including procedural, object-oriented, and functional
programming. Python is widely used for web development, data analysis, machine learning, automation, and
more.
Here are the key points about Python:
1. Overview of Python
• Readable Syntax: Python is known for its clear and concise syntax, making it an excellent choice for
beginners.
• Interpreted Language: Python code is executed line by line by the Python interpreter, making
debugging easier but potentially slower than compiled languages.
• Cross-Platform: Python is platform-independent, meaning you can run Python code on any operating
system (Windows, macOS, Linux).
• Dynamic Typing: Variables don't need explicit type definitions. Python determines the type
dynamically at runtime.
2. Basic Python Program Structure
A simple Python program structure:
print("Hello, World!")
• print(): This function prints output to the console.
3. Variables and Data Types
• Variables: Used to store data in Python. No need to declare the type explicitly.
• x = 5 # Integer
• name = "Alice" # String
• is_active = True # Boolean
• Basic Data Types:
o int: Integer numbers (e.g., 5, 42).
o float: Decimal numbers (e.g., 3.14, 0.1).
o str: Strings of text (e.g., "Hello, Python!").
o bool: Boolean values (True or False).
o list: Ordered, mutable collection (e.g., [1, 2, 3]).
o tuple: Ordered, immutable collection (e.g., (1, 2, 3)).
o dict: Unordered collection of key-value pairs (e.g., {"key": "value"}).
o set: Unordered collection of unique items (e.g., {1, 2, 3}).
4. Control Flow Statements
Python has the standard control flow statements such as:
• Conditional Statements: if, elif, else
• if x > 10:
• print("x is greater than 10")
• elif x == 10:
• print("x is equal to 10")
• else:
• print("x is less than 10")
• Loops:
o for loop: Iterates over a sequence (e.g., list, range).
o for i in range(5):
o print(i) # Prints numbers from 0 to 4
o while loop: Repeats as long as the condition is True.
o count = 0
o while count < 5:
o print(count)
o count += 1
5. Functions
Functions are defined using the def keyword.
def greet(name):
print(f"Hello, {name}!")
greet("Alice") # Output: Hello, Alice!
• Functions can accept parameters and return values using the return keyword.
• Example with return:
• def add(a, b):
• return a + b
• result = add(3, 5)
• print(result) # Output: 8
6. Classes and Objects (Object-Oriented Programming)
Python supports object-oriented programming, allowing the creation of classes and 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.")
# Creating an object of the Person class
person1 = Person("Alice", 30)
person1.greet() # Output: Hello, my name is Alice and I am 30 years old.
7. Exception Handling
Python uses try, except blocks to handle exceptions (errors).
try:
x = 10 / 0 # Division by zero will raise an exception
except ZeroDivisionError as e:
print(f"Error: {e}")
finally:
print("This block is always executed.")
8. List Comprehensions
Python supports a concise way of creating lists using list comprehensions.
squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]
9. Modules and Libraries
Python has a rich standard library and supports the use of external libraries.
• Importing Modules:
• import math
• print(math.sqrt(16)) # Output: 4.0
• You can also create your own modules by saving Python code in a .py file and importing it.
• Example of importing a custom module:
• # file: mymodule.py
• def greet(name):
• print(f"Hello, {name}!")
•
• # file: main.py
• import mymodule
• mymodule.greet("Bob")
10. File Handling
Python can read and write files using built-in functions.
• Reading a file:
• with open('file.txt', 'r') as file:
• content = file.read()
• print(content)
• Writing to a file:
• with open('file.txt', 'w') as file:
• file.write("Hello, Python!")
11. Libraries and Frameworks
Python has a vast ecosystem of libraries and frameworks that simplify development.
• Web Development:
o Django, Flask
• Data Science and Machine Learning:
o Pandas, NumPy, Matplotlib, Scikit-learn, TensorFlow, Keras
• Automation:
o Selenium, PyAutoGUI, BeautifulSoup (for web scraping)
• GUI Development:
o Tkinter, PyQt
12. Decorators
Python decorators are functions that modify the behavior of other functions or methods.
def decorator_function(func):
def