Built with Tutify.io

    AIStudyLabs

    Statements, Expressions, and Comments

    Statements, Expressions, and Comments

    Introduction

    In this lesson you will learn how to say things to Python (statements), how to ask it to compute something (expressions), and how to talk to humans reading your code (comments). You’ll practice writing and evaluating expressions, constructing different statement types, documenting your code, and spotting common syntax mistakes.


    1. Expressions vs. Statements

    What is an Expression?

    An expression is anything that Python can evaluate to a single value.

    Examples of expressions:

    3 + 4              # arithmetic expression
    name.lower()       # method call expression
    price * quantity   # expression using variables
    len("Python")      # function call expression
    
    x = 10
    x + 5              # expression using a variable
    

    In the interactive shell, expressions show their result. In a script, an expression by itself does nothing unless its result is used (stored, printed, etc.).

    What is a Statement?

    A statement is a complete instruction that Python can execute. Many statements contain expressions.

    Common statements:

    Example mixing both:

    x = 5 + 3          # whole line is a statement
                       # "5 + 3" is an expression inside the statement
    

    2. Writing and Evaluating Expressions

    Expressions with Variables and Operators

    price = 19.99
    quantity = 3
    
    total = price * quantity + 5  # 5 is, for example, a shipping fee
    print(total)
    
    # Output:
    64.97
    

    Explanation:

    Expressions with Function Calls

    message = "Python is fun!"
    length = len(message)        # expression: len(message)
    
    print("Message length:", length)
    print("Uppercase:", message.upper())
    
    # Output:
    Message length: 14
    Uppercase: PYTHON IS FUN!
    

    Explanation:


    3. Writing Effective Comments

    Comments help humans understand why code exists and what it does.

    3.1 Single-Line Comments

    Use # for single-line comments.

    # Calculate final bill including tax and tip
    subtotal = 50
    
    tax_rate = 0.1   # 10% tax
    tip_rate = 0.15  # 15% tip
    
    final_total = subtotal * (1 + tax_rate + tip_rate)
    print("Final total:", final_total)
    
    # Output:
    Final total: 62.5
    

    Guidelines:

    3.2 Multi-Line Comments / Docstrings

    Python doesn’t have a special multi-line comment syntax, but you can:

    def describe_temperature(celsius):
        """Return a human-friendly description for a temperature.
    
        This helper function converts a numeric Celsius value into a
        descriptive string like "cold", "warm", or "hot".
        """
        if celsius < 10:
            return "cold"
        elif celsius < 25:
            return "warm"
        else:
            return "hot"
    
    print(describe_temperature(18))
    
    # Output:
    warm
    

    Note: Triple-quoted strings used as the first statement inside a function become that function’s docstring, which tools can display (e.g., help(describe_temperature)).

    For general multi-line comments outside functions, prefer repeated #:

    # Load data from file
    # Validate contents
    # Then compute summary statistics
    

    4. Common Syntax Errors and How to Avoid Them

    4.1 Mixing Expressions and Statements Incorrectly

    # ❌ Invalid: two expressions side by side
    1 + 2 3 + 4
    

    Fix by separating statements with new lines or semicolons (new lines are preferred):

    # ✅ Valid
    print(1 + 2)
    print(3 + 4)
    

    4.2 Unterminated or Misplaced Comments

    # ❌ Invalid: comment interrupting code in the middle of an expression
    result = 10 +  # add base value
             5
    

    Correct usage:

    # ✅ Valid: comment at end of line or on its own line
    result = 10 + 5  # add base value
    

    4.3 Using # Inside Strings by Mistake

    text = "This is not a comment # it's part of the string"
    print(text)
    
    # Output:
    This is not a comment # it's part of the string
    

    Reminder: # only starts a comment outside of string literals.

    4.4 Missing Colons in Compound Statements

    # ❌ SyntaxError: missing colon
    if score > 50
        print("Passed")
    

    Correct form:

    # ✅ Valid
    if score > 50:
        print("Passed")
    

    4.5 Writing Expressions That Don’t Do Anything

    In scripts, an expression alone is pointless unless its result is used:

    3 + 4       # does nothing in a script
    
    result = 3 + 4
    print(result)  # now the result is visible
    

    Summary / Key Takeaways

    In this lesson on Statements, Expressions, and Comments, you have learned:

    Python Programming – Complete Course with Practical Examples — Python Syntax, Indentation, and Core Concepts

    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