Table of contents
A variable is a memory used to store values. This value is associated with the variable. The value is assigned to the variable using the assignment operator(=). Since Python is a dynamically typed language, it automatically recognizes the variable type. Therefore, we only need to declare the variable and assign a value to it.
hello = "Hello, World!"
print(hello)
#OUTPUT
Hello, World!
A variable is first declared, then initialized when a value is assigned to it. A variable can also be assigned to a new value, and the previous value is forgotten.
age = 5
print(age) #5
age = 10
print(age) #10
Variables are assigned to integers, strings, and floating points.
age = "5"
name = "Jane"
pi = "3.142"
In Python, we can also assign multiple variables to a single value or different values. This tells Python to assign the variables on the left side to their corresponding values on the right side.
# SINGLE VALUE
a = 10
b = 10
c = 10
#REWRITTEN AS
a = b = c = 10
#MULTIPLE VALUE
userName, userAge = "Jane", 5
print(userName, userAge)
#OUTPUT
#Jane 5
NAMING VARIABLES
When naming variables, there are a few rules you should follow. They are:
Variables can contain letters(A-Z, a-z), numbers(0-9), and underscores(_).
age = "5" greeting_1 = "Hi" my_name = "Jane" userName = "Jewel"
It should be noted that variables cannot begin with a number but can begin with an underscore.
_8 = "I am eight years old" print(8) #OUTPUT: #I am 8 years old
Spaces are not allowed between a variable name. Underscores can be used to separate words. Variables can also be named using camelCase.
#WRONG user name = "Jane" #RIGHT user_name = "Jane" userName = "Jane"
Avoid using reserved keywords when naming variables. Examples are print, range, for, ord, and so on. Other Reserved Keywords
Variable names must be short and descriptive. A good variable name describes what it stores.
#WRONG n = "Jane" #RIGHT name = "Jane"
Variables are case-sensitive and can be named with uppercase and lowercase letters. This means that "name", "NAME", and "Name" are three different variables.
CONCLUSION
In this article, you have learned how to declare and initialize variables in Python, and the rules when naming variables. You must make sure your Python program contains descriptive variable names to make your code readable and maintainable.
RESOURCES
Automate the boring stuff with Python(pdf)