1.1. Variables#

1.1.1. Comments#

Comments in Python are non-executable lines of text that provide information, explanations, or notes within the code. Comments are useful for making code more readable, documenting the code, and helping other developers understand the purpose and functionality of specific sections of code. Comments are ignored by the Python interpreter and do not affect the execution of the program [Downey, 2015, Python Software Foundation, 2024].

In Python, there are two ways to add comments:

1.1.2. Single-line comments#

Single-line comments start with the hash (#) symbol and extend to the end of the line. Anything written after the # symbol on the same line is considered a comment.

Example:

# This is a single-line comment
x = 10  # This is also a comment

1.1.3. Multi-line comments (Docstrings)#

Multi-line comments are typically used for more extensive documentation, especially for functions, classes, or modules. They are created using triple quotes (''' or """) at the beginning and end of the comment [Downey, 2015, Python Software Foundation, 2024].

Example:

'''
This is a multi-line comment.
It can span multiple lines
and is often used as a docstring for functions or classes.
'''

Using comments wisely can improve code maintainability and facilitate collaboration among developers. They provide insights into the code’s intention and help in understanding complex logic or algorithms. However, it’s essential to use comments judiciously and avoid excessive or redundant commenting, as it can clutter the code unnecessarily.

1.1.4. Variables#

In Python, variables are used to store and manage data. A variable is a symbolic name that references a value, and you can assign various data types (such as numbers, strings, lists, etc.) to variables. Here are the key points about variables in Python [Downey, 2015, Python Software Foundation, 2024]:

  1. Variable Naming Rules:

    • Variable names must start with a letter (a-z, A-Z) or an underscore (_).

    • The subsequent characters can be letters, underscores, or digits (0-9).

    • Variable names are case-sensitive (“myVar” and “myvar” are considered different).

    • Avoid using Python keywords (reserved words) as variable names.

  2. Assignment:

    • Variables are assigned using the = operator.

    • The value on the right side of the = is assigned to the variable on the left side.

    • Example: x = 5 assigns the value 5 to the variable x.

  3. Data Types:

    • Python is dynamically typed, meaning you don’t need to specify the data type when declaring a variable. The interpreter determines the type based on the assigned value.

    • Common data types include integers, floats, strings, lists, tuples, dictionaries, and more. We will discuss this later on.

  4. Reassignment:

    • You can reassign a variable to a new value of a different type.

    • Example: x = 'Hello' reassigns the variable x to the string 'Hello'.

  5. Variable Usage:

    • Variables can be used in expressions, print statements, function calls, and more.

    • Variables hold the value assigned until they are reassigned or the program ends.

  6. Scope of Variables:

    • The scope of a variable determines where it can be accessed or modified in the code.

    • Variables defined inside a function are local to that function.

    • Variables defined outside any function are global and can be accessed throughout the module.

Example - Variable Assignment: Here we assign values to variables x, y, and z.

x = 10                 # Assigns the integer value 10 to x
y = 'Hello, World!'    # Assigns the string value 'Hello, World!' to y
z = [1, 2, 3]          # Assigns the list [1, 2, 3] to z

When you assign a value to a variable (e.g., x = 10), Python allocates memory to store that value. The variable name acts as a reference to that value.

Example - Variable Usage: We can use the variables by referencing their names. The print function outputs the value of the variables.

# Variable usage
print(x)        # Output: 10
print(y)        # Output: Hello, World!
print(z)        # Output: [1, 2, 3]
10
Hello, World!
[1, 2, 3]

You can use variables in expressions, functions, or other operations by referencing their names. For instance, print(x) will output the current value stored in x.

Note

The print function in Python is a built-in function that allows you to output text and values to the console or standard output. It’s commonly used for debugging, displaying information to users, or just for showing the value of variables during program execution. The print function takes one or more arguments, which can be strings, numbers, variables, or even expressions. It converts these arguments to strings and displays them in the console.

Remark

In Section 1.11, we will discuss functions.

Example - Variable Reassignment: Variables in Python can be reassigned to different values and even to different data types.

# Variable reassignment
x = 'Python'    # Reassigns the value of x to the string 'Python'
print(x)        # Output: Python
Python

Python allows dynamic typing, meaning a variable can be reassigned to a value of a different type without any issue. For example, x is initially assigned an integer value 10, but later reassigned to a string value 'Python'.

1.1.5. Valid and Invalid Variable Names in Python#

In Python, variable names are fundamental elements used to identify and store data values. These names play a crucial role in making your code readable and self-explanatory. It’s essential to understand the rules for creating valid variable names and to follow best practices to enhance code clarity and maintainability [Downey, 2015, Python Software Foundation, 2024].

1.1.5.1. Valid Variable Names:#

Valid variable names must adhere to a set of rules to be considered syntactically correct in Python:

  1. Start with a letter or underscore (_): A valid variable name must begin with a letter (either lowercase or uppercase) or an underscore. It cannot start with a digit or any other character. Using an underscore as the first character is a common convention for denoting “private” variables, but it has a special meaning in some contexts. For example:

valid_variable = 42
my_var = "Calgary"
  1. Subsequent characters: After the initial character, a variable name can contain letters, underscores, and digits (0-9). No spaces or special characters (except underscore) are allowed within the variable name. This rule ensures that variable names are consistent and easy to understand. For example:

count123 = 42
my_var = "Hello"
  1. Case-sensitive: Python variable names are case-sensitive, meaning that variables with different letter case are treated as distinct entities. This distinction is important when working with variables. For example:

my_var = 5
My_Var = "Hello Calgary"
  1. Avoid using Python keywords: Variable names cannot be the same as Python keywords, which are reserved words used for specific purposes in the language. Using keywords as variable names will lead to syntax errors or unexpected behavior. For example, avoid using names like if, for, while, and so on.

1.1.5.2. Invalid Variable Names:#

Invalid variable names violate one or more of the rules mentioned above:

  1. Starting with a number: A variable name that starts with a digit is invalid because it doesn’t follow the rule of starting with a letter or underscore. For example:

    123data = "Invalid variable name"
    
  2. Containing special characters: Variable names cannot contain spaces or special characters (except underscores). Using characters like hyphens, dots, or symbols within a variable name is not allowed in Python. For example:

    my-var = "Invalid variable name"
    my.var = "Invalid variable name"
    
  3. Using Python keywords: Variable names that match Python keywords are invalid. These keywords have predefined meanings in the language, and using them as variable names will lead to conflicts and errors. For example:

    if = 42  # Invalid use of a Python keyword
    

By choosing meaningful and descriptive variable names while adhering to these rules, you can enhance the readability and clarity of your Python programs.

1.1.6. Naming Conventions: Snake Case and Camel Case#

In Python, naming conventions play a crucial role in maintaining code readability and consistency. The two primary naming conventions used in Python are snake case and camel case. While snake case is more commonly used and recommended by Python’s PEP 8 style guide, camel case is also used in specific contexts.

1.1.6.1. Snake case#

Snake case is the preferred naming convention for most identifiers in Python. In this format, words are separated by underscores (_), and all letters are in lowercase. This style enhances readability by clearly delineating words within an identifier.

  • Usage:

    • Variable Names: Snake case is used to name variables to clearly indicate their purpose.

    • Function Names: Functions are named using snake case to describe their action or purpose.

    • Module Names: File names for Python modules also follow the snake case convention.

Remark

In Section 1.9, we will discuss modules.

  • Examples:

    • Variables: user_name, account_balance, total_amount

    • Functions: calculate_area(), get_user_input(), print_report()

    • Modules: data_processing.py, user_authentication.py

  • Advantages:

    • Readability: The underscores make it easy to read and understand the name by clearly separating words.

    • Consistency: Following PEP 8 guidelines, snake case ensures a uniform naming style across Python codebases.

1.1.6.2. Camel case#

Camel case is less common in Python but is used in specific scenarios, primarily for class names. In camel case, the first letter of each word is capitalized, except for the first word in lower camel case (e.g., myVariable), while in upper camel case (PascalCase), all words start with an uppercase letter.

  • Usage:

    • Class Names: Python uses upper camel case (PascalCase) for naming classes.

    • Constants: While not camel case, constants are often written in all uppercase letters with underscores separating words (e.g., MAX_VALUE).

  • Examples:

    • Classes: MyClass, EmployeeRecord, AccountManager

  • Advantages:

    • Distinction: Using camel case for class names helps distinguish classes from functions and variables, which are named using snake case.

    • Conventions: Aligns with object-oriented programming conventions where classes represent objects or entities.

In Python, snake case and camel case serve different purposes, contributing to the overall readability and organization of the code:

  • Snake Case: The default and recommended convention for variable names, function names, and module names, ensuring clarity and consistency.

  • Camel Case: Primarily used for class names, helping to distinguish class definitions from other types of identifiers.