Programming • Updated 8 November 2026

Python Basics for Beginners: Variables, Loops, Functions, Lists, Files and a First Project

Learn Python from scratch: installing Python, variables and data types, conditions, loops, functions, lists and dictionaries, file handling, errors and a small expense-tracker project with runnable code.

Pythonbeginnersprogramming basicsloopsfunctions
⏱ 5 min read

Python is one of the easiest languages to learn and one of the most useful, powering data analysis, automation, web apps and AI. This guide takes you from installation to a small working project, with code you can run as you read. Type the examples yourself instead of pasting, because that is how syntax sticks.

Install and run Python

  1. Download Python 3 from the official python.org website and tick "Add Python to PATH" during installation on Windows.
  2. Open a terminal and type python --version (or python3 --version) to confirm.
  3. Install an editor such as VS Code, or start with the interactive prompt by typing python.
  4. Save code in a file ending in .py and run it with python filename.py.

Variables and data types

name = "Asha"
age = 24
height = 5.4
is_student = True
print("Hello,", name)
print(type(age))

Python figures out types automatically: str for text, int for whole numbers, float for decimals and bool for True or False. Use input() to read from the user, which always returns text, so convert with int() or float().

Operators and f-strings

price = 250
qty = 3
total = price * qty
gst = total * 0.18
print(f"Total with GST: {total + gst}")

Arithmetic uses + - * / and also // for floor division, % for remainder and ** for powers. An f-string lets you embed variables inside text.

Conditions

marks = 72
if marks >= 90:
    grade = "A"
elif marks >= 60:
    grade = "B"
else:
    grade = "C"
print(grade)

Indentation (four spaces) defines the code block. Combine conditions with and, or and not.

Loops

for i in range(1, 6):
    print(i * i)

count = 3
while count > 0:
    print("Countdown", count)
    count -= 1

Use for when you know the number of repetitions or are iterating over a collection, and while when you repeat until a condition changes. break exits a loop early and continue skips to the next round.

Lists, tuples and dictionaries

fruits = ["mango", "banana", "guava"]
fruits.append("apple")
print(fruits[0], len(fruits))

prices = {"mango": 120, "banana": 40}
prices["guava"] = 60
for item, cost in prices.items():
    print(item, cost)

Lists are ordered and changeable, tuples are ordered and fixed, sets hold unique values and dictionaries map keys to values. Slicing, such as fruits[1:3], extracts parts of a list.

Functions

def emi(principal, annual_rate, years):
    r = annual_rate / 12 / 100
    n = years * 12
    return principal * r * (1 + r) ** n / ((1 + r) ** n - 1)

print(round(emi(2500000, 8.5, 20)))

Functions package reusable logic. This example computes a loan EMI. You can check results against our EMI calculator. Give functions clear names and keep each one focused on a single task.

Files and errors

try:
    with open("notes.txt") as f:
        text = f.read()
    print(len(text.split()))
except FileNotFoundError:
    print("File not found")

The with statement closes the file automatically. Wrap risky operations in try/except, and catch specific errors rather than everything.

Mini project: expense tracker

expenses = []
while True:
    item = input("Item (or q to quit): ")
    if item == "q":
        break
    amount = float(input("Amount: "))
    expenses.append((item, amount))

total = sum(a for _, a in expenses)
print("Total spent:", total)
for item, amount in sorted(expenses, key=lambda x: -x[1]):
    print(f"{item:15} {amount:8.2f}")

Extend it by saving to a CSV file, adding categories and charting the totals with the techniques in Python data visualization. Pair it with a monthly plan from our budgeting guide.

Where to go next

  • Practise daily on small problems for 30 minutes.
  • Learn modules: random, datetime, csv, json.
  • Pick a direction: web (Flask), data (web scraping and charts) or databases (SQL).
  • Use virtual environments: python -m venv venv.
  • Read other people's code on GitHub and write tests for your own.

Common beginner errors

  • IndentationError: mix of tabs and spaces or wrong levels.
  • NameError: using a variable before defining it or a typo.
  • TypeError: adding a string to a number without converting.
  • Modifying a list while looping over it.
  • Forgetting that indexing starts at 0.

When stuck, read the last line of the error message first, since it names the problem. For career direction, see freelance developer tips.

A four-week study plan

Week one: install Python, learn variables, input and output, and write ten tiny programs such as a tip splitter or a temperature converter. Week two: practise conditions and loops with number games, multiplication tables and pattern printing. Week three: work with lists, dictionaries and functions, and rewrite your earlier programs to use functions. Week four: build the expense tracker, add file saving, and publish it on GitHub with a short README. Spend about an hour a day, type every example yourself, and keep a notebook of errors and what fixed them. After the month, choose one direction instead of trying everything at once.

Frequently asked questions

Is Python good for beginners?

Yes, its simple syntax and wide use make it a popular first language.

How long does it take to learn Python basics?

Most beginners grasp the basics in four to eight weeks with regular practice.

Which editor should I use?

VS Code, PyCharm Community or even IDLE are fine to start.

Do I need maths for Python?

Basic arithmetic is enough to start, and more maths helps in data science.

What is the difference between a list and a tuple?

Lists can be changed after creation, tuples cannot.

Python 2 or 3?

Use Python 3, since Python 2 is no longer supported.

Last reviewed 8 November 2026. Rates, limits and rules change, so confirm figures with the official source before you act.

Keep reading

Information on AMTools is for general guidance and is not professional financial, tax, legal or medical advice. Rules, rates and limits change, so check the latest official source before acting.