03 — Programming Fundamentals: Python Essentials

A progressive guide to Python programming fundamentals, connecting values, expressions, control flow, functions, input, output, and an integrated grade calculator.

03 — The Core Model of a Program

Programming begins with a simple goal: describe a task as precise instructions that a computer can execute. Python makes this structure visible with relatively little surrounding syntax.

A useful mental model is to separate a program into three questions:

  1. What information does the program receive?

  2. How does it transform or evaluate that information?

  3. What result does it produce?

This pattern, often summarized as →\to processing →\to , connects the ideas in this guide.

Takeaway: Programming fundamentals are the concepts used to represent information, calculate results, choose actions, repeat work, and organize reusable behavior.

Names, Values, and

A is a name associated with a value. uses the single equals sign == to associate the result of the on the right with the name on the left.

For example, score = 92 associates the value 92 with score, and student_name = "Maya" associates text with student_name. Writing score = 97 later changes the value associated with that name.

The single equals sign does not test mathematical equality. It changes an association. A name can later refer to a value of a different type: item = 10 first associates an integer with item, while item = "ten" later associates a string with it.

Good names communicate purpose. Names such as total_cost, maximum_score, and user_age are usually clearer than vague names such as x. Python also supports multiple : width, height = 8, 5 associates 88 with width and 55 with height. The statement left, right = right, left exchanges two existing values.

Takeaway: Use to create or change name–value associations, and choose names that make a program easier to read.

Data Types and Text

A describes the kind of value a program is using and the operations that make sense for it. Basic Python types include:

  • int: whole numbers such as 0, -7, and 42.

  • float: numbers with a fractional part such as 3.14.

  • str: text such as "hello".

  • bool: logical values, True or False.

  • None: the absence of a useful value.

Examples include count = 12, price = 4.99, message = "Ready", is_complete = False, and result = None. The type() reports the type of a value.

Conversion creates a value of another type when the original representation is suitable. For example, age = int("16"), measurement = float("2.5"), and label = str(42). Conversion can fail: int("hello") raises a ValueError because the text does not represent an integer.

A string is a sequence of characters. Strings can be combined with +, repeated with *, and formatted with an f-string. For example, after first = "Ada" and year = 1843, f"{first} worked in {year}." produces text containing both values.

Takeaway: Know what kind of value an operation receives, and convert text before using it as a number.

Expressions and Operators

An is code that produces a value. Literals, variables, operators, and calls can all participate in expressions.

Common arithmetic operators include addition ++, subtraction −-, multiplication ×\times, division ÷\div, floor division, remainder, and exponentiation. In Python, these operations are written with +, -, *, /, //, %, and **. For example, average = (score1 + score2 + score3) / 3, remainder = 7 % 2, and power = 2 ** 3 calculate values.

Parentheses make grouping explicit. Without them, Python follows precedence rules: exponentiation is evaluated before multiplication and division, which are evaluated before addition and subtraction.

Comparison operators produce results. Examples include age >= 18, password == "ok", and temperature != 0. The double equals sign == tests equality, while the single equals sign = performs .

Logical operators combine conditions: is_member and has_ticket, is_weekend or is_holiday, and not is_locked. A call is also an because it produces a value; for example, length = len("computer") assigns the result of the call to length.

Takeaway: Build expressions from values and operations, use parentheses when they clarify intent, and distinguish from comparison.

and Repetition

determines which statements run and in what order. The basic patterns are sequence, selection, and repetition.

In a sequence, statements execute from top to bottom. For example, name = "Ravi", followed by greeting = f"Hello, {name}!", followed by print(greeting), performs those operations in order.

Selection uses if, elif, and else to choose among alternatives. For a score, a chain such as if score >= 90:, elif score >= 80:, elif score >= 70:, and else: assigns different outcomes. The conditions are tested in order, and at most one branch in this chain runs. Python indentation marks each block.

A for repeats a block for each item in an iterable. The endpoint supplied to range() is excluded, so for number in range(1, 4): processes 1, 2, and 3.

A while repeats as long as its condition remains true. In attempts = 0 followed by while attempts < 3:, the body must update attempts, for example with attempts += 1, so the condition can eventually become false. break exits the nearest immediately, while continue skips to the next iteration.

Takeaway: Use conditions to select behavior, loops to repeat behavior, and careful indentation and updates to preserve the intended execution structure.

Functions and Decomposition

A is a named, reusable block of code. Functions reduce repetition and divide a large problem into smaller responsibilities.

A can be defined with def square(number):, followed by return number * number. Calling square(6) sends the argument 6 to the parameter number and produces the result 3636. In this example, number is a parameter, 6 is an argument, and return sends the result back to the caller.

A can have multiple parameters, as in def rectangle_area(width, height): followed by return width * height. It can also perform an action without returning a useful result. If execution reaches the end without a return statement, Python returns None.

Parameters can have default values. For example, def greet(name, punctuation="!"): can return f"Hello, {name}{punctuation}"; calling greet("Sam") uses the default punctuation, while greet("Sam", ".") supplies a different value.

Variables created inside a are normally local to that . A well-designed generally has one clear responsibility, receives needed data through parameters, and returns a result rather than relying unnecessarily on global state. For example, def is_even(number): followed by return number % 2 == 0 is easy to test because its result depends only on its argument.

Takeaway: Use functions to package behavior, give them clear responsibilities, and make their inputs and results explicit.

and

is information received by a program, and is information produced by a program. Python's built-in functions provide simple ways to handle both.

print() writes values to standard . Examples include print("Hello"), print(2 + 3), and print("A", "B", "C", sep="-"). The sep argument controls the separator between values, and end controls what is written after the final value, as in print("Loading", end="...").

() displays an optional prompt, reads one line, removes its ending newline, and returns the result as a string. For example, name = ("What is your name? ") reads text that can then be used in print(f"Hello, {name}!").

Because () returns text, convert numeric before performing arithmetic. For example, quantity = int(("How many items? ")) reads a whole number, while price = float(("Price per item? ")) reads a number that may have a fractional part. The total = quantity * price then calculates the total, and print(f"Total: ${total:.2f}") formats it with two decimal places.

Takeaway: Treat as text until it has been validated and converted, then format so the result is clear to the user.

Putting the Fundamentals Together

A small grade calculator shows how the ideas work together. It separates , processing, and while validating the score before calculating a result.

First define letter_grade(score) so that scores at least 90 return "A", scores at least 80 return "B", scores at least 70 return "C", scores at least 60 return "D", and lower scores return "F". This uses selection and returns a letter.

Next, use name = ("Student name: ") to read a name and score = float(("Exam score: ")) to read and convert the score. Test the valid interval with if 0 <= score <= 100:. When the condition is true, assign grade = letter_grade(score) and display print(f"{name} earned a {grade}."). Otherwise, display print("Score must be between 0 and 100.").

The execution sequence is:

  1. Define letter_grade, which converts a numeric score into a letter.

  2. Read the student's name as a string.

  3. Read the score and convert it to a floating-point number.

  4. Check whether the score is in the valid interval from 00 through 100100.

  5. Call the and display the grade, or report invalid .

Common errors to prevent include confusing = with ==, forgetting that () returns a string, using inconsistent indentation, creating a while that never becomes false, referring to a name before assigning it, returning before the intended work is complete, and combining incompatible types such as a string and an integer without conversion or formatting.

Final takeaway: A readable beginner program gives each part a clear role: receive and validate , process it with expressions and functions, then produce understandable .