Variables and Constants in Python Tutorial

8/16/2025
All Articles

Variables and constants in Python tutorial for beginners

Variables and Constants in Python Tutorial

Variables and Constants in Python Tutorial


Introduction

In Python, variables and constants are fundamental concepts that every programmer should understand. They allow you to store, reuse, and manage data efficiently. This tutorial covers the basics of variables and constants in Python with clear explanations and examples.


What are Variables in Python?

A variable is a container that holds data. Unlike some programming languages, Python variables don’t require explicit declaration of type. The type is determined automatically at runtime.

Rules for Naming Variables

  • Must start with a letter or underscore.

  • Cannot start with a number.

  • Can only contain letters, numbers, and underscores.

  • Case-sensitive (e.g., Name and name are different).

Example of Variables:

# Declaring variables
name = "John"
age = 25
is_student = True

print(name)       # Output: John
print(age)        # Output: 25
print(is_student) # Output: True

What are Constants in Python?

In Python, there is no direct keyword for constants, but by convention, we use uppercase letters to define constants.

Example of Constants:

# Defining constants
PI = 3.14159
GRAVITY = 9.8

print(PI)      # Output: 3.14159
print(GRAVITY) # Output: 9.8

Note: Even though constants can be changed in Python, it is considered a bad practice.


Difference Between Variables and Constants

Feature Variables Constants
Definition Store values that can change Store fixed values
Declaration Normal assignment (x = 10) Uppercase naming (PI=3.14)
Mutability Mutable (can be reassigned) Should not be changed

Best Practices

  1. Use meaningful variable names (e.g., student_name instead of x).

  2. Keep constants in uppercase for clarity.

  3. Follow PEP8 guidelines for naming conventions.


Conclusion

Understanding variables and constants in Python is the first step toward mastering programming. Variables store dynamic values, while constants store fixed values that should not change throughout the program. By practicing these basics, you’ll build a solid foundation for more advanced Python concepts.

 

Article