Variables in Python

Understand how variables work in Python with clear examples. Learn naming rules, variable assignment, dynamic typing, and best practices for writing readable Python code.

Loading...
Variables in Python

In Python, variables are used to store data values. They act as containers that hold data, which can be of various types such as integers, strings, lists, etc.

For example:

name = "John" # name is a variable that stores the value "John"
print(name) # Variables can be used in functions, print statements and more.
 
#output: John

Variable naming rules

When naming variables in Python, there are a few important rules and guidelines to follow:

  • Variable names must start with a letter or underscore.

    _name = "Alice"  # Valid
    name1 = "Bob"    # Valid
  • They can contain letters, digits, and underscores.

    name_1 = "Charlie"  # Valid
    age_30 = 30         # Valid
  • Variable names are case-sensitive (a and A are considered different variables).

    a = 5
    A = 19
    sum = a + A
    print("The sum is:", sum) # Output: The sum is: 24
  • There are specific keywords in Python (such as if, else, for, while, etc.) that cannot be used as variable names because they have special meanings in the language.

    # Invalid variable names
    # if = 10    # SyntaxError: cannot assign to keyword
    # for = 5    # SyntaxError: cannot assign to keyword

Variable Assignment and Types

Python uses dynamic typing, which means you don't have to specify the data type of a variable when declaring it, the type is determined automatically at runtime based on the assigned value. This makes Python flexible and easy to write, especially for beginners.

Example:

x = 10         # x is an integer
y = "Hello"    # y is a string
z = [1, 2, 3]  # z is a list

Python allows you to assign new values of different types to variables without any issue:

x = "Now I'm a string"  # x was initially an integer, but now it's a string

Multiple Variable Assignment

You can also assign values to multiple variables in a single line as follows:

x, y, z = 10, "Hello", [1, 2, 3]
print(x)  # Output: 10
print(y)  # Output: Hello
print(z)  # Output: [1, 2, 3]

Best Practices for Naming Variables

  • Be descriptive: Choose meaningful names that describe the purpose of the variable. For example, use age instead of a, and first_name instead of fn.
  • Use underscores for readability: If your variable name has more than one word, use underscores to separate them. This is called snake_case, and it's recommended by the PEP 8 style guide.
    user_age = 30
    first_name = "John"

Support my work!