3 Programming Fundamentals

A progressive guide to Python programming fundamentals, covering code structure, values, expressions, execution, input and output, documentation, and debugging.

Code structure and meaning

Programming expresses a solution as precise instructions that a computer can execute. A program combines data, operations, and control of execution.

determines whether code is written in an acceptable form. concerns what valid code means when it runs. For example, print("Hello") is a valid function call, but print("Hello" is missing a closing parenthesis and cannot execute.

Python source code is organized into tokens such as names, keywords, literals, operators, and delimiters. Python also uses indentation to organize blocks, and names are case-sensitive.

Takeaway: is about structure; is about meaning.

Values, variables, and data types

A value is data that a program can use, while a is a name associated with a value. Assignment uses a single equals sign, as in score = 42. It binds a name to a value; it does not test equality. Equality testing uses ==, as in score == 42.

Common Python data types include:

  • Integer (int): a whole number such as -3 or 25.

  • Floating-point number (float): a number with a fractional part such as 2.5.

  • String (str): text such as "computer".

  • Boolean (bool): either True or False.

  • None: a special value commonly used to represent the absence of a value.

Python names are bound to objects rather than permanently declared storage locations. A name can later be reassigned, including to a value of another type, although clear programs usually give variables consistent and descriptive purposes.

Takeaway: Keep assignment and comparison distinct: = changes a binding, while == tests a relationship.

Constants and expressions

A is a value intended not to change during execution. Python does not enforce constants with a special declaration, so programmers conventionally use uppercase names such as DAYS_PER_WEEK = 7 and PI_APPROXIMATION = 3.14159.

The convention communicates intent but does not prevent reassignment. Constants are especially useful when a value has a meaningful name, appears repeatedly, or might need to be changed in one place.

An produces or computes a value. It may contain literals, variables, operators, or function calls. Common arithmetic operators include addition, subtraction, multiplication, division, floor division, remainder, and exponentiation. Parentheses make grouping explicit, as in result = (hours * rate) + bonus.

Comparisons such as age >= 18 produce Boolean values. Logical operators combine conditions; and produces True only when both component conditions are true.

Takeaway: Name important fixed values, and use expressions to make calculations and decisions.

Statements and control of execution

A is an instruction that performs an action. Assignment, function calls, imports, and control-flow instructions are examples. Some statements contain expressions, such as area = 3.14159 * radius ** 2.

Simple statements generally fit on one logical line. Compound statements such as if, for, and while introduce blocks of indented statements. In an if , indentation shows which instructions belong to each branch. For example, if score >= 60: can be followed by an indented print("Pass") instruction, while an else: branch can contain print("Try again").

Consistent indentation is part of Python's , not merely visual decoration. It determines the structure of the program.

Takeaway: Expressions compute values; statements use those values to perform actions and control execution.

, processing, and

Many programs follow an -processing- pattern:

  1. Receive data.

  2. Process or transform the data.

  3. Produce a result.

received through Python's () function is returned as a string. Convert it explicitly when numeric processing is required. For example, quantity = int(("How many items? ")) converts the response to an integer, while price = float(("Price per item? ")) converts it to a floating-point number.

Conversion can fail when the text does not have the expected form, such as int("three").

is commonly produced with print(). Multiple arguments are separated by spaces by default. An f-string inserts expressions into text, for example, print(f"The temperature in {city} is {temperature} degrees.").

Takeaway: Treat as text until you deliberately convert it, then format for the reader.

Comments and documentation

A comment is text for human readers that Python normally ignores during execution. A comment begins with # and continues to the end of the line. For example, # Calculate the cost after applying the discount. can explain the purpose of a following calculation.

Useful comments explain purpose, assumptions, or non-obvious decisions. They should not merely restate code that is already clear.

A docstring is a string placed at the beginning of a function, class, or module to document that code for programmers and tools. For example, def square(number): may be followed by the docstring """Return the square of number.""" and then return number * number.

A docstring is associated with the documented object, so it is different from a regular # comment.

Takeaway: Document why code exists or how it should be used, especially when the purpose is not obvious.

Execution and debugging

A Python interpreter typically reads source code, tokenizes and parses it, reports structural errors, and then executes valid statements. Statements generally run in order unless control-flow instructions change that order. During execution, variables are bound to values, expressions are evaluated, and functions may create new execution frames.

For example, in the sequence first = 8, second = 4, result = first / second, and print(result), each assignment must occur before the value is used. Referring to a name before it has been assigned can produce a NameError.

Programs may be run interactively one command at a time or as a script such as python program.py.

Different failures require different responses:

  • A means the code violates language grammar before the affected code runs.

  • A runtime error occurs while syntactically valid code is executing, such as division by zero.

  • A allows the program to run but produces the wrong result.

Testing known examples and tracing values step by step help distinguish these cases and locate the cause.

Putting the fundamentals together

A small cost-estimation program can combine constants, variables, , expressions, statements, and . One possible sequence is:

  1. Define TAX_RATE = 0.07.

  2. Read a quantity with int(("Number of notebooks: ")).

  3. Read a unit price with float(("Price of one notebook: ")).

  4. Calculate subtotal = quantity * price_each.

  5. Calculate tax = subtotal * TAX_RATE.

  6. Calculate total = subtotal + tax.

  7. Display the results with formatted strings such as print(f"Total: ${total:.2f}").

The program receives two inputs, converts them to numeric values, calculates intermediate results, and formats the final . Names such as subtotal and tax make the sequence easier to read, test, and modify.

When designing a small program, identify the inputs, decide what values must be calculated, give intermediate results meaningful names, and determine how the final should appear. Then test expected inputs and cases that could cause conversion or calculation problems.

Takeaway: Clear names and explicit intermediate steps make a program easier to understand and debug.