Python Variables, Constants, and Literals – A Comprehensive Guide
Python Variables, Constants, and Literals
Master the fundamentals of Python data storage: learn how to declare and manipulate variables, use constants, and work with various literal types in practical examples.
Video: Python Variables and print()
Watch the tutorial on how to use variables with the print() function for clear output in your scripts.
Python Variables
A variable is a named reference that holds a value in memory. Think of it as a container that can be updated as your program runs. For example:
number = 10
Here, number is assigned the integer value 10. Later, the value can change:
number = 10
number = 1.1
Initially number held 10; it was then overwritten with 1.1. In Python, variables store references to objects rather than the objects themselves.
Assigning Values to Variables in Python
Use the assignment operator = to bind a value to a variable name.
Example 1: Declaring and Assigning a Value
website = "apple.com"
print(website)
Output
apple.com
Python automatically infers the type; website is a string because the value is surrounded by quotes.
Example 2: Changing the Value of a Variable
website = "apple.com"
print(website)
# Reassign a new value
website = "programiz.com"
print(website)
Output
apple.com programiz.com
Example 3: Assigning Multiple Values to Multiple Variables
a, b, c = 5, 3.2, "Hello"
print(a)
print(b)
print(c)
Assigning the same value to several variables simultaneously:
x = y = z = "same"
print(x)
print(y)
print(z)
Constants
A constant is a variable whose value is intended to remain unchanged throughout the program. In Python, constants are a convention rather than a language feature: you name them in all caps to signal their immutability.
Example 4: Declaring Constants in a Module
Create a file constants.py:
PI = 3.14159
GRAVITY = 9.8
Then, use them in main.py:
import constants
print(constants.PI)
print(constants.GRAVITY)
Output
3.14159 9.8
While Python does not enforce immutability, the naming convention helps maintain code clarity and prevents accidental reassignment.
Naming Rules & Conventions
- Variable and constant names may contain letters (a‑z, A‑Z), digits (0‑9), and underscores (
_), but must not start with a digit. - Use descriptive names: vowel is clearer than v.
- Separate words with underscores for readability:
current_salary. - Constants are usually in all caps:
PI,SPEED_OF_LIGHT. - Avoid special symbols such as
!,@,#,$, etc. - Never begin a name with a number.
Literals
A literal represents raw data in source code. Python supports several literal types, each with its own syntax and semantics.
Numeric Literals
Numeric literals are immutable and come in three primary forms: integers, floats, and complex numbers.
Example 5: Using Various Numeric Literals
a = 0b1010 # Binary
b = 100 # Decimal
c = 0o310 # Octal
d = 0x12c # Hexadecimal
float_1 = 10.5
float_2 = 1.5e2 # Scientific notation
x = 3.14j # Complex
print(a, b, c, d)
print(float_1, float_2)
print(x, x.imag, x.real)
Output
10 100 200 300 10.5 150.0 3.14j 3.14 0.0
String Literals
Strings are sequences of characters enclosed in single, double, or triple quotes. A single character surrounded by quotes is a character literal.
Example 6: Working with Strings
strings = "This is Python"
char = "C"
multiline_str = """This is a multiline string with more than one line code."""
unicode = u"\u00dcnic\u00f6de"
raw_str = r"raw \n string"
print(strings)
print(char)
print(multiline_str)
print(unicode)
print(raw_str)
Output
This is Python C This is a multiline string with more than one line code. Ünicöde raw \n string
Boolean Literals
Boolean literals are True and False, which internally map to integer values 1 and 0.
Example 7: Using Boolean Literals
x = (1 == True)
y = (1 == False)
a = True + 4
b = False + 10
print("x is", x)
print("y is", y)
print("a:", a)
print("b:", b)
Output
x is True y is False a: 5 b: 10
Special Literals
The None literal represents the absence of a value.
Example 8: Using None
drink = "Available"
food = None
def menu(x):
if x == drink:
print(drink)
else:
print(food)
menu(drink)
menu(food)
Output
Available None
Literal Collections
Python provides four core collection types: lists, tuples, dictionaries, and sets.
Example 9: Using Collection Literals
fruits = ["apple", "mango", "orange"] # List
numbers = (1, 2, 3) # Tuple
alphabets = {'a':"apple", 'b':"ball", 'c':"cat"} # Dictionary
vowels = {'a', 'e', 'i', 'o', 'u'} # Set
print(fruits)
print(numbers)
print(alphabets)
print(vowels)
Output
['apple', 'mango', 'orange']
(1, 2, 3)
{'a': 'apple', 'b': 'ball', 'c': 'cat'}
{'e', 'a', 'o', 'i', 'u'}
For deeper dives into numeric types and data structures, refer to the official Python Tutorial and Standard Library Reference.
Python
- Mastering C++ Variables, Literals, and Constants: A Comprehensive Guide
- C Variables, Constants, and Literals: A Complete Guide
- Python Keywords and Identifiers: Mastering Reserved Words and Naming Conventions
- Python Namespaces & Variable Scope: Understanding Names, Bindings, and Scopes
- Understanding Python Global, Local, and Nonlocal Variables
- Java Variables and Literals: A Comprehensive Guide
- Understanding C Constants and Literals: Types, Usage, and Best Practices
- C++ Constants & Literals Explained: Types, Syntax, and Best Practices
- Mastering C# Constants & Literals: Types, Rules, and Best Practices
- Python Variable Types: Understanding and Using Data Types