Understanding Python Expressions and Operators

Aug 8, 2024

Expressions, Operators, and User Input in Python

Statements

  • Statement: A unit of code the Python interpreter can execute.
  • Types of statements:
    • Print statement
    • Assignment statement
  • Interactive mode: Typing and executing statements directly in the Python interpreter.
  • Script mode: Writing a sequence of statements in a file and executing the script.

Example in Interactive Mode

  • Assignment Statement: x = 5
    • Stores 5 in the memory allocated for x.
    • Typing x will display 5.
  • Arithmetic Operation: x + y
    • Fetches values of x and y, adds them, and prints the result in interactive mode.
    • In a script, use print(x + y) to display the result.

Writing and Executing a Python Script

  • Editor: Use any editor (e.g., vi editor in Linux).
  • File Extension: .py for Python scripts.
  • Example Script: first.py
    print(100)
    x = 5
    y = 20
    print(x + y)
    
  • Execution: python3 first.py
    • Output: 100 25

Operators and Operands

  • Operator: Special symbols that represent computations (e.g., +, -, *, /, **).
  • Operand: Values the operator is applied to.
  • Types of operators:
    • + (Addition)
    • - (Subtraction)
    • * (Multiplication)
    • / (Division)
    • ** (Exponentiation)

Division Operator Changes

  • Python 2.x: Integer division (e.g., 7 / 5 results in 1).
  • Python 3.x: Floating-point division (e.g., 7 / 5 results in 1.4).

Expressions

  • Expression: Combination of values, variables, and operators.
  • Examples:
    • 20 + 32
    • r - 1
    • 1 + 1
  • Interactive Mode: Evaluates and displays the result.
  • Script Mode: Use print to display results.

Order of Operations (PEMDAS)

  • P: Parentheses
  • E: Exponents
  • MD: Multiplication and Division (same precedence)
  • AS: Addition and Subtraction (same precedence)
  • Left to Right: Operators with the same precedence are evaluated from left to right.

Modulus Operator

  • Modulus: %
    • Yields the remainder when the first operand is divided by the second.
    • Example: 7 % 3 results in 1.
  • Floor Division: //
    • Example: 7 // 5 results in 1.
  • Usage: Extracts rightmost digits from a number.

String Operations

  • Concatenation: + operator joins two strings.
    • Example: `