Python: Python Basics

Master the building blocks of Python: comments, data types, variables, and the rules every Python program follows.

Python Comments

A comment is a line your program completely ignores at runtime. Comments exist purely for humans reading the code, whether that is a teammate, an instructor, or yourself six months from now. Python supports two styles: single-line and multi-line.

A single-line comment starts with the # character. Everything after it on that line is ignored. A multi-line comment is just a string literal wrapped in triple quotes that is not assigned to anything; Python evaluates the string and discards it immediately.

Comment Styles

Use comments to explain why your code does something, not just what it does.

  • # This is a single-line comment
  • Triple-quoted strings act as multi-line comments when not assigned
  • Tip: comment your logic, not obvious code like x = 1 # set x to 1
  • Shortcut in VS Code: Ctrl+/ to toggle a comment on the selected line

Single-line and Multi-line Comments

Python

Both styles shown side by side.

Statements and Expressions

An expression is any piece of code that produces a value when evaluated: 3 + 4, "hello".upper(), True are all expressions. A statement is a complete instruction that Python executes, such as assigning a variable, calling a function, or starting a loop. Every statement either contains expressions inside it or stands on its own.

Statement vs Expression

A simple mental model: an expression gives back a value; a statement does something.

  • Expression: 5 * 10 (evaluates to 50)
  • Statement: x = 5 * 10 (assigns 50 to x, produces no value itself)
  • A single line can be both: print(5 * 10) is a statement containing two expressions
  • Python allows multi-line statements using a backslash \ or open brackets

Statements and Expressions

Python

Seeing the difference in practice.

Indentation in Python

Most languages use curly braces to group blocks of code. Python uses indentation instead. This is not a style preference; it is a hard rule enforced by the interpreter. If your indentation is wrong, Python raises an IndentationError and refuses to run.

The standard is 4 spaces per level. Never mix tabs and spaces in the same file. Most editors let you configure the Tab key to insert 4 spaces automatically.

Indentation Rules

Indentation is what defines where one block ends and another begins in Python.

  • Use 4 spaces per indentation level (PEP 8 standard)
  • All lines inside an if / for / while / def / class must be indented equally
  • Mixing tabs and spaces causes a TabError in Python 3
  • VS Code tip: set Tab Size to 4 and enable Insert Spaces in settings

Indentation Controls Flow

Python

The indentation level decides which block each line belongs to.

Case Sensitivity

Python is case-sensitive. That means name, Name, and NAME are three completely different variables. The same applies to function names, class names, and module names. Built-in keywords like True, False, and None must be capitalised exactly as shown; writing true is a NameError.

Case Sensitivity Demo

Python

Three different variable names that look almost identical.

Python Keywords

Keywords are reserved words that Python gives special meaning to. You cannot use them as variable names, function names, or any other identifier. Python 3 has 35 keywords. You can always see the current list at runtime using the keyword module.

Complete Keyword List (Python 3)

These 35 words are off-limits as identifiers. The list rarely changes between minor versions.

  • False, None, True
  • and, as, assert, async, await
  • break, class, continue, def, del
  • elif, else, except, finally, for
  • from, global, if, import, in
  • is, lambda, nonlocal, not, or
  • pass, raise, return, try, while
  • with, yield

Listing Keywords at Runtime

Python

Use the keyword module to print all reserved words.

Naming Identifiers

An identifier is any name you give to a variable, function, class, or module. Python has strict rules about what characters are allowed, and PEP 8 adds further conventions on top to keep code readable and consistent across teams.

Identifier Rules and Best Practices

Follow these rules to avoid SyntaxErrors and write professional-looking code.

  • Must start with a letter (a-z, A-Z) or underscore _
  • Can contain letters, digits (0-9), and underscores
  • Cannot start with a digit: 2name is invalid
  • Cannot be a keyword: for, if, class etc. are off-limits
  • Case-sensitive: total and Total are different identifiers
  • Convention: variables and functions use snake_case (my_function)
  • Convention: classes use PascalCase (MyClass)
  • Convention: constants use UPPER_SNAKE_CASE (MAX_SIZE)
  • Leading underscore _name signals private/internal use by convention

Valid vs Invalid Identifiers

Python

Spot the pattern in what Python accepts and what it rejects.

Fundamental Data Types

Every value in Python has a type. The interpreter uses the type to decide what operations are valid and how to store the value in memory. Python has six fundamental built-in types that you will use constantly.

The Six Core Types

Python assigns types automatically based on the value you write, not a declaration.

  • int: whole numbers with no limit in size (42, -7, 1_000_000)
  • float: decimal numbers stored as IEEE-754 doubles (3.14, -0.5, 2.0)
  • complex: numbers with a real and imaginary part (3+4j)
  • str: text, enclosed in single or double quotes ("hello", 'world')
  • bool: exactly two values, True or False (subclass of int)
  • NoneType: a single value None, meaning "no value" or "nothing here"

