05/10/2025, 01:41 Python for Beginners - Complete Guide
🐍 Download as PDF (Print to PDF)
🐍 Python for Beginners
A Complete Guide to Getting Started with Python Programming
📚 Table of Contents
1. What is Python?
2. Getting Started
3. Variables & Data Types
4. Operators
5. Control Flow
6. Functions
7. Data Structures
8. Loops
9. String Manipulation
10. File Handling
11. Error Handling
12. Object-Oriented Programming
13. Modules & Packages
14. Best Practices
[Link] 1/24
05/10/2025, 01:41 Python for Beginners - Complete Guide
1. What is Python?
Python is a high-level, interpreted programming language known for its simplicity
and readability.
Why Learn Python?
Easy to Learn: Simple, English-like syntax
Versatile: Web development, data science, AI, automation, gaming
Popular: One of the most in-demand programming languages
Large Community: Tons of libraries and support
Career Opportunities: High-paying jobs in tech
💡 Fun Fact: Python was named after the British comedy series "Monty
Python's Flying Circus," not the snake!
What Can You Build with Python?
Websites (Django, Flask)
Data Analysis & Visualization
Machine Learning & AI
Automation Scripts
Games
Desktop Applications
2. Getting Started
Installing Python
1. Visit [Link]
2. Download Python 3.x (latest version)
3. Run installer (check "Add Python to PATH")
4. Verify installation: Open terminal/command prompt and type:
[Link] 2/24
05/10/2025, 01:41 Python for Beginners - Complete Guide
python --version
Your First Python Program
# This is a comment
print("Hello, World!")
Output:
Hello, World!
💡 Tip: Use print() to display output. Comments start with # and are
ignored by Python.
[Link] 3/24
05/10/2025, 01:41 Python for Beginners - Complete Guide
3. Variables & Data Types
Variables
Variables store data. In Python, you don't need to declare the type.
# Creating variables
name = "Alice"
age = 25
height = 5.6
is_student = True
# Printing variables
print(name)
print(age)
Output:
Alice
25
Data Types
Type Example Description
int 42 Whole numbers
float 3.14 Decimal numbers
str "Hello" Text (strings)
bool True , False Boolean values
list [1, 2, 3] Ordered collection
tuple (1, 2, 3) Immutable list
[Link] 4/24
05/10/2025, 01:41 Python for Beginners - Complete Guide
dict {"key": "value"} Key-value pairs
Type Checking & Conversion
# Check type
print(type(42)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type("Hello")) # <class 'str'>
# Convert types
x = "123"
y = int(x) # Convert string to int
z = float(y) # Convert int to float
print(y, z) # 123 123.0
Getting User Input
name = input("Enter your name: ")
age = int(input("Enter your age: "))
print(f"Hello {name}, you are {age} years old!")
[Link] 5/24
05/10/2025, 01:41 Python for Beginners - Complete Guide
4. Operators
Arithmetic Operators
Operator Description 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 (remainder) 5 % 2 1
** Exponentiation 5 ** 2 25
Comparison Operators
x = 5
y = 10
print(x == y) # False (equal to)
print(x != y) # True (not equal to)
print(x < y) # True (less than)
print(x > y) # False (greater than)
print(x <= y) # True (less than or equal)
print(x >= y) # False (greater than or equal)
Logical Operators
[Link] 6/24
05/10/2025, 01:41 Python for Beginners - Complete Guide
a = True
b = False
print(a and b) # False (both must be True)
print(a or b) # True (at least one is True)
print(not a) # False (opposite of a)
[Link] 7/24
05/10/2025, 01:41 Python for Beginners - Complete Guide
5. Control Flow
If Statements
age = 18
if age >= 18:
print("You are an adult")
elif age >= 13:
print("You are a teenager")
else:
print("You are a child")
Output:
You are an adult
⚠️ Important: Python uses indentation (4 spaces) to define code blocks. This
is not optional!
Nested If Statements
score = 85
if score >= 60:
print("You passed!")
if score >= 90:
print("Excellent!")
elif score >= 80:
print("Great job!")
else:
print("Good work!")
else:
print("You failed.")
Ternary Operator (Shorthand If-Else)
[Link] 8/24
05/10/2025, 01:41 Python for Beginners - Complete Guide
age = 20
status = "Adult" if age >= 18 else "Minor"
print(status) # Adult
6. Functions
Defining Functions
def greet():
print("Hello!")
# Call the function
greet() # Hello!
Functions with Parameters
def greet(name):
print(f"Hello, {name}!")
greet("Alice") # Hello, Alice!
greet("Bob") # Hello, Bob!
Return Values
def add(a, b):
return a + b
result = add(5, 3)
print(result) # 8
Default Parameters
def greet(name="Guest"):
print(f"Hello, {name}!")
[Link] 9/24
05/10/2025, 01:41 Python for Beginners - Complete Guide
greet() # Hello, Guest!
greet("Alice") # Hello, Alice!
Multiple Return Values
def calculate(a, b):
sum_val = a + b
diff_val = a - b
return sum_val, diff_val
s, d = calculate(10, 5)
print(s, d) # 15 5
[Link] 10/24
05/10/2025, 01:41 Python for Beginners - Complete Guide
7. Data Structures
Lists (Arrays)
# Creating lists
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]
# Accessing elements (index starts at 0)
print(fruits[0]) # apple
print(fruits[-1]) # cherry (last item)
# Modifying lists
[Link]("orange") # Add to end
[Link](1, "mango") # Insert at position
[Link]("banana") # Remove item
popped = [Link]() # Remove and return last
print(len(fruits)) # Get length
# Slicing
print(numbers[1:4]) # [2, 3, 4]
print(numbers[:3]) # [1, 2, 3]
print(numbers[3:]) # [4, 5]
Tuples (Immutable Lists)
coordinates = (10, 20)
rgb = (255, 128, 0)
# Accessing
print(coordinates[0]) # 10
# Tuples cannot be modified
# coordinates[0] = 15 # This would cause an error!
[Link] 11/24
05/10/2025, 01:41 Python for Beginners - Complete Guide
Dictionaries (Key-Value Pairs)
# Creating dictionaries
person = {
"name": "Alice",
"age": 25,
"city": "New York"
}
# Accessing values
print(person["name"]) # Alice
print([Link]("age")) # 25
# Modifying
person["age"] = 26 # Update value
person["job"] = "Engineer" # Add new key-value
# Dictionary methods
print([Link]()) # All keys
print([Link]()) # All values
print([Link]()) # All key-value pairs
# Check if key exists
if "name" in person:
print("Name exists!")
Sets (Unique Elements)
numbers = {1, 2, 3, 4, 5}
[Link](6) # Add element
[Link](3) # Remove element
# Sets automatically remove duplicates
nums = {1, 2, 2, 3, 3, 3}
print(nums) # {1, 2, 3}
[Link] 12/24
05/10/2025, 01:41 Python for Beginners - Complete Guide
8. Loops
For Loops
# Loop through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Loop with range
for i in range(5): # 0 to 4
print(i)
for i in range(1, 6): # 1 to 5
print(i)
for i in range(0, 10, 2): # 0, 2, 4, 6, 8
print(i)
# Loop through dictionary
person = {"name": "Alice", "age": 25}
for key, value in [Link]():
print(f"{key}: {value}")
While Loops
count = 0
while count < 5:
print(count)
count += 1
# Infinite loop with break
while True:
answer = input("Type 'exit' to quit: ")
if answer == "exit":
[Link] 13/24
05/10/2025, 01:41 Python for Beginners - Complete Guide
break
print("You typed:", answer)
Loop Control Statements
# break - exit loop
for i in range(10):
if i == 5:
break
print(i) # Prints 0 to 4
# continue - skip to next iteration
for i in range(5):
if i == 2:
continue
print(i) # Prints 0, 1, 3, 4
# pass - do nothing (placeholder)
for i in range(3):
pass # TODO: Add code later
List Comprehensions (Advanced)
# Create a new list from existing list
numbers = [1, 2, 3, 4, 5]
squared = [x**2 for x in numbers]
print(squared) # [1, 4, 9, 16, 25]
# With condition
evens = [x for x in numbers if x % 2 == 0]
print(evens) # [2, 4]
[Link] 14/24
05/10/2025, 01:41 Python for Beginners - Complete Guide
9. String Manipulation
String Basics
text = "Hello, World!"
# String methods
print([Link]()) # HELLO, WORLD!
print([Link]()) # hello, world!
print([Link]()) # Hello, World!
print([Link]("Hello", "Hi")) # Hi, World!
print([Link](",")) # ['Hello', ' World!']
print(len(text)) # 13
# Check substring
print("Hello" in text) # True
print("Python" in text) # False
String Formatting
name = "Alice"
age = 25
# Method 1: f-strings (Python 3.6+) - RECOMMENDED
print(f"My name is {name} and I am {age} years old")
# Method 2: format()
print("My name is {} and I am {} years old".format(name, age)
# Method 3: % operator (old style)
print("My name is %s and I am %d years old" % (name, age))
String Slicing
[Link] 15/24
05/10/2025, 01:41 Python for Beginners - Complete Guide
text = "Python"
print(text[0]) # P
print(text[-1]) # n
print(text[0:3]) # Pyt
print(text[2:]) # thon
print(text[:4]) # Pyth
print(text[::-1]) # nohtyP (reverse)
Multiline Strings
message = """
This is a
multiline
string
"""
print(message)
[Link] 16/24
05/10/2025, 01:41 Python for Beginners - Complete Guide
10. File Handling
Reading Files
# 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 into list
with open("[Link]", "r") as file:
lines = [Link]()
print(lines)
Writing Files
# Write (overwrite existing)
with open("[Link]", "w") as file:
[Link]("Hello, World!\n")
[Link]("Python is awesome!")
# Append to file
with open("[Link]", "a") as file:
[Link]("\nNew line appended")
💡 Tip: Using with open() automatically closes the file. Always use this
instead of [Link]() and [Link]() .
File Modes
[Link] 17/24
05/10/2025, 01:41 Python for Beginners - Complete Guide
Mode Description
"r" Read (default)
"w" Write (overwrites)
"a" Append
"r+" Read and write
"b" Binary mode (e.g., "rb")
[Link] 18/24
05/10/2025, 01:41 Python for Beginners - Complete Guide
11. Error Handling
Try-Except Blocks
try:
number = int(input("Enter a number: "))
result = 10 / number
print(f"Result: {result}")
except ValueError:
print("That's not a valid number!")
except ZeroDivisionError:
print("Cannot divide by zero!")
except Exception as e:
print(f"An error occurred: {e}")
finally:
print("This always executes")
Raising Exceptions
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero!")
return a / b
try:
result = divide(10, 0)
except ValueError as e:
print(e)
12. Object-Oriented Programming (OOP)
Classes and Objects
class Dog:
# Constructor
[Link] 19/24
05/10/2025, 01:41 Python for Beginners - Complete Guide
def __init__(self, name, age):
[Link] = name
[Link] = age
# Method
def bark(self):
print(f"{[Link]} says Woof!")
def get_info(self):
return f"{[Link]} is {[Link]} years old"
# Create objects
dog1 = Dog("Buddy", 3)
dog2 = Dog("Max", 5)
# Use methods
[Link]() # Buddy says Woof!
print(dog1.get_info()) # Buddy is 3 years old
Inheritance
class Animal:
def __init__(self, name):
[Link] = name
def speak(self):
pass
class Cat(Animal):
def speak(self):
return f"{[Link]} says Meow!"
class Dog(Animal):
def speak(self):
return f"{[Link]} says Woof!"
cat = Cat("Whiskers")
dog = Dog("Buddy")
[Link] 20/24
05/10/2025, 01:41 Python for Beginners - Complete Guide
print([Link]()) # Whiskers says Meow!
print([Link]()) # Buddy says Woof!
[Link] 21/24
05/10/2025, 01:41 Python for Beginners - Complete Guide
13. Modules & Packages
Importing Modules
# Import entire module
import math
print([Link]) # 3.141592...
print([Link](16)) # 4.0
# Import specific functions
from math import pi, sqrt
print(pi)
print(sqrt(16))
# Import with alias
import math as m
print([Link])
# Import all (not recommended)
from math import *
Common Built-in Modules
Module Purpose Example
math Math functions [Link](16)
random Random numbers [Link](1, 10)
datetime Date & time [Link]()
os Operating system [Link]()
json JSON data [Link](data)
Common Module Examples
[Link] 22/24
05/10/2025, 01:41 Python for Beginners - Complete Guide
# Random module
import random
print([Link](1, 100)) # Random number 1-100
print([Link]([1, 2, 3])) # Random item from list
print([Link]()) # Random float 0-1
# Datetime module
from datetime import datetime
now = [Link]()
print(now)
print([Link]("%Y-%m-%d %H:%M:%S"))
# OS module
import os
print([Link]()) # Current directory
print([Link]()) # List files
Creating Your Own Module
# File: [Link]
def greet(name):
return f"Hello, {name}!"
def add(a, b):
return a + b
# File: [Link]
import mymodule
print([Link]("Alice"))
print([Link](5, 3))
[Link] 23/24
05/10/2025, 01:41 Python for Beginners - Complete Guide
14. Best Practices
✅ Do:
Use descriptive variable names: user_age not ua
Follow PEP 8 style guide (use 4 spaces for indentation)
Use comments to explain complex code
Keep functions small and focused
Use meaningful function names that describe what they do
Handle errors with try-except blocks
Use f-strings for string formatting
Write docstrings for functions and classes
❌ Don't:
Use single-letter variables (except in loops)
Mix tabs and spaces
Write functions longer than 50 lines
Use global variables unnecessarily
Ignore errors silently
Use import *
Naming Conventions
Type Convention Example
[Link] 24/24