Introduction
Python is the world’s most popular programming language for good reason: it reads almost like plain English, runs on any platform, and powers everything from simple scripts to AI systems at Google, NASA, and Netflix.
Whether you want to automate repetitive tasks, analyze data, build websites, or dive into machine learning — Python is the perfect starting point. And the best way to start is by getting solid on the fundamentals.
In this guide you will learn every basic Python operation through concise explanations, real code examples, and the exact output you can expect to see when you run them. No fluff, no setup headaches — just Python.
| 💡 What You Will Learn Variables & data types, arithmetic & comparison operators, strings, lists, tuples, dictionaries, sets, conditional statements, loops, functions, file I/O, and basic error handling — all with working code examples. |
Why Python?
- Simple, readable syntax that resembles everyday English
- Massive ecosystem of libraries (NumPy, Pandas, Django, TensorFlow)
- Cross-platform: Windows, macOS, Linux, Raspberry Pi
- Huge community and free resources everywhere
- Top language for data science, AI, web development, and automation
01. Hello World & the print() Function
Every Python journey starts with a single line. The print() function displays output to the screen — it is the simplest and most useful tool for learning and debugging.
# Your very first Python programprint("Hello, World!")# print() can display text, numbers, variables, and expressionsprint("Python is fun!")print(42)print(3.14 * 2)# Print multiple values separated by a spaceprint("Score:", 100, "points")# Use sep and end to customize outputprint("a", "b", "c", sep="-") # a-b-cprint("No newline here", end="!") # stays on same line
Output: Hello, World! Python is fun! 42 6.28 Score: 100 points a-b-c No newline here!
| 📘 Comments in Python Lines starting with # are comments — Python ignores them when running code. Use comments to explain what your code does. Good comments make code readable for others (and for your future self!). |
02.Variables & Data Types
A variable is a named container that stores a value. In Python you do not need to declare a type — Python figures it out automatically. This is called dynamic typing.
# Creating variables — just use the = sign
name = "Alice" # str (text)
age = 28 # int (whole number)
height = 5.6 # float (decimal number)
is_dev = True # bool (True or False)
nothing = None # NoneType (absence of value)
# Check the type of any variable
print(type(name)) # <class 'str'>
print(type(age)) # <class 'int'>
print(type(height)) # <class 'float'>
print(type(is_dev)) # <class 'bool'>
# Multiple assignment on one line
x, y, z = 10, 20, 30
print(x, y, z) # 10 20 30
# Assign same value to multiple variables
a = b = c = 0
Output:<class 'str'><class 'int'><class 'float'><class 'bool'>10 20 30
Python Data Types — Quick Reference
| Type | Keyword | Example | Mutable? |
| Integer | int | x = 42 | No |
| Float | float | x = 3.14 | No |
| String | str | x = “hello” | No |
| Boolean | bool | x = True | No |
| List | list | x = [1, 2, 3] | Yes |
| Tuple | tuple | x = (1, 2, 3) | No |
| Dictionary | dict | x = {“a”: 1} | Yes |
| Set | set | x = {1, 2, 3} | Yes |
| NoneType | None | x = None | No |
| ✅ Type Conversion You can convert between types using int(), float(), str(), bool(). Example: int(“42”) returns 42, str(99) returns “99”. This is called explicit type casting. |
03.Python Operators
Operators perform operations on values and variables. Python has several categories — let us walk through each one with examples.
Arithmetic Operators
a, b = 15, 4
print(a + b) # Addition: 19
print(a - b) # Subtraction: 11
print(a * b) # Multiplication: 60
print(a / b) # Division: 3.75 (always float)
print(a // b) # Floor Division: 3 (integer result)
print(a % b) # Modulus: 3 (remainder)
print(a ** b) # Exponentiation: 50625 (15 to the power of 4)
Output:
19
11
60
3.75
3
3
50625
Comparison Operators
Comparison operators always return True or False (a boolean value).
x, y = 10, 20print(x == y) # Equal to: Falseprint(x != y) # Not equal to: Trueprint(x > y) # Greater than: Falseprint(x < y) # Less than: Trueprint(x >= 10) # Greater than or equal: Trueprint(y <= 20) # Less than or equal: True
Output:FalseTrueFalseTrueTrueTrue
Logical Operators
a, b = True, Falseprint(a and b) # Both must be True: Falseprint(a or b) # At least one True: Trueprint(not a) # Opposite: False# Combine comparisonsage = 25print(age > 18 and age < 65) # Trueprint(age < 10 or age > 20) # True
Output:FalseTrueFalseTrueTrue
Assignment Operators
n = 10n += 5 # same as: n = n + 5 => 15n -= 3 # same as: n = n - 3 => 12n *= 2 # same as: n = n * 2 => 24n //= 4 # same as: n = n // 4 => 6n **= 2 # same as: n = n ** 2 => 36print(n) # 36
Output: 36
04.Strings & String Operations
Strings are sequences of characters enclosed in single or double quotes. Python’s string handling is powerful and expressive.
Creating & Accessing Strings
# Creating strings
s1 = 'Hello'
s2 = "World"
s3 = """Multi
line
string"""
# String indexing (zero-based)
word = "Python"
print(word[0]) # P (first character)
print(word[-1]) # n (last character)
print(word[0:3]) # Pyt (slice: index 0 to 2)
print(word[2:]) # thon (from index 2 to end)
print(word[::-1]) # nohtyP (reversed!)
Output:
P
n
Pyt
thon
nohtyP
Essential String Methods
s = " Hello, Python World! "
print(s.strip()) # Remove whitespace: 'Hello, Python World!'
print(s.lower()) # lowercase
print(s.upper()) # UPPERCASE
print(s.replace('Python', 'Beautiful')) # Replace substring
print(s.find('Python')) # Index where 'Python' starts: 9
print(s.count('l')) # Count occurrences: 3
# Check content
print("123".isdigit()) # True
print("hello".isalpha()) # True
print(" ".isspace()) # True
# Split and Join
words = "apple,banana,cherry".split(",")
print(words) # ['apple', 'banana', 'cherry']
print(" | ".join(words)) # apple | banana | cherry
Output:
Hello, Python World!
hello, python world!
HELLO, PYTHON WORLD!
Hello, Beautiful World!
9
3
True
True
True
['apple', 'banana', 'cherry']
apple | banana | cherry
f-Strings (Formatted String Literals)
f-strings (Python 3.6+) are the modern, readable way to embed variables and expressions inside strings.
name = "Alice"
age = 28
pi = 3.14159
# Embed variables with {}
print(f"My name is {name} and I am {age} years old.")
# Expressions inside {}
print(f"Next year I will be {age + 1}.")
# Format numbers
print(f"Pi to 2 decimal places: {pi:.2f}")
print(f"Large number: {1_000_000:,}")
# Padding and alignment
print(f"|{name:<10}|{age:>5}|") # left / right align
Output:
My name is Alice and I am 28 years old.
Next year I will be 29.
Pi to 2 decimal places: 3.14
Large number: 1,000,000
|Alice | 28|
| ⚠️ String Immutability Strings in Python are immutable — you cannot change a character in place. Instead, string methods always return a new string. So s.upper() does NOT change s itself; it returns a new uppercase version. You need s = s.upper() to update the variable. |
05.Lists — Python’s Most Versatile Data Structure
A list is an ordered, mutable (changeable) collection that can hold items of any type — including other lists. Lists are one of the most frequently used data structures in Python.
# Creating lists
fruits = ['apple', 'banana', 'cherry']
numbers = [10, 20, 30, 40, 50]
mixed = [1, 'hello', 3.14, True]
empty = []
# Accessing elements
print(fruits[0]) # apple
print(fruits[-1]) # cherry
print(numbers[1:4]) # [20, 30, 40]
# Modifying lists
fruits[1] = 'mango' # Change item
fruits.append('kiwi') # Add to end
fruits.insert(1, 'grape') # Insert at index
fruits.remove('apple') # Remove by value
popped = fruits.pop() # Remove & return last item
print(fruits)
print("Popped:", popped)
# Useful list operations
print(len(numbers)) # Length: 5
print(sum(numbers)) # Sum: 150
print(min(numbers)) # Min: 10
print(max(numbers)) # Max: 50
print(sorted([3,1,4,1,5])) # Sort: [1, 1, 3, 4, 5]
Output:
apple
cherry
[20, 30, 40]
['grape', 'mango', 'cherry']
Popped: kiwi
5
150
10
50
[1, 1, 3, 4, 5]
List Comprehensions
List comprehensions are a concise, Pythonic way to create new lists by applying an expression to each item in an existing iterable.
# Traditional approach
squares = []
for i in range(1, 6):
squares.append(i ** 2)
# List comprehension — same result, one line
squares = [i ** 2 for i in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
# With a condition (filter)
evens = [i for i in range(1, 11) if i % 2 == 0]
print(evens) # [2, 4, 6, 8, 10]
# Transform strings
words = ['hello', 'world', 'python']
upper = [w.upper() for w in words]
print(upper) # ['HELLO', 'WORLD', 'PYTHON']
Output:
[1, 4, 9, 16, 25]
[2, 4, 6, 8, 10]
['HELLO', 'WORLD', 'PYTHON']
06.Tuples, Sets & Dictionaries
Tuples — Immutable Sequences
Tuples are like lists but cannot be changed after creation. They are ideal for data that should remain constant, such as coordinates, RGB values, or database records.
# Creating a tuple
coords = (10.5, 20.3)
colors = ('red', 'green', 'blue')
single = (42,) # Note the comma — required for single-item tuple
# Access like a list
print(coords[0]) # 10.5
print(len(colors)) # 3
# Tuple unpacking — very Pythonic!
x, y = coords
print(f"x={x}, y={y}") # x=10.5, y=20.3
# Swap variables elegantly
a, b = 5, 10
a, b = b, a
print(f"a={a}, b={b}") # a=10, b=5
Output:
10.5
3
x=10.5, y=20.3
a=10, b=5
Sets — Unique, Unordered Collections
Sets store unique values with no duplicates and no guaranteed order. They are excellent for membership testing and set operations (union, intersection, difference).
# Creating sets
fruits = {'apple', 'banana', 'cherry', 'apple'} # duplicate removed
print(fruits) # {'apple', 'banana', 'cherry'}
# Set operations
a = {1, 2, 3, 4, 5}
b = {4, 5, 6, 7, 8}
print(a | b) # Union: {1,2,3,4,5,6,7,8}
print(a & b) # Intersection: {4, 5}
print(a - b) # Difference: {1, 2, 3}
print(a ^ b) # Symmetric diff: {1,2,3,6,7,8}
# Membership test — O(1), very fast
print('apple' in fruits) # True
print('grape' in fruits) # False
Output:
{'cherry', 'apple', 'banana'}
{1, 2, 3, 4, 5, 6, 7, 8}
{4, 5}
{1, 2, 3}
{1, 2, 3, 6, 7, 8}
True
False
Dictionaries — Key-Value Stores
Dictionaries store data as key-value pairs. They are one of the most powerful and frequently used structures in Python — great for representing real-world objects and fast lookups.
# Creating a dictionary
person = {
"name": "Alice",
"age": 28,
"city": "Delhi",
"skills": ["Python", "SQL", "Spark"]
}
# Accessing values
print(person["name"]) # Alice
print(person.get("age")) # 28
print(person.get("phone", "N/A")) # N/A (default if missing)
# Adding / updating
person["email"] = "alice@example.com"
person["age"] = 29
# Removing
del person["city"]
removed = person.pop("email")
# Iterating
for key, value in person.items():
print(f" {key}: {value}")
# Useful methods
print(list(person.keys())) # all keys
print(list(person.values())) # all values
print("name" in person) # True
Output:
Alice
28
N/A
name: Alice
age: 29
skills: ['Python', 'SQL', 'Spark']
['name', 'age', 'skills']
['Alice', 29, ['Python', 'SQL', 'Spark']]
True
| 💡 When to Use Each Collection Use a list when order matters and items can repeat. Use a tuple for fixed data that should not change. Use a set when you need unique values or fast membership tests. Use a dict when you need to look up values by a meaningful key. |
07.Conditional Statements (if / elif / else)
Conditional statements let your program make decisions — executing different blocks of code depending on whether a condition is True or False.
# Basic if / elif / else
score = 78
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"Score: {score} => Grade: {grade}")
# Nested conditions
age = 20
has_id = True
if age >= 18:
if has_id:
print("Entry allowed")
else:
print("ID required")
else:
print("Too young")
# Ternary (one-line) conditional
num = 7
result = "odd" if num % 2 != 0 else "even"
print(f"{num} is {result}")
Output:
Score: 78 => Grade: C
Entry allowed
7 is odd
Truthy and Falsy Values
In Python, every value has an implicit boolean meaning. Understanding truthy/falsy values makes your conditionals cleaner.
| Falsy Values | Truthy Values |
| False | True |
| 0, 0.0, 0j (zero numbers) | Any non-zero number |
| “” (empty string) | “hello” (any non-empty string) |
| [] (empty list) | [1, 2] (non-empty list) |
| {} (empty dict/set) | {“a”: 1} (non-empty dict) |
| None | Any object that is not None |
08.Loops — for and while
Loops let you repeat a block of code multiple times. Python has two types: for loops (iterate over a sequence) and while loops (repeat while a condition is true).
for Loops
# Loop over a list
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(f" I like {fruit}")
# range() — generate a sequence of numbers
for i in range(5): # 0, 1, 2, 3, 4
print(i, end=" ")
print() # newline
for i in range(1, 10, 2): # start=1, stop=10, step=2
print(i, end=" ")
print()
# enumerate() — get index AND value
for idx, fruit in enumerate(fruits, start=1):
print(f" {idx}. {fruit}")
# zip() — loop over two lists at once
names = ['Alice', 'Bob', 'Carol']
scores = [92, 87, 95]
for name, score in zip(names, scores):
print(f" {name}: {score}")
Output:
I like apple
I like banana
I like cherry
0 1 2 3 4
1 3 5 7 9
1. apple
2. banana
3. cherry
Alice: 92
Bob: 87
Carol: 95
while Loops
# while loop — runs while condition is True
count = 1
while count <= 5:
print(f' Count: {count}')
count += 1
# Loop control: break and continue
print('--- break example ---')
for n in range(1, 11):
if n == 6:
break # exit loop completely
print(n, end=" ")
print()
print('--- continue example ---')
for n in range(1, 11):
if n % 2 == 0:
continue # skip even numbers
print(n, end=" ")
print()
# for...else — runs if loop completed without break
for i in range(3):
print(f" iteration {i}")
else:
print(" Loop finished cleanly!")
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
--- break example ---
1 2 3 4 5
--- continue example ---
1 3 5 7 9
iteration 0
iteration 1
iteration 2
Loop finished cleanly!
09.Functions
Functions are reusable blocks of code that perform a specific task. They are the foundation of organized, DRY (Don’t Repeat Yourself) Python programming.
# Defining and calling a basic function
def greet(name):
"""Return a personalized greeting."""
return f"Hello, {name}!"
print(greet("Alice")) # Hello, Alice!
print(greet("Bob")) # Hello, Bob!
# Default parameters
def power(base, exponent=2):
return base ** exponent
print(power(3)) # 9 (exponent defaults to 2)
print(power(2, 10)) # 1024
# *args — variable number of positional arguments
def add_all(*numbers):
return sum(numbers)
print(add_all(1, 2, 3, 4, 5)) # 15
# **kwargs — variable number of keyword arguments
def profile(**info):
for key, val in info.items():
print(f" {key}: {val}")
profile(name="Alice", age=28, city="Delhi")
# Lambda — anonymous one-liner function
square = lambda x: x ** 2
add = lambda x, y: x + y
print(square(5)) # 25
print(add(3, 7)) # 10
# Higher-order functions: map, filter, sorted
nums = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, nums))
evens = list(filter(lambda x: x % 2 == 0, nums))
print(doubled) # [2, 4, 6, 8, 10]
print(evens) # [2, 4]
Output:
Hello, Alice!
Hello, Bob!
9
1024
15
name: Alice
age: 28
city: Delhi
25
10
[2, 4, 6, 8, 10]
[2, 4]
| 📘 Docstrings The triple-quoted string right after def greet(…): is a docstring. It documents what the function does. Use help(greet) or greet.__doc__ to read it. Well-documented functions make your code professional and maintainable. |
10.Error Handling with try / except
Errors (exceptions) happen — dividing by zero, opening a missing file, converting invalid input. Instead of crashing, Python lets you catch and handle errors gracefully with try/except blocks.
# Basic try / except
try:
result = 10 / 0
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
# Catching multiple exception types
def safe_divide(a, b):
try:
return a / b
except ZeroDivisionError:
return "Error: division by zero"
except TypeError:
return "Error: invalid types"
print(safe_divide(10, 2)) # 5.0
print(safe_divide(10, 0)) # Error: division by zero
print(safe_divide(10, "x")) # Error: invalid types
# try / except / else / finally
def read_number(s):
try:
n = int(s)
except ValueError as e:
print(f" ValueError: {e}")
return None
else:
print(f" Converted successfully: {n}")
return n
finally:
print(" This always runs.")
read_number("42")
read_number("abc")
Output:
Error: Cannot divide by zero!
5.0
Error: division by zero
Error: invalid types
Converted successfully: 42
This always runs.
ValueError: invalid literal for int() with base 10: 'abc'
This always runs.
| Exception | When It Occurs | Example |
| ValueError | Wrong value for the type | int(“abc”) |
| TypeError | Wrong type for operation | “a” + 1 |
| ZeroDivisionError | Division by zero | 5 / 0 |
| IndexError | Index out of range | [1,2,3][9] |
| KeyError | Key not in dict | {“a”:1}[“b”] |
| FileNotFoundError | File does not exist | open(“x.txt”) |
| AttributeError | Object has no attribute | “hi”.nonexistent() |
| NameError | Variable not defined | print(undefined_var) |
11.File Input & Output
Python makes it easy to read and write files. The built-in open() function gives you access to files on disk. Always use a with statement — it automatically closes the file even if an error occurs.
# ── Writing to a file ───────────────────────────────────
with open("notes.txt", "w") as f:
f.write("Line 1: Python is great\n")
f.write("Line 2: File I/O is easy\n")
f.writelines(["Line 3: Hello\n", "Line 4: World\n"])
print("File written!")
# ── Reading entire file ─────────────────────────────────
with open("notes.txt", "r") as f:
content = f.read()
print(content)
# ── Reading line by line ────────────────────────────────
with open("notes.txt", "r") as f:
for line in f:
print(line.strip())
# ── Reading into a list of lines ────────────────────────
with open("notes.txt", "r") as f:
lines = f.readlines()
print(f"Total lines: {len(lines)}")
# ── Appending to a file ─────────────────────────────────
with open("notes.txt", "a") as f:
f.write("Line 5: Appended!\n")
# ── Safe reading with error handling ────────────────────
try:
with open("missing_file.txt") as f:
data = f.read()
except FileNotFoundError:
print("File not found — please check the path.")
Output:
File written!
Line 1: Python is great
Line 2: File I/O is easy
Line 3: Hello
Line 4: World
Line 1: Python is great
Line 2: File I/O is easy
Line 3: Hello
Line 4: World
Total lines: 4
File not found — please check the path.
| Mode | Meaning | Creates file? | Overwrites? |
| “r” | Read only (default) | No | — |
| “w” | Write (overwrite) | Yes | Yes |
| “a” | Append | Yes | No |
| “x” | Create new (fails if exists) | Yes | — |
| “rb” / “wb” | Read/Write binary | — | — |
Python Basics Cheat Sheet
A quick-reference summary of everything covered in this guide.
| Concept | Syntax / Example | Notes |
| Print output | print(“Hello”) | Use sep= and end= to customize |
| Variable | x = 10 | No type declaration needed |
| f-string | f”Hi {name}” | Embed expressions in strings |
| List | [1, 2, 3] | Ordered, mutable, allows duplicates |
| Tuple | (1, 2, 3) | Ordered, immutable |
| Set | {1, 2, 3} | Unordered, unique values |
| Dictionary | {“k”: “v”} | Key-value pairs, fast lookup |
| if / elif / else | if x > 0: | Use indentation (4 spaces) |
| for loop | for i in range(5): | Iterate over any iterable |
| while loop | while x > 0: | Runs while condition is True |
| break / continue | break / continue | Exit loop / skip iteration |
| Define function | def greet(name): | Always add a docstring |
| Lambda | lambda x: x**2 | Short anonymous function |
| try / except | try: … except ValueError: | Handle specific errors |
| Open file | with open(“f.txt”) as f: | Always use with statement |
| List comprehension | [x**2 for x in range(5)] | Concise list creation |
| Type check | type(x) / isinstance(x, int) | Check variable type |
| String slice | s[1:4] | From index 1 to 3 |
| Unpack tuple | a, b = (1, 2) | Parallel assignment |
| Dict items | for k,v in d.items(): | Iterate key-value pairs |
Conclusion & Next Steps
You have just covered the essential building blocks of Python — variables, data types, operators, strings, lists, tuples, sets, dictionaries, conditionals, loops, functions, error handling, and file I/O. That is a solid foundation that will carry you far.
Python’s power lies in its simplicity combined with an enormous ecosystem. With these fundamentals in hand, you are ready to explore the wider Python world.
Suggested Learning Path
- Object-Oriented Programming (OOP) — classes, objects, inheritance
- Modules & Packages — import system, pip, virtual environments
- Python Standard Library — os, sys, datetime, collections, itertools
- Popular Libraries — NumPy for numbers, Pandas for data, Requests for web APIs
- Data Visualization — Matplotlib, Seaborn
- Web Development — Flask or Django
- Data Science & ML — Scikit-learn, TensorFlow, PyTorch
| ✅ Practice Makes Permanent The fastest way to get good at Python is to build things you care about. Automate a boring task, analyze a dataset from Kaggle, build a simple CLI tool, or scrape a website. Real projects expose you to real problems — and that is where real learning happens. |
Discover more from DataSangyan
Subscribe to get the latest posts sent to your email.