Expressions and Instructions

Objectives

  • understand the difference between expressions and instructions in Python, as well as their role in a program
  • importance of these two concepts for writing readable and efficient Python code

Definitions and differences

Expression

  • An expression is a combination of values, variables, operators and functions that is evaluated to produce a value.
  • An expression always returns a value

Simple examples:

2 + 3   # evaluates to 5
x * 10  # evaluates to the value of x multiplied by 10
"Hello" + " World" # evaluates to "Hello World"

More complex examples:

(x + y) / 2
len("Python") > 5

Instructions

  • An instruction (or command) is a line of code that performs an action.
  • Instructions do not necessarily return a value

Examples of instructions:

x = 5       # Assignment instruction
print(x)    # Display instruction
if x > 0:   # Conditional instruction
    print("Positive")

Expressions in detail

  • Types of expressions:
    • Arithmetic expressions: 2 + 3, x - 1
    • Boolean expressions: x > 5, y == 0
    • String expressions: "Hello" + "World"
  • Expression evaluation:
    • Explain how Python evaluates expressions from left to right, respecting operator precedence rules.
  • Using expressions in instructions:
    • An expression can be used inside an instruction:
y = (x + 5) * 2  # Expression (x + 5) * 2 used in an assignment instruction

Instructions

  • Types of instructions:
    • Assignment instruction: x = 10
    • Control flow instruction: if, for, while
    • Function instruction: def my_function():
    • Import instruction: import math
  • Compound and simple instructions:
    • Simple instructions: A single line of code, for example x = 10.
    • Compound instructions: Consist of multiple lines of code and include a code block (for example, loops and conditions).
  • Using expressions in instructions:
    • Expressions are commonly used in conditional instructions or loops:
if (x + 5) > 10:  # The expression (x + 5) > 10 is used to test the condition
    print("The condition is true.")