Python Programming Notes
1. Introduction to Python
What is Python?
Python is a high-level, interpreted, general-purpose programming language created by
Guido van Rossum in 1991. It emphasizes code readability with the use of significant
indentation. Python is widely used in web development, data science, machine learning,
automation, and scientific computing.
Key Features of Python
Easy to Learn - Simple syntax similar to English language
Interpreted Language - Code executed line by line by interpreter
Dynamically Typed - No need to declare data types explicitly
Object-Oriented - Supports classes and objects
Rich Standard Library - Extensive built-in modules and functions
Platform-Independent - Runs on Windows, Mac, Linux
Extensive Frameworks - Django, Flask, NumPy, Pandas, TensorFlow
Community Support - Large, active community with resources
Why Learn Python?
Most popular language for machine learning and AI
Data science and analytics
Web development with Django and Flask
Automation and scripting
Scientific computing
Game development
Cybersecurity and ethical hacking
2. Setting Up Python Environment
Installation
1. Download Python from: [Link]
2. Run installer and check "Add Python to PATH"
3. Verify installation: python --version
IDEs and Editors
PyCharm - Full-featured IDE
VS Code - Lightweight with extensions
Jupyter Notebook - Interactive coding
Thonny - Beginner-friendly
IDLE - Built-in Python IDE
Your First Python Program
print("Hello, Python!")
Run the program:
python [Link]
3. Basic Syntax and Data Types
Variables and Assignment
Variables (no type declaration needed)
name = "Alice"
age = 25
height = 5.6
is_student = True
Multiple assignment
x, y, z = 1, 2, 3
Dynamic typing
var = 10 # Integer
var = "hello" # String (type changed)
Data Types
Integer
age = 25
count = -10
Float
price = 99.99
pi = 3.14159
String
name = "John"
message = 'Hello, World!'
multi_line = """This is a
multi-line string"""
Boolean
is_valid = True
is_empty = False
None
result = None
Type Conversion
Convert to different types
x = "10"
y = int(x) # Convert to integer
z = float(x) # Convert to float
s = str(25) # Convert to string
b = bool(1) # Convert to boolean
print(type(y)) # <class 'int'>
print(type(s)) # <class 'str'>
4. Operators
Arithmetic Operators
a = 10
b=3
print(a + b) # 13 (Addition)
print(a - b) # 7 (Subtraction)
print(a * b) # 30 (Multiplication)
print(a / b) # 3.333... (Division)
print(a // b) # 3 (Floor Division)
print(a % b) # 1 (Modulus)
print(a ** b) # 1000 (Exponentiation)
Comparison Operators
x = 10
y =5
print(x == y) # False (Equal)
print(x != y) # True (Not equal)
print(x > y) # True (Greater than)
print(x < y) # False (Less than)
print(x >= y) # True (Greater or equal)
print(x <= y) # False (Less or equal)
Logical Operators
a = True
b = False
print(a and b) # False (AND)
print(a or b) # True (OR)
print(not a) # False (NOT)
Assignment Operators
x = 10
x += 5 # x = 15 (Addition assignment)
x -= 3 # x = 12
x *= 2 # x = 24
x /= 4 # x = 6.0
x //= 2 # x = 3.0
x %= 3 # x = 0.0
5. Control Flow Statements
If-Else Statement
age = 18
if age >= 18:
print("You are an adult")
else:
print("You are a minor")
If-Elif-Else
marks = 75
if marks >= 90:
print("Grade: A")
elif marks >= 80:
print("Grade: B")
elif marks >= 70:
print("Grade: C")
else:
print("Grade: F")
Ternary Operator
age = 20
status = "Adult" if age >= 18 else "Minor"
print(status)
6. Loops
For Loop
Print numbers 1 to 5
for i in range(1, 6):
print(i)
Loop through list
fruits = ["Apple", "Banana", "Orange"]
for fruit in fruits:
print(fruit)
Loop with index
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
While Loop
count = 1
while count <= 5:
print(count)
count += 1
Break and Continue
Break - exit loop
for i in range(1, 11):
if i == 5:
break
print(i) # 1 2 3 4
Continue - skip iteration
for i in range(1, 6):
if i == 3:
continue
print(i) # 1 2 4 5
7. Functions
Function Definition
Simple function
def greet():
print("Hello!")
greet() # Call function
Function with parameters
def add(a, b):
return a + b
result = add(5, 3)
print(result) # 8
Function with default parameters
def introduce(name, age=18):
print(f"{name} is {age} years old")
introduce("Alice")
introduce("Bob", 25)
Function with Multiple Return Values
def get_name_and_age():
return "Alice", 25
name, age = get_name_and_age()
print(name, age) # Alice 25
Variable-length Arguments
def sum_numbers(*numbers):
total = 0
for num in numbers:
total += num
return total
print(sum_numbers(1, 2, 3)) # 6
print(sum_numbers(1, 2, 3, 4, 5)) # 15
Keyword arguments
def print_info(**info):
for key, value in [Link]():
print(f"{key}: {value}")
print_info(name="Alice", age=25, city="Mumbai")
Lambda Functions
Anonymous function
square = lambda x: x ** 2
print(square(5)) # 25
Use in map
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # [1, 4, 9, 16, 25]
Use in filter
even = list(filter(lambda x: x % 2 == 0, numbers))
print(even) # [2, 4]
8. Strings
String Creation and Access
text = "Hello, Python!"
Access character
print(text[0]) # H
print(text[-1]) # !
String slicing
print(text[0:5]) # Hello
print(text[7:]) # Python!
print(text[:5]) # Hello
String Methods
text = "hello world"
print([Link]()) # HELLO WORLD
print([Link]()) # Hello world
print([Link]("world")) # 6
print([Link]("world", "python")) # hello python
print([Link]()) # ['hello', 'world']
print([Link]("hello")) # True
print([Link]("world")) # True
String Formatting
name = "Alice"
age = 25
Old style
print("Name: %s, Age: %d" % (name, age))
Format method
print("Name: {}, Age: {}".format(name, age))
f-string (Python 3.6+)
print(f"Name: {name}, Age: {age}")
print(f"Age after 5 years: {age + 5}")
9. Lists
List Creation and Access
Create list
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]
Access elements
print(numbers[0]) # 1
print(numbers[-1]) # 5
List slicing
print(numbers[1:4]) # [2, 3, 4]
print(numbers[:3]) # [1, 2, 3]
print(numbers[::2]) # [1, 3, 5] (every 2nd element)
List Methods
numbers = [1, 2, 3]
Add elements
[Link](4) # [1, 2, 3, 4]
[Link]([5, 6]) # [1, 2, 3, 4, 5, 6]
[Link](0, 0) # [0, 1, 2, 3, 4, 5, 6]
Remove elements
[Link](3) # Remove value 3
popped = [Link]() # Remove and return last element
[Link](0) # Remove element at index 0
Other operations
print(len(numbers)) # Length
print(3 in numbers) # Check if element exists
[Link]() # Sort in place
[Link]() # Reverse in place
[Link](2) # Count occurrences
[Link](5) # Find index of element
[Link]() # Remove all elements
List Comprehension
Create lists using comprehension
squares = [x ** 2 for x in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
With condition
even = [x for x in range(10) if x % 2 == 0]
print(even) # [0, 2, 4, 6, 8]
10. Tuples
Tuple Creation
Immutable sequence
point = (3, 4)
person = ("Alice", 25, "Engineer")
Access elements
print(point[0]) # 3
print(person[1]) # 25
Tuple unpacking
x, y = point
print(x, y) # 3 4
Tuple operations
print(len(point)) # 2
print(5 in point) # False
Tuple vs List
Tuples are immutable
my_tuple = (1, 2, 3)
my_tuple[0] = 10 # Error!
Lists are mutable
my_list = [1, 2, 3]
my_list[0] = 10 # OK
11. Dictionaries
Dictionary Creation and Access
Create dictionary
student = {
"name": "Alice",
"age": 25,
"cgpa": 8.5,
"branch": "CSE"
}
Access values
print(student["name"]) # Alice
print([Link]("age")) # 25
print([Link]("city", "Mumbai")) # Mumbai (default if not found)
Dictionary Methods
student = {"name": "Alice", "age": 25}
Add/modify
student["city"] = "Mumbai" # Add new key
student["age"] = 26 # Modify existing value
Remove
del student["city"] # Delete key
[Link]("age") # Remove and return value
Iterate
for key in student:
print(f"{key}: {student[key]}")
for key, value in [Link]():
print(f"{key}: {value}")
Get keys and values
print([Link]()) # dict_keys(['name', 'age'])
print([Link]()) # dict_values(['Alice', 26])
Other operations
print(len(student)) # 2
print("name" in student) # True
[Link]() # Remove all items
12. Sets
Set Creation and Operations
Create set (unordered, unique elements)
numbers = {1, 2, 3, 3, 4}
print(numbers) # {1, 2, 3, 4}
Add and remove
[Link](5) # {1, 2, 3, 4, 5}
[Link](3) # {1, 2, 4, 5}
[Link](10) # No error if element doesn't exist
Set operations
set1 = {1, 2, 3}
set2 = {2, 3, 4}
print(set1 & set2) # Intersection: {2, 3}
print(set1 | set2) # Union: {1, 2, 3, 4}
print(set1 - set2) # Difference: {1}
13. Object-Oriented Programming (OOP)
Classes and Objects
class Student:
# Class variable
school = "ABC School"
# Constructor
def __init__(self, name, roll_no, cgpa):
# Instance variables
[Link] = name
self.roll_no = roll_no
[Link] = cgpa
# Instance method
def display_info(self):
print(f"Name: {[Link]}")
print(f"Roll No: {self.roll_no}")
print(f"CGPA: {[Link]}")
def get_grade(self):
if [Link] >= 8.0:
return "A"
elif [Link] >= 7.0:
return "B"
else:
return "C"
Create objects
student1 = Student("Alice", 101, 8.5)
student2 = Student("Bob", 102, 7.2)
student1.display_info()
print(f"Grade: {student1.get_grade()}") # Grade: A
Inheritance
Parent class
class Vehicle:
def init(self, brand, year):
[Link] = brand
[Link] = year
def display_info(self):
print(f"Brand: {[Link]}, Year: {[Link]}")
Child class
class Car(Vehicle):
def init(self, brand, year, doors):
super().init(brand, year)
[Link] = doors
def display_info(self):
super().display_info()
print(f"Doors: {[Link]}")
Usage
car = Car("Honda", 2020, 4)
car.display_info()
Polymorphism
class Animal:
def sound(self):
pass
class Dog(Animal):
def sound(self):
return "Woof! Woof!"
class Cat(Animal):
def sound(self):
return "Meow! Meow!"
Usage
animals = [Dog(), Cat(), Dog()]
for animal in animals:
print([Link]())
14. Exception Handling
Try-Except
try:
num1 = 10
num2 = 0
result = num1 / num2
print(result)
except ZeroDivisionError:
print("Cannot divide by zero!")
except TypeError:
print("Invalid data type!")
except Exception as e:
print(f"Error: {e}")
finally:
print("Program completed")
Custom Exceptions
class CustomError(Exception):
def init(self, message):
[Link] = message
try:
age = 10
if age < 18:
raise CustomError("Age must be 18 or above")
except CustomError as e:
print(f"Error: {[Link]}")
15. File Handling
Reading from File
Read entire file
with open("[Link]", "r") as file:
content = [Link]()
print(content)
Read line by line
with open("[Link]", "r") as file:
for line in file:
print([Link]())
Read all lines
with open("[Link]", "r") as file:
lines = [Link]()
Writing to File
Write to file
with open("[Link]", "w") as file:
[Link]("Hello, File!\n")
[Link]("Line 2\n")
Append to file
with open("[Link]", "a") as file:
[Link]("Line 3\n")
16. Modules and Packages
Import Modules
Import entire module
import math
print([Link])
print([Link](16))
Import specific function
from math import sqrt, pi
print(sqrt(25)) # 5
Import with alias
import numpy as np
arr = [Link]([1, 2, 3])
Import all
from math import *
print(ceil(3.4))
Common Modules
Random numbers
import random
print([Link](1, 10))
print([Link]([1, 2, 3, 4, 5]))
Date and time
import datetime
today = [Link]()
now = [Link]()
Operating system
import os
print([Link]())
print([Link]())
JSON
import json
data = {"name": "Alice", "age": 25}
json_string = [Link](data)
parsed = [Link](json_string)
17. Common Programming Problems and Solutions
Problem 1: Sum of List Elements
numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print(f"Sum: {total}") # 15
Or using loop
total = 0
for num in numbers:
total += num
print(f"Sum: {total}")
Problem 2: Find Maximum Element
numbers = [3, 7, 2, 9, 1]
maximum = max(numbers)
print(f"Maximum: {maximum}") # 9
Problem 3: Check if Number is Prime
def is_prime(n):
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(n**0.5) + 1, 2):
if n % i == 0:
return False
return True
print(is_prime(17)) # True
print(is_prime(20)) # False
Problem 4: Reverse a String
text = "Hello"
Method 1: Slicing
reversed_text = text[::-1]
print(reversed_text) # olleH
Method 2: Loop
reversed_text = ""
for char in text:
reversed_text = char + reversed_text
print(reversed_text) # olleH
Problem 5: Fibonacci Sequence
def fibonacci(n):
a, b = 0, 1
result = []
for _ in range(n):
[Link](a)
a, b = b, a + b
return result
print(fibonacci(10)) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
18. Python Best Practices
1. Use Meaningful Names - Variables and functions with clear names
2. Follow PEP 8 - Python Enhancement Proposal 8 style guide
3. Write Docstrings - Document functions and classes
4. Use Type Hints - Specify expected types (Python 3.5+)
5. DRY Principle - Don't Repeat Yourself
6. Error Handling - Always use try-except appropriately
7. Virtual Environments - Use venv to isolate projects
8. List Comprehensions - More Pythonic than loops
9. Context Managers - Use with statement for file handling
10. Testing - Write unit tests using unittest or pytest
19. Quick Reference
String Methods
upper(), lower(), capitalize(), title(), strip()
split(), join(), replace(), find(), startswith()
endswith(), count(), format()
List Methods
append(), extend(), insert(), remove(), pop()
clear(), sort(), reverse(), copy(), index(), count()
Dictionary Methods
keys(), values(), items(), get(), pop(), update()
clear(), copy(), fromkeys()
Set Methods
add(), remove(), discard(), clear(), union()
intersection(), difference(), issubset(), issuperset()
20. Resources for Further Learning
Official Python Documentation: [Link]
Python Tutorial: [Link]
GeeksforGeeks Python: [Link]
Real Python: [Link]
Practice Platforms: LeetCode, HackerRank, CodeChef, Codewars
Books: "Python Crash Course" by Eric Matthes, "Fluent Python" by Luciano Ramalho
YouTube: Search "Python Complete Course for Beginners"
Conclusion
Python is a powerful, versatile language suitable for beginners and experts alike. Its simple
syntax combined with powerful libraries makes it ideal for web development, data science,
and automation. Keep practicing regularly, explore libraries like NumPy and Pandas for
data science, and Django/Flask for web development.
Key Takeaway: Master the fundamentals (data types, loops, functions, OOP), then explore
domain-specific libraries for your area of interest.
Happy Coding! 🐍📚