Python Programming
A Comprehensive Beginner's Guide
1. Introduction to Python
Python is a high-level, interpreted, general-purpose programming language. Created by Guido
van Rossum and first released in 1991, Python emphasizes code readability and simplicity,
making it an ideal language for beginners and professionals alike.
Key Features
• Simple and readable syntax — easy to learn and write
• Interpreted language — no compilation needed
• Dynamically typed — variable types are determined at runtime
• Cross-platform — runs on Windows, macOS, and Linux
• Extensive standard library and third-party packages
• Supports multiple programming paradigms: OOP, functional, procedural
Common Use Cases
• Web Development (Django, Flask, FastAPI)
• Data Science and Machine Learning (NumPy, Pandas, TensorFlow)
• Automation and Scripting
• Artificial Intelligence and NLP
• Scientific Computing and Research
2. Setting Up Python
To get started with Python, download the latest version from [Link]. Python 3.x is the
current and actively maintained version.
Verifying Installation
After installation, open a terminal and verify with:
python --version
# Output: Python 3.x.x
Running Python
• Interactive mode: type python in the terminal
• Script mode: save a .py file and run python [Link]
• IDEs: VS Code, PyCharm, Jupyter Notebook
3. Syntax and Variables
Python uses indentation (spaces or tabs) to define code blocks instead of curly braces. This
enforces clean, readable code.
Variables
Variables in Python do not need explicit type declarations. They are created when a value is
assigned.
name = "Alice" # string
age = 25 # integer
height = 5.6 # float
is_student = True # boolean
nothing = None # NoneType
Variable Naming Rules
• Must start with a letter or underscore (_)
• Can contain letters, numbers, and underscores
• Case-sensitive: name and Name are different
• Cannot use Python reserved keywords (e.g., if, for, while)
4. Data Types
Python has several built-in data types used to represent different kinds of values.
Data Type Example Description
int x = 10 Whole numbers
float x = 3.14 Decimal numbers
str x = "hello" Text / string of
characters
bool x = True Boolean: True or False
list x = [1, 2, 3] Ordered, mutable
collection
tuple x = (1, 2, 3) Ordered, immutable
collection
dict x = {"a": 1} Key-value pairs
set x = {1, 2, 3} Unordered, unique
elements
Type Checking & Conversion
type(42) # <class 'int'>
type("hello") # <class 'str'>
int("10") # converts string to int: 10
str(3.14) # converts float to string: '3.14'
float(5) # converts int to float: 5.0
5. Operators
Arithmetic Operators
Operator Symbol Example Result
Addition + 5 + 3 8
Subtraction - 5 - 3 2
Multiplication * 5 * 3 15
Division / 5 / 2 2.5
Floor Division // 5 // 2 2
Modulus % 5 % 2 1
Exponentiation ** 2 ** 3 8
Comparison & Logical Operators
# Comparison
x == y # equal to
x != y # not equal
x > y # greater than
x < y # less than
# Logical
x and y # both must be True
x or y # at least one must be True
not x # negation
6. Control Flow
if / elif / else
age = 18
if age >= 18:
print("Adult")
elif age >= 13:
print("Teenager")
else:
print("Child")
for Loop
Used to iterate over a sequence (list, string, range, etc.).
for i in range(5):
print(i) # prints 0 1 2 3 4
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
while Loop
Executes as long as a condition remains True.
count = 0
while count < 5:
print(count)
count += 1
break, continue, pass
• break — exits the loop immediately
• continue — skips current iteration and moves to next
• pass — does nothing; acts as a placeholder
7. Functions
Functions are reusable blocks of code defined using the def keyword. They help organize and
modularize programs.
def greet(name):
return "Hello, " + name
message = greet("Alice")
print(message) # Hello, Alice
Function Features
• Default parameters: def greet(name="World")
• Keyword arguments: greet(name="Bob")
• *args: variable number of positional arguments
• **kwargs: variable number of keyword arguments
• Lambda functions: short anonymous functions
# Lambda example
square = lambda x: x ** 2
print(square(4)) # 16
8. Lists and Collections
Lists
Lists are ordered, mutable (changeable) collections. They allow duplicate elements.
nums = [1, 2, 3, 4, 5]
[Link](6) # add to end
[Link](0, 0) # insert at index 0
[Link](3) # remove first occurrence of 3
[Link]() # remove and return last element
nums[1:3] # slicing: [2, 4]
len(nums) # number of elements
Tuples
Tuples are like lists but immutable (cannot be changed after creation).
coordinates = (10.5, 20.3)
x, y = coordinates # unpacking
Dictionaries
Dictionaries store data as key-value pairs.
student = {"name": "Alice", "age": 20, "grade": "A"}
student["age"] # access: 20
student["city"] = "NY" # add new key
[Link]() # all keys
[Link]() # all values
[Link]() # all key-value pairs
Sets
Sets are unordered collections with no duplicate elements.
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
a | b # union: {1,2,3,4,5,6}
a & b # intersection: {3,4}
a - b # difference: {1,2}
9. Object-Oriented Programming (OOP)
Python supports OOP — a paradigm that organizes code using classes and objects.
class Animal:
def __init__(self, name, species):
[Link] = name
[Link] = species
def speak(self):
return f"{[Link]} makes a sound"
class Dog(Animal):
def speak(self):
return f"{[Link]} says Woof!"
dog = Dog("Rex", "Canis lupus")
print([Link]()) # Rex says Woof!
OOP Principles
• Encapsulation — bundling data and methods in a class
• Inheritance — a class can inherit from another class
• Polymorphism — same method name, different behaviour
• Abstraction — hiding complex implementation details
10. File Handling
Python makes reading and writing files straightforward using the built-in open() function.
# Writing to a file
with open("[Link]", "w") as f:
[Link]("Hello, Python!")
# Reading from a file
with open("[Link]", "r") as f:
content = [Link]()
print(content)
# Appending
with open("[Link]", "a") as f:
[Link]("\nMore content")
File Modes
Mode Description
"r" Read (default) — file must exist
"w" Write — creates or overwrites file
"a" Append — adds to end of file
"rb" Read in binary mode
"wb" Write in binary mode
11. Error Handling
Python uses try/except blocks to catch and handle exceptions gracefully.
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError as e:
print(f"Value error: {e}")
else:
print("No error occurred")
finally:
print("This always runs")
Common Exceptions
• ValueError — invalid value passed
• TypeError — wrong data type
• IndexError — list index out of range
• KeyError — dictionary key not found
• FileNotFoundError — file doesn't exist
• ZeroDivisionError — division by zero
12. Modules and Libraries
Modules are Python files with reusable code. Python has a rich standard library plus thousands
of third-party packages.
import math
import random
from datetime import datetime
print([Link](16)) # 4.0
print([Link](1, 100)) # random number
print([Link]()) # current date and time
Installing Third-Party Packages
pip install requests
pip install numpy pandas matplotlib
Popular Libraries
Library Purpose
NumPy Numerical computing, arrays
Pandas Data analysis and manipulation
Matplotlib Data visualization / charts
Requests HTTP requests and web APIs
Flask / Django Web development
TensorFlow / PyTorch Machine learning and AI
SQLAlchemy Database ORM
13. Quick Reference
Common Built-in Functions
Function Description Example
print() Display output print("Hi")
input() Read user input name = input("Name: ")
len() Length of object len([1,2,3]) → 3
range() Generate number sequence range(5) → 0..4
type() Get data type type(3.14) → float
int/str/float() Type conversion int("5") → 5
sorted() Return sorted list sorted([3,1,2]) →
[1,2,3]
enumerate() Index + value pairs enumerate(list)
zip() Combine iterables zip(a, b)
map() Apply function to map(fn, list)
iterable
Python Basics Notes | Happy Coding!