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:
Compilation: A compiler generates a bytecode representation of the source code.
Storage: This bytecode is saved with a extension and stored in the
__pycache__directory.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 --versionpython3 --versionpython -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
pythonorpython3in the terminal to see the>>>prompt.First Code Example:
>>> print('hello, world')
Modes of Execution
Interactive Mode (Shell): Expressions are evaluated instantly, but nothing is saved.
Script Mode: Code is written in a file with a extension (e.g.,
hello_world.py) and executed via an IDE or the command line usingpython 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 then later ).
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, andSPAMare 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.,
hoursinstead ofx1q3z9ocd).Descriptive but Short: Prefer
student_nameovers_n, but keep it concise.Avoid Confusion: Be careful with lowercase
land uppercaseO, as they look like1and0.Reserved Words: Avoid using Python keywords (e.g.,
print).
Python Keywords (Reserved Words) These names cannot be used as variables:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Mnemonic Comparison Examples
Unclear:
python x1q3z9ocd = 35.0 x1q3z9afd = 12.50 x1q3p9afd = x1q3z9ocd * x1q3z9afd print x1q3p9afd Slightly Better (Short but non-descriptive):
python a = 35.0 b = 12.50 c = a * b print c 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 , where is the real part, is the imaginary part, and .
String (str): A sequence of characters (e.g.,
'1 + 3','hello').Boolean (bool): Represented by
True(equivalent to ) orFalse(equivalent to ).
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 in42.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.0results in1.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.,
1evaluates to1).
Arithmetic Operators Most operators are "binary infix," meaning they operate on two operands and are placed between them.
Operator | Function | Example |
|---|---|---|
| Addition / Concatenation |
|
| Subtraction |
|
| Multiplication / String repetition |
|
| Division |
|
| Floor Division (Euclidean quotient) |
|
| Modulo (Remainder) |
|
| Exponentiation |
|
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 . 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 .
String Multiplication: If a string is multiplied by , the result is an empty string
''.
Operator Precedence (PEMDAS) When multiple operators are present, Python follows specific priority:
Parentheses
Exponentiation
Multiplication and Division (including
//and%)Addition and Subtraction
Operators of equal priority are evaluated Left to Right.
Example evaluation:
x = 1 + 2 * 3 - 4 / 2 ** 2results inx = 1 + 6 - 4 / 4x = 7 - 1.0x = 6.0.
Boolean Expressions and Logic
Boolean Logic
Type:
<class 'bool'>.Values:
TrueandFalse.Boolean Algebra: Expressions obey algebraic laws (Boolean logic). Combined using
and,or, andnot.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'isTrue.Case sensitivity:
'a' < 'A'isFalsebecauseord('a')is andord('A')is .Length: Shorter strings are padded with an "invisible character" that comes before all others. Thus,
'a' < 'aa'isTrue.
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
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).
Expression Statements: Lines that produce values, assign values, or generate results (e.g.,
pass,return,continue).Compound Statements: Include conditional (
if) and loop statements.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.