A4. Python Variables, Constants and Literals


In this docs, we will learn about Python variables, constants, and literals with examples.

Python Variable

In any programming language, we can assign values to a variable, which is like a memory allocation. For example:

x = 200

Here, 200 (Integer) will be stored in the variable name ‘x’. X is used as an identifier, for a memory storage block.

Assigning values to Variables in Python

As we can see from the above example, we use the assignment operator = to assign a value to a variable.

# assign value to name variable
name = 'Elon Musk'

print(name)

# Output: Elon Musk

In the above example, we assigned the value ‘Elon Musk’ to the variable name. Then, we printed out the value assigned to name variable.

Please note that: Python is a type-inferred language, which means that it automatically recognizes the data type of a variable without the need for explicit definition. For example, when the variable ‘site_name’ is assigned the value ‘Elon Musk’, Python recognizes this as a string and declares the variable as such.

How to change the Value of a Variable in Python


name = 'Elon Musk'
print(name)

# assigning a new value to name
name = 'Jeff Bezos'

print(name)

Output:

Elon musk
Jeff Bezos

Here, the value of site_name is changed from ‘Elon musk’ to ‘Jeff Bezos’.

Example: Assigning multiple values to multiple variables


a, b, c = 50, 322.2, 'Elon musk'

print(a)  # prints 50 
print(b)  # prints 322.2
print(c)  # prints Elon musk 

We can also assign the same value to multiple variables at once, we can do this as:

a = b = 'elon musk'

print(a)  # prints elon musk
print(b)  # prints elon musk

Here, we have assigned the same string value ’elon musk’ to both variables a and b.


10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co

Rules for Naming Python Variables

In Python, variable names must follow a few simple rules:

  1. Variable names can only contain letters, numbers, and underscores. They cannot begin with a number.
snake_case
MACRO_CASE
camelCase
CapWords
  1. Variable names are case-sensitive, so ‘myVariable’ and ‘myvariable’ are considered different variables.
var num = 5 
var Num = 55
print(num) # 5
print(Num) # 55
  1. Variable names cannot be one of Python’s reserved words, such as ‘if’, ’else’, ‘while’, ‘for’, etc.

  2. Variable names should be descriptive and meaningful so that it is easy to understand their purpose when reading the code.

  3. It is a good practice to start variable names with a lowercase letter, and use uppercase letters to separate words in multi-word variable names, such as “myVariable” or “variable_name” Avoid using single-letter variable names like “x” and “y”

It’s also worth noting that, while not technically a rule, it is a convention in Python to use snake_case (lowercase letters separated by underscores) when naming variables and functions.

Python Constants

A constant is a type of variable that maintains a fixed value and cannot be altered.

In Python, constants are typically defined and assigned within a module, which is a separate file containing variables, functions, and other elements that can be imported into the main program.

For example, we can create a “constant.py” file to declare and assign our constants, and then import and use them in the main program.

# declare constants 
PI = 3.14
GRAVITY = 9.8
PI = 3.14
MAX_SPEED = 300
DEFAULT_COLOR = "\033[1;34m"
WIDTH = 20
API_TOKEN = "593086396372"
BASE_URL = "https://api.example.com"
DEFAULT_TIMEOUT = 5

main.py

Create a main.py:
# import constant file we created above
import constant

print(constant.PI) # prints 3.14
print(constant.GRAVITY) # prints 9.8
print(constant.MAX_SPEED) # prints 300
print(constant.WIDTH) # prints 20

In this example, we created a module file called constant.py and assigned the values of PI and GRAVITY and other constants like MAX_SPEED, DEFAULT_COLOR, WIDTH, API_TOKEN, DEFAULT_TIMEOUT.

We then created a main.py file and imported the constant module. Finally, we printed the constant values.

Python Literals

In a program, literals are fixed values that can be represented as numbers, characters, strings, and more.

Some examples include

  1. ‘Hello, World!’,
  2. 100,
  3. 45.0, and
  4. ‘X’. These literals are commonly used to assign values to variables or constants, such as assigning the value 12 to a variable named “age” or the string ‘Hello, World!’ to a constant named “greeting”.
name = 'elon musk'

In the above expression, name is a variable, and ’elon musk’ is literal.


10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co

Python Numeric Literals

Numeric literals, which cannot be altered i.e immutable, can be categorized into three distinct types: Integer, Float, and Complex.

TypeExampleExplanation
Decimal5, 10, -68Regular numbers.
Binary0b101, 0b11Start with 0b.
Octal0o13Start with 0o.
Hexadecimal0x13Start with 0x.
Floating-point Literal10.5, 3.14Containing floating decimal points.
Complex Literal6 + 9jNumerals in the form a + bj, where a is real and b is imaginary part

10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co

Python Boolean Literals

There are two boolean literals: True and False.

For example :

pass = true  
## Here, true is a boolean literal assigned to pass.

String and Character Literals in Python

Character literals are Unicode characters enclosed in a quote.

For example,

charaterExample = 'S'
## Here, S is a character literal assigned to charaterExample.

Similarly, String literals are sequences of Characters enclosed in quotation marks.

For example :

some_string = 'Python is fun' 
## Here, 'Python is fun' is a string literal assigned to some_string.

Special Literal in Python

Python contains one special literal None. We use it to specify a null variable. For example :

value = None

print(value)

Output: None

Run Code Here, we get None as an output as the value variable has no value assigned to it.

Literal Collections There are four different literal collections List literals, Tuple literals, Dict literals, and Set literals.

list literal

fruits = ["apple", "sony", "tesla"] 
print(fruits)

tuple literal

numbers = (10, 20, 30) 
print(numbers)

dictionary literal

alphabets = {'a':'apple', 'b':'sony', 'c':'tesla'} 
print(alphabets)

set literal

vowels = {'a', 'e', 'i' , 'o', 'u'} 
print(vowels)

Output :


['apple', 'sony', 'tesla']
(10, 20, 30)
{'a': 'apple', 'b': 'sony', 'c': 'tesla'}
{'e', 'a', 'o', 'i', 'u'}

In the example above, we constructed a list containing different types of fruits, a tuple containing numerical values, a dictionary associating alphabets with designated keys and values, and a set comprising vowels.


10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co