Beginner Guide · Python Fundamentals
What Are the Basics of Python Programming You Must Know
Quick summary — Python basics you must know
Every Python beginner needs six core concepts: variables and data types, operators, control flow (if/else and loops), functions, data structures (lists, tuples, dictionaries, sets), and file handling. Master these and you can build real programs.
Here's what this guide covers:
- Variables and data types — the building blocks.
- Operators — arithmetic, comparison, logical.
- Control flow — if/else, for, while.
- Functions — reusable blocks of code.
- Data structures — lists, tuples, dicts, sets.
- File handling & errors — working with real data.
- An 8-week roadmap to master it all.
SECTION 01Variables and data types
Variables are containers for storing data. Python is dynamically typed — you don't declare the type; Python infers it.
| Data type | Example | What it stores |
|---|---|---|
| int | age = 25 |
Whole numbers |
| float | price = 99.99 |
Decimal numbers |
| str | name = "Alice" |
Text |
| bool | is_active = True |
True / False |
| NoneType | result = None |
Absence of value |
# Variable assignment
name = "Alice" # str
age = 25 # int
salary = 45000.50 # float
is_employed = True # bool
middle_name = None # NoneType
# Check types
print(type(name)) # <class 'str'>
print(type(age)) # <class 'int'>
# f-strings (modern formatting)
print(f"{name} is {age} years old")
# Type conversion
age_str = "25"
age_int = int(age_str) # str → int
price = float("99.99") # str → float
count = str(100) # int → str
# Important: input() always returns a string
user_age = input("Your age: ")
user_age = int(user_age) # must convert!
# Common error
# "25" + 5 → TypeError
# "25" is str, 5 is int
SECTION 02Operators
Operators let you perform operations on variables and values. Python has several categories.
| Category | Operators | Example |
|---|---|---|
| Arithmetic | + - * / // % ** | 10 // 3 = 3 |
| Comparison | == != < > <= >= | 5 > 3 → True |
| Logical | and, or, not | True and False → False |
| Assignment | = += -= *= /= | x += 5 |
| Membership | in, not in | "a" in "cat" → True |
| Identity | is, is not | None is None → True |
# Arithmetic
a, b = 10, 3
print(a + b) # 13
print(a - b) # 7
print(a * b) # 30
print(a / b) # 3.333...
print(a // b) # 3 (floor division)
print(a % b) # 1 (remainder)
print(a ** b) # 1000 (power)
# Comparison
print(10 == 10) # True
print(10 != 5) # True
print(10 > 5) # True
# Logical operators
is_adult = True
has_id = False
print(is_adult and has_id) # False
print(is_adult or has_id) # True
print(not has_id) # True
# Membership
fruits = ["apple", "banana", "mango"]
print("apple" in fruits) # True
print("orange" in fruits) # False
# Identity
x = None
print(x is None) # True
print(x is not None) # False
/ always returns a float, while
// returns an integer (floor division). This is a common
source of beginner errors.
SECTION 03Control flow
Control flow lets your program make decisions and repeat actions. Python has three main constructs.
# if / elif / else
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(f"Grade: {grade}") # Grade: B
# Ternary (one-line if)
status = "Pass" if score >= 40 else "Fail"
# for loop — iterate over a sequence
fruits = ["apple", "banana", "mango"]
for fruit in fruits:
print(fruit)
# range() — iterate over numbers
for i in range(1, 6):
print(i) # 1 2 3 4 5
# while loop — repeat until condition is False
count = 0
while count < 3:
print(f"Count: {count}")
count += 1
# break and continue
for i in range(10):
if i == 5:
break # exit loop
if i % 2 == 0:
continue # skip this iteration
print(i) # 1 3
IndentationError — a common beginner mistake.
SECTION 04Functions
Functions are reusable blocks of code. They help you avoid repetition and organise your program.
# Define a function
def greet(name):
return f"Hello, {name}!"
# Call it
message = greet("Alice")
print(message) # Hello, Alice!
# Function with no return
def say_hi():
print("Hi!")
say_hi() # Hi!
# Default parameters
def greet_default(name="Guest"):
return f"Hello, {name}!"
print(greet_default()) # Hello, Guest!
print(greet_default("Bob")) # Hello, Bob!
# Multiple parameters
def add(a, b):
return a + b
print(add(3, 5)) # 8
print(add(a=3, b=5)) # 8 (keyword args)
# Returning multiple values
def min_max(numbers):
return min(numbers), max(numbers)
low, high = min_max([3, 1, 4, 1, 5])
print(low, high) # 1 5
# *args — variable positional arguments
def total(*args):
return sum(args)
print(total(1, 2, 3, 4)) # 10
# **kwargs — variable keyword arguments
def show(**kwargs):
for k, v in kwargs.items():
print(k, v)
show(name="Alice", age=25)
SECTION 05Data structures
Python has four built-in data structures. Each has different strengths and use cases.
| Structure | Syntax | Ordered? | Mutable? | Use for |
|---|---|---|---|---|
| List | [1, 2, 3] |
Yes | Yes | Ordered collections that change |
| Tuple | (1, 2, 3) |
Yes | No | Fixed data (coordinates, RGB) |
| Dict | {"a": 1} |
Yes (3.7+) | Yes | Key-value lookups |
| Set | {1, 2, 3} |
No | Yes | Unique items, membership |
# Lists — ordered, mutable
fruits = ["apple", "banana", "mango"]
fruits.append("orange")
fruits.remove("banana")
print(fruits[0]) # apple
print(fruits[-1]) # orange
print(len(fruits)) # 3
# List slicing
numbers = [10, 20, 30, 40, 50]
print(numbers[1:3]) # [20, 30]
print(numbers[:2]) # [10, 20]
print(numbers[::2]) # [10, 30, 50]
# Tuples — ordered, immutable
point = (10, 20)
x, y = point # unpacking
# point[0] = 5 # TypeError — can't modify
# Dicts — key-value pairs
user = {
"name": "Alice",
"age": 25,
"city": "Delhi"
}
print(user["name"]) # Alice
print(user.get("email")) # None (safe access)
user["email"] = "alice@x.com" # add
user["age"] = 26 # update
del user["city"] # delete
# Iterate
for key, value in user.items():
print(f"{key}: {value}")
# Sets — unique items, no order
unique = {1, 2, 3, 3, 2, 1}
print(unique) # {1, 2, 3}
a = {1, 2, 3}
b = {3, 4, 5}
print(a & b) # {3} — intersection
print(a | b) # {1,2,3,4,5} — union
SECTION 06File handling & errors
Real programs read and write files, and handle errors gracefully. Here's how.
# Writing to a file
with open("notes.txt", "w") as f:
f.write("First line\n")
f.write("Second line\n")
# Reading a 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())
# Appending
with open("notes.txt", "a") as f:
f.write("Third line\n")
# Always use "with" — it closes the file automatically
# try / except — handle errors gracefully
try:
num = int(input("Enter a number: "))
result = 10 / num
print(f"Result: {result}")
except ValueError:
print("That's not a valid number")
except ZeroDivisionError:
print("Can't divide by zero")
else:
print("No exceptions occurred")
finally:
print("This always runs")
# Raising your own errors
def validate_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
return age
# Custom exceptions
class InvalidInputError(Exception):
pass
with open(...) — it's the
safe way to handle files. It closes the file automatically,
even if an error occurs.
SECTION 07Interview Q&A — Python basics
Q1Is Python easier than other languages?
Yes — Python's syntax is clean and readable, which is why it's recommended as a first language. You can build useful programs in weeks rather than months.
Q2Do I need to know math for Python?
For basic programming, no. For data science or machine learning, you'll need statistics and linear algebra later. Python itself doesn't require advanced math.
Q3What's the difference between a list and a tuple?
Lists are mutable (can change), tuples are immutable (can't change). Use lists for collections that change, tuples for fixed data like coordinates.
Q4Should I learn Python 2 or Python 3?
Python 3, always. Python 2 reached end-of-life in 2020 and is no longer supported. All new code should be Python 3.10+.
Q5How long does it take to learn Python basics?
With 2-3 hours daily, 6-8 weeks is realistic for the basics. You'll be able to write small programs. Real fluency takes 3-6 months of practice.
SECTION 08Test yourself — Python basics quiz
Five questions. No sign-up.
0 / 5Pick an answer to see why it is right or wrong.
SECTION 09Frequently asked questions
What are the core Python basics every beginner must know?
Six concepts: variables and data types, operators, control flow (if/else and loops), functions, data structures (lists, tuples, dicts, sets), and file handling with error handling.
Is Python good for absolute beginners?
Yes. Python's readable syntax makes it one of the easiest languages to learn first. It's widely recommended for beginners in schools, colleges, and self-study.
What should I build after learning the basics?
Start with small projects: a calculator, a to-do list app, a number guessing game, and a simple notes app. These build confidence and create a portfolio.
Do I need to memorize syntax?
No — you need to understand concepts. Even experienced developers look up syntax. Focus on knowing what's possible and how to solve problems.
What's the next step after Python basics?
Depends on your goal. For data: NumPy, Pandas. For web: Flask or Django. For automation: requests, BeautifulSoup. For general mastery: object-oriented programming and error handling.
SECTION 10Related reads
Classroom & online · Noida
Learn Python properly
Our Python Training Course covers all the basics plus NumPy, Pandas, and real projects — with mentor guidance and placement support.
₹15,500 · full programme- Python basics to advanced
- Real projects
- Mock interviews
- Weekday & weekend batches