Variables, Expressions, and Statements in Python Programming

Introduction to Computer Programming and Python Philosophy

Course Information:

  • Subject: Computer Programming (SECT-1082)

  • Topic: Variables, Expressions, and Statements

  • Instructor: Surafel Lemma Abebe (Ph. D.)

Python Philosophy Python was designed with a focus on core principles to facilitate efficient and clean programming:

  • Code Readability: The syntax is designed to be clear and readable, often resembling human language.

  • Efficiency: Encourages writing logic using few lines of code compared to other languages.

Technical Classification

  • General Purpose: Suitable for a wide range of applications, from web development to data science.

  • High Level: Abstracts away low-level computer details (like memory management).

  • Interpreted: Python code is processed at runtime by an interpreter.

The Execution Process (Behind the Scenes) When a Python script is run, the following sequence occurs:

  1. Compilation: A compiler generates a bytecode representation of the source code.

  2. Storage: This bytecode is saved with a .pyc.pyc extension and stored in the __pycache__ directory.

  3. Execution: The Python Virtual Machine (PVM) executes the bytecode.

Python Versioning and Installation

Versioning Programming languages evolve over time to incorporate new ideas and technologies, make the language more versatile and powerful, and provide bug fixes.

  • Latest Version (as of April 2025): Python 3.13.3

  • Verification: To check the installed version via command prompt, use:

    • python --version

    • python3 --version

    • python -v

Installation and Environment

  • Official Source: Download for specific operating systems at https://www.python.org/downloads/.

  • References: For detailed installations steps and setting up Editors/IDEs, refer to Appendix A and Appendix B of Python Crash Course: A Hands-on, Project-based Introduction to Programming by Eric Matthes (2016).

The REPL Environment

  • Definition: REPL stands for Read-Evaluate-Print Loop.

  • History: Invented in the early 1960s for exploratory programming.

  • Usage: Allows programmers to see the result of each portion of code as they enter it, making it ideal for experimentation and tinkering.

  • Starting the Shell: Type python or python3 in the terminal to see the >>> prompt.

  • First Code Example: >>> print('hello, world')

Modes of Execution

  1. Interactive Mode (Shell): Expressions are evaluated instantly, but nothing is saved.

  2. Script Mode: Code is written in a file with a .py.py extension (e.g., hello_world.py) and executed via an IDE or the command line using python hello_world.py.

Variables and Naming Conventions

Definition of a Variable A variable is the combination of a name and an associated value with a specific type. Formally, it is a named place in memory where a programmer can store data and retrieve it later using the variable "name."

  • Single Value Association: At any given time, a variable can refer to only one value.

  • Dynamic Nature: The value can change over time (e.g., setting x=3x = 3 then later x=5x = 5).

Variable Naming Rules

  • Start Characters: Must start with a letter (a-z, A-Z) or an underscore _.

  • Body Characters: Must consist only of letters, numbers, and underscores.

  • Forbidden: Spaces are not allowed within a name.

  • Case Sensitivity: spam, Spam, and SPAM are three different variables.

Naming Examples

  • Good: spam, eggs, spam23, _speed.

  • Bad: 23spam (starts with number), #sign (invalid character), var.12 (contains period), student name (contains space).

Best Practices

  • Mnemonic Names: Choose names that serve as memory aids for what the variable stores (e.g., hours instead of x1q3z9ocd).

  • Descriptive but Short: Prefer student_name over s_n, but keep it concise.

  • Avoid Confusion: Be careful with lowercase l and uppercase O, as they look like 1 and 0.

  • Reserved Words: Avoid using Python keywords (e.g., print).

Python Keywords (Reserved Words) These names cannot be used as variables:

False

class

finally

is

return

None

continue

for

lambda

try

True

def

from

nonlocal

while

and

del

global

not

with

as

elif

if

or

yield

assert

else

import

pass

break

except

in

raise

Mnemonic Comparison Examples

  1. Unclear:python x1q3z9ocd = 35.0 x1q3z9afd = 12.50 x1q3p9afd = x1q3z9ocd * x1q3z9afd print x1q3p9afd     

  2. Slightly Better (Short but non-descriptive):python a = 35.0 b = 12.50 c = a * b print c     

  3. Best practice (Mnemonic):python hours = 35.0 rate = 12.50 pay = hours * rate print pay     

Named Constants

  • Constants are memory locations with names whose content should not change.

  • They improve code readability.

  • Convention: Use all uppercase (e.g., PI = 3.14). Python does not strictly enforce this immutability, but it is a standard practice.

Primitive Data Types and Literals

Literals Literals are "unnamed constants" where the value seen is literally the value you have (e.g., 13, 'hello').

  • Handling Apostrophes in Strings: To use an apostrophe inside a string literal, use double quotes (e.g., "Earl's") or an escape character (e.g., 'Earl\'s').

Data Types A data type is a classification telling the interpreter how the programmer intends to use the data.

  • Purpose: Different types have unique memory storage requirements and varying behaviors for operators.

  • Operator Overloading: The + operator performs addition on numeric types but concatenation on strings.

