Week 2: Mastering Variables, Data, and Operations

Unlocking the power to store and manipulate information in Python.

Dive into Chapter 2

Chapter 2: Fundamental Data Types and Operations

Variables: Naming, Assigning Values.

In Python, a variable is like a named storage location in the computer's memory. You can use variables to store and refer to data. Think of it as a label you can put on a box containing some information.

Naming Variables

Python has specific rules and conventions for naming variables (as briefly mentioned last week):

  • Variable names must start with a letter (a-z, A-Z) or an underscore (_).
  • The rest of the name can contain letters, numbers (0-9), and underscores.
  • Variable names are case-sensitive (e.g., `myVar` is different from `myvar`).
  • Avoid using Python keywords (reserved words like `if`, `else`, `for`, etc.) as variable names.
  • Choose descriptive names that indicate the purpose of the variable (e.g., `user_name` is better than `n`).
  • The convention in Python is to use snake_case for variable names (lowercase words separated by underscores).

Assigning Values

You assign a value to a variable using the assignment operator (`=`).

message = "Hello, Python!"
number_of_students = 25
pi_value = 3.14159

Python is dynamically typed, meaning you don't need to explicitly declare the data type of a variable when you assign a value to it. Python will automatically infer the type.

x = 10      # x is an integer
y = 3.14    # y is a float
z = "text"  # z is a string
is_valid = True # is_valid is a boolean

Basic Data Types: The Building Blocks of Information.

Data types classify the kind of values that a variable can hold. Python has several built-in data types. Let's look at the fundamental ones:

  • Integers (`int`): Whole numbers (positive, negative, or zero) without any decimal point.
    count = 100
    negative_number = -5
    zero = 0
  • Floats (`float`): Numbers with a decimal point. They can also represent numbers in scientific notation.
    price = 99.99
    temperature = 36.5
    scientific_notation = 2.5e3  # Represents 2500.0
  • Strings (`str`): Sequences of characters enclosed in single quotes (`'...'`) or double quotes (`"..."`).
    name = "Alice"
    greeting = 'Hello'
    empty_string = ""
  • Booleans (`bool`): Represent truth values. There are only two boolean values: `True` and `False` (note the capitalization). Booleans are often the result of comparisons or logical operations.
    is_student = True
    is_adult = False

You can use the `type()` function to determine the data type of a variable.

age = 30
print(type(age))  # Output: <class 'int'>

pi = 3.14159
print(type(pi))   # Output: <class 'float'>

message = "World"
print(type(message)) # Output: <class 'str'>

is_active = True
print(type(is_active)) # Output: <class 'bool'>

Arithmetic Operators: Performing Calculations.

Arithmetic operators are used to perform mathematical operations on numbers.

Operator Name Example Result Description
`+` Addition `5 + 3` `8` Adds two operands.
`-` Subtraction `5 - 3` `2` Subtracts the second operand from the first.
`*` Multiplication `5 * 3` `15` Multiplies two operands.
`/` Division `5 / 3` `1.666...` Divides the first operand by the second (always results in a float).
`//` Floor Division `5 // 3` `1` Divides the first operand by the second, rounding down to the nearest whole number (integer).
`%` Modulo `5 % 3` `2` Returns the remainder of the division of the first operand by the second.
`**` Exponentiation `5 ** 3` `125` Raises the first operand to the power of the second.

Let's see some examples in code:

a = 10
b = 4

print("a + b =", a + b)   # Output: a + b = 14
print("a - b =", a - b)   # Output: a - b = 6
print("a * b =", a * b)   # Output: a * b = 40
print("a / b =", a / b)   # Output: a / b = 2.5
print("a // b =", a // b) # Output: a // b = 2
print("a % b =", a % b)   # Output: a % b = 2
print("a  b =", a  b) # Output: a ** b = 10000

Comparison Operators: Making Decisions.

Comparison operators are used to compare two values. The result of a comparison operation is always a boolean value (`True` or `False`).

Operator Name Example Result (if x=5, y=3) Description
`==` Equal to `x == y` `False` Returns `True` if both operands are equal.
`!=` Not equal to `x != y` `True` Returns `True` if operands are not equal.
`>` Greater than `x > y` `True` Returns `True` if the left operand is greater than the right operand.
`<` Less than `x < y` `False` Returns `True` if the left operand is less than the right operand.
`>=` Greater than or equal to `x >= y` `True` Returns `True` if the left operand is greater than or equal to the right operand.
`<=` Less than or equal to `x <= y` `False` Returns `True` if the left operand is less than or equal to the right operand.

Examples in code:

p = 10
q = 10
r = 5

print("p == q:", p == q)   # Output: p == q: True
print("p != r:", p != r)   # Output: p != r: True
print("p > r:", p > r)     # Output: p > r: True
print("p < r:", p < r)     # Output: p < r: False
print("p >= q:", p >= q)   # Output: p >= q: True
print("r <= q:", r <= q)   # Output: r <= q: True

Logical Operators: Combining Conditions.

Logical operators are used to combine or modify boolean values. Python has three main logical operators: `and`, `or`, and `not`.

  • `and` (Logical AND): Returns `True` if both operands are `True`. Otherwise, it returns `False`.
    Operand 1 Operand 2 Result (Operand 1 and Operand 2)
    `True` `True` `True`
    `True` `False` `False`
    `False` `True` `False`
    `False` `False` `False`
    age = 25
    has_license = True
    can_drive = age >= 18 and has_license
    print("Can drive:", can_drive) # Output: Can drive: True
  • `or` (Logical OR): Returns `True` if at least one of the operands is `True`. It returns `False` only if both operands are `False`.
    Operand 1 Operand 2 Result (Operand 1 or Operand 2)
    `True` `True` `True`
    `True` `False` `True`
    `False` `True` `True`
    `False` `False` `False`
    is_weekend = True
    is_holiday = False
    can_relax = is_weekend or is_holiday
    print("Can relax:", can_relax) # Output: Can relax: True
  • `not` (Logical NOT): Returns the opposite of the operand's boolean value. If the operand is `True`, `not` returns `False`, and if the operand is `False`, `not` returns `True`.
    Operand Result (not Operand)
    `True` `False`
    `False` `True`
    is_raining = False
    is_sunny = not is_raining
    print("Is sunny:", is_sunny) # Output: Is sunny: True

Order of Operations: The Precedence of Operators.

When an expression contains multiple operators, Python follows a specific order of operations (often remembered by the acronym PEMDAS/BODMAS) to determine the sequence in which the operations are performed:

  1. Parentheses / Brackets: Operations inside parentheses are evaluated first.
  2. Exponents / Orders (powers and square roots, etc.): Evaluated next.
  3. Multiplication and Division: These are performed from left to right.
  4. Addition and Subtraction: These are performed from left to right.

Understanding the order of operations is crucial for writing expressions that produce the intended results.

result1 = 10 + 2 * 3  # Multiplication is done before addition
print("result1:", result1) # Output: result1: 16

result2 = (10 + 2) * 3  # Parentheses change the order
print("result2:", result2) # Output: result2: 36

result3 = 5 ** 2 - 10 / 2 # Exponentiation, then division, then subtraction
print("result3:", result3) # Output: result3: 20.0

When in doubt, use parentheses to explicitly control the order of operations and make your code clearer.

Syllabus