PYTHON NOTES
1. Introduction to Python
• Developed by: Guido van Rossum (1991)
• Type: High-level, interpreted, object-oriented language
• File extension: .py
• Execution:
• python filename.py
Features
• Simple & easy to learn
• Open-source & free
• Platform independent
• Object-oriented
• Huge library support
• Dynamic typing (no need to declare variable type)
2. Basic Syntax
print("Hello, World!")
a = 10
b = 20
print(a + b)
• Indentation: Defines code blocks (no braces {})
• Comments:
• # Single line
• '''Multi-line comment'''
3. Data Types
Type Example Description
int a=5 Integer numbers
float b = 3.14 Decimal numbers
str s = "Hello" String
bool flag = True Boolean
list [1,2,3] Ordered, mutable
tuple (1,2,3) Ordered, immutable
set {1,2,3} Unordered, unique
dict {'a':1,'b':2} Key-value pairs
complex 3+4j Complex numbers
Check type:
type(a)
4. Operators
• Arithmetic: + - * / % // **
• Comparison: == != > < >= <=
• Logical: and or not
• Assignment: = += -= *=
• Membership: in, not in
• Identity: is, is not
5. Control Statements
If-Else
x = 10
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")
Loops
for i in range(5):
print(i)
while i < 5:
print(i)
i += 1
Jump Statements
break, continue, pass
6. Functions
def add(a, b):
return a + b
print(add(2, 3))
• Default argument: def greet(name="User"):
• Lambda function:
• f = lambda x: x * x
• print(f(5))
7. Data Structures
List
nums = [1, 2, 3]
nums.append(4)
nums.remove(2)
nums.sort()
print(nums[0])
Tuple
t = (1, 2, 3)
print(t[1])
Set
s = {1, 2, 3, 2}
s.add(4)
print(s)
Dictionary
d = {'name': 'Alice', 'age': 25}
print(d['name'])
d['age'] = 30
8. Strings
s = "Python"
print(s.lower())
print(s.upper())
print(s[0:3])
print(len(s))
print(s.replace("P", "J"))
9. File Handling
f = open("file.txt", "w")
f.write("Hello Python")
f.close()
f = open("file.txt", "r")
print(f.read())
f.close()
10. Exception Handling
try:
x=5/0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Done")
11. Object-Oriented Programming (OOP)
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def display(self):
print(self.name, self.age)
s1 = Student("John", 20)
s1.display()
Concepts:
• Inheritance
• class A:
• def show(self): print("A")
• class B(A):
• def show(self): print("B")
• Polymorphism
• Encapsulation
• Abstraction
12. Modules & Packages
import math
print(math.sqrt(16))
from math import pi
print(pi)
• Create your own module: Save code as mymodule.py, then import mymodule
13. Iterators & Generators
def gen():
for i in range(3):
yield i
for val in gen():
print(val)
14. Important Built-in Functions
len(), type(), id(), range(), sorted(), max(), min(), sum(), input(), int(), str(), list(), tuple(),
set(), dict()
15. File I/O with with
with open("file.txt", "r") as f:
data = f.read()
16. Libraries to Know
Category Library
Data Analysis pandas, numpy
Visualization matplotlib, seaborn
Web flask, django
Machine Learning scikit-learn
Automation os, sys, shutil
Networking socket, requests
17. Input/Output Example
name = input("Enter name: ")
print("Hello", name)
18. Miscellaneous
• List Comprehension:
• squares = [x*x for x in range(5)]
• Dictionary Comprehension:
• d = {x: x*x for x in range(5)}
• Enumerate:
• for i, val in enumerate(['a','b','c']):
• print(i, val)
19. File Path & OS
import os
print(os.getcwd())
os.mkdir("new_folder")
20. Quick Summary
• Everything is an object.
• Indentation = code block.
• No need for type declaration.
• Functions are first-class citizens.
• Powerful standard library.
• Interpreted, cross-platform, and easy to use.