All Six Basic Types

Python

One example of each type with type() verification.

Type Checking with type()

The built-in type() function returns the class of any value you pass to it. It is invaluable when debugging: if a variable does not behave as expected, calling type() on it usually reveals the problem immediately. You can also use isinstance() to check whether a value belongs to a particular type or any of its subclasses.

type() and isinstance()

Python

Two ways to inspect the type of a value.

Type Conversion (Implicit and Explicit)

Sometimes Python converts types for you automatically; other times you have to do it yourself. The first kind is called implicit (or coercion) and the second is called explicit (or casting).

Implicit conversion happens when Python promotes a narrower type to a wider type so arithmetic can proceed without loss of information. For example, adding an int to a float gives a float. Explicit conversion uses dedicated functions and can fail at runtime if the value cannot be converted.

Conversion Functions

These four built-in functions cover the most common casting scenarios.

  • int(x): converts x to an integer, truncates decimals (int(3.9) gives 3)
  • float(x): converts x to a float (float("3.14") gives 3.14)
  • str(x): converts x to a string (str(100) gives "100")
  • bool(x): 0, "", None, [], {}, () all convert to False; everything else is True

Implicit and Explicit Conversion

Python

Watch how Python handles types automatically and manually.

Variable Declaration and Initialization

In Python there is no separate declaration step. You create a variable the moment you assign a value to it. The interpreter figures out the type from the value on the right side of the equals sign, and you can reassign the same variable to a completely different type later; Python will not complain.

Variables in Python

Think of a variable as a label stuck onto a value, not a box with a fixed type.

  • No var, let, or int keyword needed before a variable name
  • Assignment is done with a single = (not == which is comparison)
  • The label can be moved to a new value at any time
  • Reassigning to a different type is perfectly valid in Python

Variable Assignment

Python

Python is dynamically typed, so a variable can change type at any time.

Multiple Variable Assignment

Python lets you assign several variables on a single line in two useful ways. You can give the same value to multiple variables at once, or unpack a sequence of values into individual names. This keeps code concise and is often seen in loops and function return values.

Multiple Assignment Patterns

Python

Three common one-liner assignment techniques.

Constants (UPPER_CASE Convention)

Python has no built-in constant keyword. By convention, a name written entirely in uppercase letters signals to other developers: "do not change this value." The interpreter does not enforce the restriction; it is purely a social contract between programmers. For true enforcement you would use a frozen dataclass or a module-level attribute.

Constant Naming Convention

Uppercase names are a promise, not a guarantee.

  • Write constant names in ALL_CAPS with underscores between words
  • Define constants at the top of the module, before any functions
  • Commonly used for configuration values, limits, and mathematical constants
  • Example: PI = 3.14159, MAX_CONNECTIONS = 100, BASE_URL = "https://api.example.com"

Using Constants

Python

Constants are just regular variables named in uppercase by convention.

Literals (Integer, Float, String, Boolean)

A literal is a fixed value written directly in the source code. The text 42 is an integer literal; "hello" is a string literal. Python also supports special notation for binary, octal, and hexadecimal integer literals, and scientific notation for floats.

Literal Formats

Python provides readable alternatives for numbers in different bases.

  • Decimal integer: 100, -7, 1_000_000 (underscores as visual separators)
  • Binary literal: 0b1010 (prefix 0b)
  • Octal literal: 0o17 (prefix 0o)
  • Hex literal: 0xFF (prefix 0x)
  • Float scientific notation: 1.5e3 means 1500.0
  • String literals: "hello", 'world', """multi-line"""
  • Boolean literals: True, False (capital first letter only)

Different Literal Formats

Python

Python can read numbers in binary, octal, hex, and scientific notation.

The del Keyword

The del keyword removes a variable name from the current scope. After deletion, any attempt to access that name raises a NameError. You can also use del to remove individual items from lists or keys from dictionaries. Note that deleting a name does not necessarily free memory immediately; Python's garbage collector decides when the underlying object is actually deallocated.

del in Practice

del removes the binding between a name and its value, not the value itself.

  • del variable_name removes the variable from scope
  • Trying to use the variable after del causes NameError
  • del list[index] removes one item from a list
  • del dict[key] removes a key-value pair from a dictionary
  • Rarely needed for variables, but very common with list slices

del Keyword Examples

Python

Deleting a variable and a list item.

Quiz - Test Your Knowledge

Work through these questions to check how well you have absorbed the Python Basics concepts. Take your time and retry as many times as you need.

Knowledge Check

1. Which symbol is used for a single-line comment in Python?

2. What is the correct indentation size recommended by PEP 8?

3. Which of the following is a valid Python identifier?

4. What does type(3.14) return in Python?

5. Which of the following is an implicit type conversion?

6. What is the value of type(None) in Python?

7. Which keyword is used to delete a variable in Python?

8. What does a, b = 10, 20 demonstrate?