Variables

Variables let us store and manipulate different kinds of data. For example, we can store numbers, characters, lists, dictionaries, and many other types with Python.


Assigning values

We use the assignment operator = to assign values to variables.

On the left side is a name we give to our variable and on the right side is a literal value.

[1]:
example_variable = 5
print("example_variable =", example_variable)
example_variable = 5

We can also assign values to multiple variables on the same line.

[15]:
x, y, z = 1,2,3
print(x, y, z)
1 2 3

Naming Variables

Variable names should be descriptive. Your programs will be easier to read and write if you name your variables according to the values they represent. Most python programs name variables with all lowercase letters and underscores between words. For example, this_is_a_long_variable_name. Consistency in naming style is considered a good practice.

Rules for Python variables:

  • A variable name must start with a letter or the underscore character

  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )

  • Variable names are case-sensitive (age, Age and AGE are three different variables)

[3]:
_variable_names_can_start_with_an_underscore = True
variable_names_can_include_numbers_like_123 = True
VARIABLE_NAMES_ARE_CASE_SENSITIVE = True

Data Types

Python is a dynamically-typed programming language. This means that data types are automatically inferred based on the values being assigned. Python has many built-in data types. For example,

  • bool (a logical value, either True or False)

  • int (integer values, positive or negative whole numbers like -1 and 1)

  • float (floating point values, numbers like 3.1415)

  • str (a string is a list of characters, like "programming is fun")

The type() Function

We can use the type() function to check a variable’s type.

[20]:
a = True
b = -1
c = 3.1415
d = "programming is fun"
print("the variable 'a' has type:", type(a))
print("the variable 'b' has type:", type(b))
print("the variable 'c' has type:", type(c))
print("the variable 'd' has type:", type(d))
the variable 'a' has type: <class 'bool'>
the variable 'b' has type: <class 'int'>
the variable 'c' has type: <class 'float'>
the variable 'd' has type: <class 'str'>