Variables, Constants and Keywords
Learn about variables and constants in Python, how to use them, and their importance in programming.
Variables in Python
A variable in Python is a symbolic name that points to the location where data is stored in memory.
Let us understand this with an example:
# Assigning a variable
var1 = 200
# Printing var1
print(var1)In the example above, the value 200 is being pointed by the variable called var1. You can also update the value of a variable as shown below.
# Updating the value of var1
var1 = 200
var1 = 30
print(var1)Variable naming conventions
In order to properly name a variable in Python, we must follow a set of rules like in any other programming languages. Here are a list of rules and best practises:
- Variables names should only consist of a combination of lowercase letters (a-z) or uppercase letters (A-Z) or digits (0-9) or an underscore (_).
# Valid variable names
apple = 200
apple23 = 3
apple_APPLE = 21
PI = 3.14Keep in mind that in Python, a constant is a variable whose value is not meant to be changed. The general practice for declaring a constant is by using uppercase letters for the variable name (like we have done for PI above).
- A meaningful word should be used as a variable name based on the value it points to.
# Meaningful variable names
age = 25
weight = 80
height = 165- Variable names should not start with a digit.
# This will print out an error when run
22age = 25- Variable names consisting of two or more words should have an underscore (_) in between them according to best practises.
weight_kgs = 75
weight_lbs = 185- Variable names should not use special symbols other than an underscore (_).
# This will print out an error when run
weight&kgs = 75Keywords
Keywords are case-sensitive words in Python that have a Python-specific meaning. Such keywords cannot be used as variable names and are reserved by the Python programming language.
Since keywords define the syntax and structure of Python, they are large in number and remembering all of them is very hard when starting out. The correct way to memorize such keywords is by actually using them in Python and we will be doing so throughout the course.
But, for now, here are some example Python keywords along with their meaning:
Python Keyword | Meaning |
|---|---|
| def | Used for creating a function in Python |
| global | Used for declaring a global variable in Python |
| class | Used for creating a class in Python |
| True | Used for denoting a boolean |
# This will print out an error when run
def = 200That concludes our discussion on variables, constants and keywords in Python. In the next lesson, we will be discussing operators in Python.