Variables, Constants and Keywords

Learn about variables and constants in Python, how to use them, and their importance in programming.

10 min read
Beginner

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:

python
# 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.

python
# 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 (_).
python
# Valid variable names
apple = 200
apple23 = 3
apple_APPLE = 21
PI = 3.14

Keep 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.
python
# Meaningful variable names
age = 25
weight = 80
height = 165
  • Variable names should not start with a digit.
python
# 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.
python
weight_kgs = 75
weight_lbs = 185
  • Variable names should not use special symbols other than an underscore (_).
python
# This will print out an error when run
weight&kgs = 75

Keywords

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 Examples
Python Keyword
Meaning
defUsed for creating a function in Python
globalUsed for declaring a global variable in Python
classUsed for creating a class in Python
TrueUsed for denoting a boolean
python
# This will print out an error when run
def = 200

That concludes our discussion on variables, constants and keywords in Python. In the next lesson, we will be discussing operators in Python.

Test your knowledge

🧠 Knowledge Check
1 / 10

What is a variable in Python?