Variable Assignments in Python
This blog post is part of our course Python Tutorial for Ultimate Beginners.
Now that we’ve seen how to use numbers in Python as a calculator let’s see how we can assign names and create variables.
We use a single equals sign to assign labels to variables. Let’s see a few examples of how we can do this.
# Let's create an object called "a" and assign it the number
5 >>> a = 5
Now if I call in my Python script, Python will treat it as the number 5.
# Adding the objects
>>> a+a
10
What happens on reassignment? Will Python let us write it over?
# Reassignment
>>> a = 10
# Check
>>> print(a)
10
Rules for variable names
- names can not start with a number
- names can not contain spaces, use _ instead
- names can not contain any of these symbols as
:'",<>/?|!@#%^&*~-+
- it’s considered best practice (PEP8) that names are lowercase with underscores
- avoid using Python built-in keywords like list and str
- avoid using the single characters
l
(lowercase letter el),O
(uppercase letter oh) andI
(uppercase letter eye) as they can be confused with1
and0
.
Dynamic Typing
Python uses dynamic typing, meaning you can reassign variables to different data types. This makes Python very flexible in assigning data types; it differs from other languages that are statically typed.
>>> my_dogs = 2
>>> print(my_dogs)
2>>> my_dogs = ['Sammy', 'Frankie']
>>> print(my_dogs)
['Sammy', 'Frankie']
Determining variable type with type()
You can check what type of object is assigned to a variable using Python’s built-in type() function. Common data types include:
>>> a = 2
>>> print(type(a))
int
Originally published at https://blog.upendra.tech on June 3, 2020.