Built with Tutify.io

    AIStudyLabs

    Declaring and Using Variables

    Declaring and Using Variables

    Introduction

    In this lesson, you will move from simply running Python code to actually managing data with variables. You will learn how to declare and use variables, what kinds of data they can store, how reassignment changes values during execution, and how to convert between data types safely and intentionally.

    By the end, you should feel confident creating variables for numbers, text, and boolean values, understanding how they behave in memory, and using type conversion functions to keep your programs predictable and error‑free.


    1. What Is a Variable in Python?

    A variable is a name that refers to a value stored in memory. Think of it as a labeled box: the box name is the variable, and the content is the value.

    Python uses the assignment operator = to bind a name to a value:

    age = 25
    name = "Alice"
    is_member = True
    

    Here, age, name, and is_member are variables. They are created the moment you assign them a value.


    2. Declaring Variables Correctly

    2.1 Variable Names and the Assignment Operator

    A variable declaration in Python is just an assignment statement:

    score = 10           # integer
    player_name = "Sam"  # string
    is_active = False    # boolean
    

    Key points:

    You can also assign the result of an expression:

    width = 5
    height = 3
    area = width * height
    

    Now area stores the result of width * height at that moment in time.

    Example: Basic Variable Creation and Use

    # Example: Declaring and using variables
    item_price = 19.99
    quantity = 3
    subtotal = item_price * quantity
    
    print("Item price:", item_price)
    print("Quantity:", quantity)
    print("Subtotal:", subtotal)
    
    # Output:
    Item price: 19.99
    Quantity: 3
    Subtotal: 59.97
    

    Explanation:


    3. Mutable vs Immutable Variable Types

    Python variables don’t contain values; they refer to objects in memory. Different object types behave differently.

    3.1 Immutable Example

    # Example: Immutable variables (int and str)
    count = 5
    count = count + 1  # creates a new int object and rebinds 'count'
    
    message = "Hello"
    message = message + "!"  # creates a new string object
    
    print(count)
    print(message)
    
    # Output:
    6
    Hello!
    

    Explanation:

    3.2 Mutable Example

    # Example: Mutable variable (list)
    numbers = [1, 2, 3]
    
    numbers.append(4)       # modifies the list in place
    numbers[0] = 10         # changes the first element
    
    print(numbers)
    
    # Output:
    [10, 2, 3, 4]
    

    Explanation:


    4. Storing and Updating Different Value Types

    4.1 Numeric Variables

    You can store integers and floating‑point numbers and update them using expressions:

    # Example: Working with numeric variables
    balance = 100.0
    
    deposit = 25.5
    balance = balance + deposit
    
    withdrawal = 40
    balance = balance - withdrawal
    
    print("Final balance:", balance)
    
    # Output:
    Final balance: 85.5
    

    Explanation:

    4.2 String Variables

    # Example: Updating string variables
    first_name = "Jordan"
    last_name = "Lee"
    
    full_name = first_name + " " + last_name
    
    print("Full name:", full_name)
    
    # Output:
    Full name: Jordan Lee
    

    Explanation:

    4.3 Boolean Variables

    Booleans represent truth values and are often used to track state:

    # Example: Boolean variables
    is_logged_in = False
    
    # User logs in successfully
    is_logged_in = True
    
    print("Logged in:", is_logged_in)
    
    # Output:
    Logged in: True
    

    Explanation:


    5. Variable Reassignment and Execution Flow

    Reassignment means changing which object a variable refers to as the program runs.

    # Example: Tracing variable reassignment
    status = "pending"
    print("Initial status:", status)
    
    status = "processing"  # reassign
    print("During process:", status)
    
    status = "completed"   # reassign again
    print("Final status:", status)
    
    # Output:
    Initial status: pending
    During process: processing
    Final status: completed
    

    How to predict behavior:

    A common mistake is assuming a later change will retroactively update earlier calculations—it does not. Once a calculation is done and stored, changing the input variables does not change that stored result unless you explicitly recompute it.


    6. Type Conversion When Assigning and Manipulating Variables

    When data comes from input() or external sources, it’s often a string. To use it as a number or boolean, you must convert its type.

    Common conversion functions:

    6.1 Converting on Assignment

    # Example: Converting types on assignment
    raw_age = "30"            # imagine this came from input()
    age = int(raw_age)         # convert string to int
    
    raw_price = "19.95"
    price = float(raw_price)   # convert string to float
    
    print(type(age), age)
    print(type(price), price)
    
    # Output:
    <class 'int'> 30
    <class 'float'> 19.95
    

    Explanation:

    6.2 Using Type Conversion in Expressions

    # Example: Combining input-like strings with numeric operations
    quantity_text = "4"
    unit_price_text = "5.50"
    
    quantity = int(quantity_text)
    unit_price = float(unit_price_text)
    
    total_cost = quantity * unit_price
    
    message = "Total cost: " + str(total_cost)
    print(message)
    
    # Output:
    Total cost: 22.0
    

    Explanation:

    6.3 Booleans from Other Types

    # Example: Boolean conversion
    items_in_cart = 0
    has_items = bool(items_in_cart)
    
    print("Items in cart:", items_in_cart)
    print("Has items:", has_items)
    
    # Output:
    Items in cart: 0
    Has items: False
    

    Explanation:


    Summary / Key Takeaways

    In this lesson on Declaring and Using Variables, you have learned:

    Python Programming – Complete Course with Practical Examples — Variables, Data Types, and Type Conversion

    Getting Started with Python and the Course

    Python Syntax, Indentation, and Core Concepts

    Variables, Data Types, and Type Conversion

    Operators, Expressions, and Control Flow

    Loops and Iteration Patterns

    Working with Strings in Depth

    Collections: Lists, Tuples, Sets, and Dictionaries

    Functions and Program Structuring

    Functional Programming Concepts in Python

    Modules, Packages, and Code Organization

    Error Handling and Debugging Fundamentals

    File Handling and Data Formats

    Object-Oriented Programming in Python

    Advanced Python: Iterators, Generators, and Decorators

    Python Standard Library for Real-World Tasks

    Python for Automation and Scripting

    Testing and Quality Assurance in Python

    Tutorial Not Found