Python is the most popular first programming language, and for good reason: it reads almost like English, and the same skills lead to web development, data analytics, automation and AI. This guide takes you from your first variable to classes, decorators, logging and clean code, with short examples you can type and run. Work through it in order, or jump to the topic you need.
Contents
- 1. Variables, lists, loops and conditions
- 2. String methods and f-strings
- 3. List comprehensions
- 4. Dictionaries
- 5. Sets and tuples
- 6. Functions: arguments, return values and scope
- 7. Modules, packages and import
- 8. Virtual environments
- 9. Exception handling
- 10. Logging instead of print()
- 11. Object-oriented Python: classes and objects
- 12. Inheritance and polymorphism
- 13. Decorators
- 14. Dates and times with datetime
- 15. Reading and writing CSV files
- 16. Decimal: a price calculator exercise
- 17. Your first automation script
- 18. Clean code habits
- 19. How to practise every day
1. Variables, lists, loops and conditions
These basics come up in every Python course and every junior developer interview.
- Variables and types: a variable is a name that holds a value, and Python works out the type automatically. The first types you will use are
int(whole numbers),float(decimals),str(text) andbool(True or False). - Lists: hold several values in order. Add an item with
append(), read one by its position, and loop over all of them. - Loops: a
forloop repeats code for each item; awhileloop repeats until a condition is false. Most beginner bugs are loops that never end, so test with a short list first. - Conditions:
ifruns code only when a condition is true; addelifandelsefor other cases.
marks = [72, 45, 88, 51, 39]
passed = 0
for m in marks:
if m > 50:
passed += 1
print("Passed:", passed)
print("Average:", sum(marks) / len(marks))This ten-line program uses a variable, a list, a loop and a condition, which is a good first exercise to type out and change.
2. String methods and f-strings
Names, emails, file paths, form input and CSV rows are all text, and Python strings have built-in methods for the common jobs.
- Cleaning:
strip()removes spaces and newlines from both ends (always use it on user input),lower()andupper()change case,title()capitalises names andreplace(old, new)swaps text. - Splitting and joining:
"python,java,sql".split(",")gives a list of three items, and", ".join(items)does the reverse. - Searching:
"sql" in text,name.endswith(".csv"),find()(returns -1 if missing) andcount(). - Checking:
isdigit(),isalpha()andisalnum(). A quick phone check:phone.isdigit() and len(phone) == 10.
Build text with f-strings: f"{name} scored {score:.1f} marks", where :.1f means one decimal place. Remember that strings never change: every method returns a new string, so write name = name.strip(), not just name.strip().
3. List comprehensions
A list comprehension builds a new list from an existing one in a single line: new_list = [expression for item in old_list if condition].
- Squares:
[n * n for n in numbers] - Only even numbers:
[n for n in numbers if n % 2 == 0] - Upper-case names:
[name.upper() for name in names]
If the logic needs several steps, a normal loop is easier to read. Clear code matters more than a short line.
4. Dictionaries
A dictionary stores key-value pairs, such as a student’s name and score. Looking a value up by key is faster and clearer than searching a list.
scores = {"Asha": 82, "Ravi": 74}
scores["Meena"] = 90 # add or change
print(scores["Asha"]) # 82
for name, score in scores.items():
print(name, score)Use dictionaries to count things, map codes to names, or hold one record with several fields, such as an order with its date, customer and amount. Use scores.get("Kiran", 0) to supply a default when a key might be missing.
5. Sets and tuples
Tuples: fixed groups of values
A tuple is like a list that cannot change: point = (12.97, 77.59), then lat, lon = point unpacks it. Use tuples for values that belong together, such as coordinates or a function returning two results (return total, average). Because they cannot change, tuples can be dictionary keys: distances[("BTM", "Koramangala")] = 4.
Sets: unique values and fast membership checks
A set keeps only unique items: set(list_with_duplicates) removes duplicates, and if email in seen: is much faster on a set than on a long list. Sets also support useful operations:
a | b: union, everything in either set.a & b: intersection, for example students enrolled in both Python and SQL.a - b: difference, for example enquiries not yet called back.
Quick comparison
- List: ordered, changeable, duplicates allowed.
- Tuple: ordered, unchangeable, duplicates allowed.
- Set: unordered, changeable, no duplicates.
- Dictionary: key-value pairs with unique keys.
Watch out: {} creates an empty dictionary, not a set (use set()), and a one-item tuple needs a comma: (5,).
6. Functions: arguments, return values and scope
Once scripts grow past a few dozen lines, you start copying code. Functions let you name a piece of logic, test it once and reuse it everywhere.
def price_with_tax(amount, rate=0.18):
return amount * (1 + rate)
price_with_tax(100) # uses the default rate
price_with_tax(amount=100, rate=0.05) # keyword arguments- return vs print: print only shows text; return hands the value back so the program can use, store or test it. Return values from functions and print at the top level.
- Mutable defaults: never write
def add(item, items=[]); the same list is shared between calls. UseNoneand create the list inside the function. - Scope: a variable created inside a function exists only there. Pass values in as arguments rather than reading globals.
A good function does one job, says what it does in its name, takes inputs as parameters, returns a result and is short enough to read without scrolling.
7. Modules, packages and import
Any .py file is a module. If pricing.py contains add_tax(), another file can use import pricing then pricing.add_tax(100), or from pricing import add_tax. Avoid from pricing import *, which hides where names come from. A package is a folder of modules, imported as from shop.pricing import add_tax; Django apps are packages, which is why you see from .models import Course.
Python searches the folder of the script you ran, then installed libraries. Two common mistakes follow: naming your file after a library (a random.py or pandas.py in your project hides the real one), and running a file from the wrong folder. Put demo code under if __name__ == "__main__": so it runs only when the file is executed directly, and fix circular imports by moving shared code into a third module.
8. Virtual environments
A virtual environment is a separate folder holding the packages one project needs, so upgrading a library for one project does not break another.
- Create it:
python -m venv venv - Activate on Windows:
venv\Scripts\activate; on Linux or macOS:source venv/bin/activate - Install packages while it is active, then save them:
pip freeze > requirements.txt
Do not commit the venv folder to Git. Add it to .gitignore and share requirements.txt so others can recreate the same setup.
9. Exception handling
Programs meet missing files, wrong input and lost connections. Exception handling lets your program respond clearly instead of crashing.
while True:
try:
age = int(input("Age: "))
except ValueError:
print("Please enter a whole number.")
else:
break- Catch specific errors such as
ValueErrororFileNotFoundError; avoid a bareexceptthat hides every problem. elseruns only when no error happened;finallyalways runs, which is useful for closing files or connections.- Use
raise ValueError("Age cannot be negative")when input breaks a rule, with a clear message for whoever calls your function.
10. Logging instead of print()
print() works until a program runs on a server at night and fails. The built-in logging module records what happened, when and how serious it was.
import logging
logging.basicConfig(level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s")
logger = logging.getLogger(__name__)
logger.info("Import started")
logger.warning("Row 42 has no email")The five levels are DEBUG, INFO, WARNING, ERROR and CRITICAL; use DEBUG while developing and INFO or WARNING in production. Inside an except block, logger.exception("Failed to process row %s", row_id) records the full traceback. Add filename="app.log" to write to a file. Pass values as arguments rather than building strings, and never log passwords, tokens or personal data.
11. Object-oriented Python: classes and objects
Object-oriented programming organises code around objects that hold data and actions. A class is a blueprint, such as Student; an object is one instance, such as a student named Asha.
- Attributes: the data an object stores, such as name and marks.
- Methods: functions that belong to the object, such as
calculate_average(). __init__: runs when a new object is created and sets its starting data.
Practice: write a BankAccount class with a balance, a deposit() method and a withdraw() method that refuses to go below zero, then create two accounts and test each one.
12. Inheritance and polymorphism
Inheritance lets a new class take the attributes and methods of an existing one:
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
class SavingsAccount(Account):
def __init__(self, owner, balance=0, rate=0.04):
super().__init__(owner, balance)
self.rate = rate
def add_interest(self):
self.balance += self.balance * self.rateSavingsAccount gets deposit() for free and adds its own method. Forgetting super().__init__() is a common bug: the child object then has no owner or balance.
Polymorphism means different classes respond to the same method call in their own way. If Circle and Square both define area(), you can loop over a mixed list and call shape.area() without checking types; Python calls this duck typing. You will see both ideas everywhere in Django: models inherit from models.Model, class-based views from ListView and CreateView, and custom exceptions from Exception. Keep inheritance shallow; two levels are usually enough.
13. Decorators
A decorator is a function that takes another function and returns an improved version. The @ symbol is shorthand for that step, and you will meet it constantly in Django (@login_required) and Flask (@app.route).
import functools, time
def timed(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
print(f"{func.__name__} took {time.perf_counter() - start:.4f}s")
return result
return wrapper
@timed
def build_report():
return sum(range(1_000_000))@timed is the same as writing build_report = timed(build_report). The wrapper accepts *args, **kwargs so it works with any function, and functools.wraps keeps the original name and documentation. To pass options such as a number of retries, add one more layer: a function that returns the decorator. The standard library’s @functools.lru_cache is a useful decorator for caching results.
14. Dates and times with datetime
Treating dates as plain text causes bugs, such as sorting “10/2” before “9/2”. The datetime module handles them properly.
from datetime import date, datetime, timedelta
today = date.today()
print(today.strftime("%d %b %Y")) # e.g. 20 Nov 2026
start = datetime.strptime("19-11-2026", "%d-%m-%Y")
due = today + timedelta(days=30)
days_left = (due - today).daysThe format in strptime() must match the text exactly. Indian data usually uses day-month-year while many tools default to month-day-year, so always check. For apps used across regions, store times in UTC and convert for display with zoneinfo.ZoneInfo("Asia/Kolkata"). In pandas, convert a column once with pd.to_datetime(df["order_date"], dayfirst=True).
15. Reading and writing CSV files
CSV files are the most common way to share data between tools, from billing exports to surveys. The built-in csv module handles them in a few lines:
import csv
with open("sales.csv", newline="") as f:
reader = csv.DictReader(f)
total = sum(float(row["amount"]) for row in reader)
with open("summary.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["metric", "value"])
writer.writerow(["total_sales", total])Use a with block so files close even if an error happens. Two checks: compare the number of rows you read with the source file, and convert text to numbers before adding, because CSV values are always read as text. For larger files, pandas is faster to work with.
16. Decimal: a price calculator exercise
Floats cannot represent many decimal values exactly, which matters for money. Python’s Decimal type lets you represent prices directly and choose a rounding rule.
from decimal import Decimal, ROUND_HALF_UP
unit_price = Decimal("19.95") # build from text, not from a float
quantity = 3
total = (unit_price * quantity).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
assert total == Decimal("59.85")Decide deliberately where rounding happens. With two line amounts of 0.005 each, rounding each line gives 0.02 but rounding the total gives 0.01. Record your policy and use it everywhere. Then extend the exercise: reject text such as “abc”, negative or fractional quantities and “NaN”, write a test for each case, and build a simple form that shows errors beside the field. This is a software-design exercise, not tax or accounting advice.
17. Your first automation script
Automation is one of the quickest ways to see Python save real time. Good first tasks include renaming or sorting files in a folder, combining several CSV or Excel files into one, checking a list of links for errors, and creating a daily summary from a data file.
- Do the task by hand once and write down each step.
- Turn each step into a few lines of Python.
- Test on a copy of the files, never the originals.
- Log what the script did (see section 10).
The built-in os and pathlib modules handle files and folders, and pandas handles spreadsheets. These cover most beginner automation.
18. Clean code habits
Clean code is code another developer can read and change without pain, which matters far more than clever tricks.
- Names that explain themselves:
monthly_revenue, notx; functions named for their action, such ascalculate_discount. - Small functions: if a block needs a comment to explain it, it may deserve its own function.
- No repetition: when you copy a block a third time, move it into a function.
- Tools: use a formatter such as Black, a linter such as flake8, and one test for each important function.
19. How to practise every day
Most people who stop learning Python do not lack talent; they read for a week and then go months without coding. A small daily habit beats a long weekend session. Try this 30-minute routine:
- 5 minutes: review yesterday’s code and fix one line you are unsure about.
- 15 minutes: one small task, such as reading a CSV file or counting words in a text.
- 10 minutes: write one or two sentences about what you learned, in your notes or a Git commit message.
Projects that fit the habit: a to-do list that saves to a file, a script that renames files, a calculator that reads user input, and a program that totals a sales CSV by month. Keep each in its own folder in Git; interviewers like to see that you finish things and can explain them. When you are ready for bigger work, see 5 Python full stack project ideas for freshers and your first Django CRUD project.
Learn Python with ScholarLogic
Python fundamentals open the Python and Python Full Stack courses in Bangalore at ScholarLogic, BTM Layout, with daily exercises and trainer code reviews before moving on to Django, APIs and deployment. Book a free demo class and a counsellor will share the fee and the next batch dates. To book, call 78923 93639.

Python Full Stack with Django: A Beginner’s Guide to Web Apps, REST APIs and Deployment - ScholarLogic
[…] you are new to the language itself, start with our Python for Beginners guide […]
Machine Learning for Beginners: A Complete Data Science Guide from pandas to Model Monitoring - ScholarLogic
[…] will need basic Python first; our Python for Beginners guide covers it. For the statistics behind the models, see our statistics guide for data […]
How to Choose an IT Course in Bangalore: A Complete Checklist for Freshers - ScholarLogic
[…] you feel later: practise daily, build small projects and ask questions early. Our Core Java and Python guides show what the first stage of each looks […]