Common Python Types

  • Numeric Types:

    • Integer (int): Whole numbers.

    • Floating Point (float): Numbers with fractional parts.

    • Long Integers: Limited only by available memory.

    • Doubles: Double precision floating numbers.

    • Complex Numbers: Written in the form z=a+biz = a + bi, where aa is the real part, bibi is the imaginary part, and i=1i = \sqrt{-1}.

  • String (str): A sequence of characters (e.g., '1 + 3', 'hello').

  • Boolean (bool): Represented by True (equivalent to 11) or False (equivalent to 00).

Typing Mechanisms

  • Static Typing: Types are known at compile time and cannot change (used in other languages).

  • Dynamic Typing: Types of variables can change at runtime (used in Python).

  • Note: While convenient, dynamic typing puts more responsibility on the programmer as Python does not enforce type consistency. Use the type() function to check a variable's current type.

Type Casting and Conversion

Casting The process of converting one data type into another using built-in functions:

  • int(): Converts to integer.

  • float(): Converts to float.

  • str(): Converts to string.

Casting Logic

  • If i = 42, float(i) results in 42.0.

  • Error: Using int() on a string that contains non-numeric characters will result in an error.

  • Implicit Conversion: Python automatically converts types in certain contexts. For example, 3 - 2.0 results in 1.0 (integer converted to float before operation).

Expressions and Arithmetic Operators

Definition of an Expression A syntactically valid combination of constants, variables, functions, and operators that can be evaluated to a single value.

  • The simplest expression is a single literal (e.g., 1 evaluates to 1).

Arithmetic Operators Most operators are "binary infix," meaning they operate on two operands and are placed between them.

Operator

Function

Example

+

Addition / Concatenation

1 + 2 = 3

-

Subtraction

3 - 1 = 2

*

Multiplication / String repetition

'Foo' * 3 = 'FooFooFoo'

/

Division

17 / 5 = 3.4

//

Floor Division (Euclidean quotient)

17 // 5 = 3; 17 // -5 = -4

%

Modulo (Remainder)

17 % 5 = 2; 17 % -5 = -3

**

Exponentiation

2 ** 3 = 8

Mathematical Notes on Operators

  • Division Rule: Division / always yields a float, even if operands are integers.

  • Modulo/Floor Division Rule: Calculated based on the identity a=bq+ra = bq + r. The result of % always carries the same sign as the second operand (the divisor).

  • Floor Function: Returns the largest integer less than or equal to xx.

  • String Multiplication: If a string is multiplied by 00, the result is an empty string ''.

Operator Precedence (PEMDAS) When multiple operators are present, Python follows specific priority:

  1. Parentheses

  2. Exponentiation

  3. Multiplication and Division (including // and %)

  4. Addition and Subtraction

  • Operators of equal priority are evaluated Left to Right.

  • Example evaluation: x = 1 + 2 * 3 - 4 / 2 ** 2 results in x = 1 + 6 - 4 / 4 \rightarrow x = 7 - 1.0 \rightarrow x = 6.0.

Boolean Expressions and Logic

Boolean Logic

  • Type: <class 'bool'>.

  • Values: True and False.

  • Boolean Algebra: Expressions obey algebraic laws (Boolean logic). Combined using and, or, and not.

  • De Morgan's Laws: Used for simplifying logical expressions.

Comparison Operators These compare two objects or values and return a Boolean.

  • ==: Equal to

  • !=: Not equal to

  • >: Greater than

  • <: Less than

  • >=: Greater than or equal to

  • <=: Less than or equal to

Lexicographical Order Strings are compared based on their Unicode code points (found via ord() function).

  • Alphabetic order: 'a' < 'b' is True.

  • Case sensitivity: 'a' < 'A' is False because ord('a') is 9797 and ord('A') is 6565.

  • Length: Shorter strings are padded with an "invisible character" that comes before all others. Thus, 'a' < 'aa' is True.

Python Statements

Definition A statement is an instruction to perform a specific action and is the smallest unit of code the interpreter can execute.

Types of Statements

  1. Simple Statements: A single line representing a basic action. Usually ends with a newline.

    • Assignment Statement: <variable> = <expr>. The expression is evaluated first, then the result is stored in the variable (e.g., x = x + 1).

  2. Expression Statements: Lines that produce values, assign values, or generate results (e.g., pass, return, continue).

  3. Compound Statements: Include conditional (if) and loop statements.

  4. Multi-line Statements:

    • Explicit continuation: Use a backslash \ to break a long line.

    • Implicit continuation: Use parentheses (), braces {}, or square brackets [] to extend logic across lines.

Documentation and Comments

Purpose of Comments

  • Increases code readability and maintainability.

  • Facilitates knowledge sharing and explains logic for long-term understanding.

  • Allows for including resource links and encourages code reusability.

Implementing Comments

  • Single-line: Identified with the hash symbol #. Everything following it on that line is ignored by the interpreter.

  • Multi-line: Python does not have a dedicated multi-line comment syntax, but triple quotes (''' or """) are used as a workaround to create multi-line string blocks that act as comments.