Introduction to Python Variables
Variables are one of the first concepts you need to understand when learning Python. A variable allows you to give a name to a value so that you can use that value later in your program.
For example, imagine you are creating a student management program. You may need to store a student name, age, marks and course. Instead of writing these values repeatedly, you can store them in variables and reuse them whenever required.
Python makes variable creation simple. You do not need to declare the data type before assigning a value.
In this guide, you will learn how Python variables work, how to create and update them, which naming rules to follow, how to check their data types and how to use them in practical programs.
1. What Is a Variable in Python?
A variable is a name that refers to a value stored in a Python object.
Consider this example:
```python
name = "Rahul"
age = 22
city = "Delhi"
print(name)
print(age)
print(city)
```
Output:
Rahul
22
DelhiExplanation:
namerefers to the text value"Rahul".agerefers to the integer value22.cityrefers to the text value"Delhi".- The
print()function displays the values on the screen.
The equals sign (=) is called the assignment operator. It assigns the value on the right to the variable name on the left.
2. How to Create Variables in Python
You can create a variable simply by writing its name, an equals sign and a value.
Syntax:
variable_name = valueExample:
```python
product = "Laptop"
price = 55000
quantity = 2
print(product)
print(price)
print(quantity)
```
Output:
Laptop
55000
2Explanation:
Python creates each variable when the assignment statement runs. You do not need to write a separate declaration such as int price or string product.
This behaviour is part of Python dynamic typing.
3. Different Types of Values Stored in Variables
Python variables can refer to different kinds of values. The type depends on the value assigned to the variable.
String (str)
A string stores text. You can write strings using single or double quotation marks.
```python
student_name = "Aman"
course = "Python Programming"
print(student_name)
print(course)
```
Output:
Aman
Python ProgrammingExplanation: Both variables contain text values, so their data type is str.
Integer (int)
An integer stores whole numbers without a decimal point.
```python
age = 22
students = 45
year = 2026
print(age)
print(students)
print(year)
```
Output:
22
45
2026Explanation: All three values are whole numbers, so Python treats them as integers.
Float (float)
A float stores numbers with a decimal point.
```python
height = 5.9
price = 149.50
percentage = 87.5
print(height)
print(price)
print(percentage)
```
Output:
5.9
149.5
87.5Explanation: These values are floating-point numbers. Notice that Python may display 149.50 as 149.5 because the trailing zero is not needed.
Boolean (bool)
A Boolean variable stores one of two values: True or False.
```python
is_logged_in = True
is_admin = False
print(is_logged_in)
print(is_admin)
```
Output:
True
FalseExplanation: Boolean values are useful when a program needs to make decisions, such as checking whether a user is logged in.
NoneType
Python also has a special value called None. It represents the absence of a value.
```python
middle_name = None
print(middle_name)
print(type(middle_name))
```
Output:
None
<class 'NoneType'>Explanation: None is not the same as zero, an empty string or False. It is commonly used when a value is not available yet.
4. How to Check the Data Type of a Variable
Python provides the built-in type() function to identify the type of a value.
```python
name = "Priya"
age = 21
salary = 25000.50
is_student = True
print(type(name))
print(type(age))
print(type(salary))
print(type(is_student))
```
Output:
<class 'str'>
<class 'int'>
<class 'float'>
<class 'bool'>Explanation:
type(name)identifies a string.type(age)identifies an integer.type(salary)identifies a float.type(is_student)identifies a Boolean.
This is particularly useful when debugging a program or checking values received from user input.
5. Updating the Value of a Variable
A variable can be assigned a new value whenever your program needs it. The latest assignment becomes the current value associated with that name.
```python
score = 50
print(score)
score = 80
print(score)
score = 95
print(score)
```
Output:
50
80
95Explanation:
The first assignment stores 50. The second assignment changes the value to 80, and the third changes it to 95.
When you print score, Python displays its current value.
6. Assigning Multiple Variables in Python
Python allows you to assign values to multiple variables in one statement.
Assign Different Values
```python
name, age, city = "Rohit", 23, "Mumbai"
print(name)
print(age)
print(city)
```
Output:
Rohit
23
MumbaiExplanation: Each variable receives its corresponding value from left to right.
Assign the Same Value to Multiple Variables
```python
a = b = c = 100
print(a)
print(b)
print(c)
```
Output:
100
100
100Explanation: All three names are assigned the same integer value.
7. Rules for Naming Python Variables
Python allows flexible variable names, but you must follow certain rules.
- A variable name must begin with a letter or an underscore.
- A variable name cannot begin with a number.
- Variable names can contain letters, numbers and underscores.
- Spaces are not allowed in variable names.
- Python variable names are case-sensitive.
- Reserved Python keywords cannot be used as variable names.
Valid variable names:
name = "Amit"
student_age = 22
total_marks = 450
_private_value = 10
price2 = 500Invalid variable names:
# 2price = 500 # Cannot begin with a number
# student name = "A" # Spaces are not allowed
# class = "Python" # class is a reserved keywordExplanation:
Use meaningful names that explain what a variable represents. For example, total_price is easier to understand than tp.
8. Difference Between Variables and Constants
A variable is a name whose assigned value can be changed during program execution.
A constant is a value that programmers intend to keep unchanged. Python does not enforce constants through a special declaration, but uppercase naming is a common convention.
Variable example:
```python
price = 500
price = 700
print(price)
```
Output:
700Constant convention example:
```python
TAX_RATE = 0.18
MAX_ATTEMPTS = 3
print(TAX_RATE)
print(MAX_ATTEMPTS)
```
Output:
0.18
3Explanation: Uppercase names communicate that these values are intended to remain unchanged. Python will still allow you to reassign them.
9. Changing the Data Type of a Variable
Python provides functions such as int(), float() and str() to convert compatible values from one type to another.
Convert String to Integer
```python
age = "22"
age_number = int(age)
print(age_number)
print(type(age_number))
```
Output:
22
<class 'int'>Explanation: The original value is text. The int() function converts the numeric text into an integer.
Convert Integer to String
```python
number = 100
text_number = str(number)
print(text_number)
print(type(text_number))
```
Output:
100
<class 'str'>Explanation: The value is now a string, even though it looks like a number when printed.
Convert Integer to Float
```python
price = 250
decimal_price = float(price)
print(decimal_price)
print(type(decimal_price))
```
Output:
250.0
<class 'float'>Important: Conversion is not guaranteed to work for every value. For example, int("hello") raises a ValueError because the text does not represent an integer.
10. Taking User Input and Storing It in Variables
The input() function allows a program to receive information from a user. The value returned by input() is a string, so numeric input should be converted before mathematical calculations.
Example:
```python
name = input("Enter your name: ")
age = int(input("Enter your age: "))
print("Your name is:", name)
print("Your age is:", age)
```
Sample Output:
Enter your name: Aman
Enter your age: 22
Your name is: Aman
Your age is: 22Explanation:
input()displays a prompt and waits for the user.- The entered name is stored in
name. int()converts the age entered as text into an integer.print()displays the stored information.
If the user enters non-numeric text for age, the conversion will fail. A production program should validate user input before converting it.
11. Practical Example: Calculate the Total Price
Variables are useful in everyday programs. Consider a shopping example where a customer buys three notebooks.
```python
product_name = "Notebook"
price = 50
quantity = 3
total_price = price * quantity
print("Product:", product_name)
print("Price per item:", price)
print("Quantity:", quantity)
print("Total price:", total_price)
```
Output:
Product: Notebook
Price per item: 50
Quantity: 3
Total price: 150Explanation:
The program stores the product name, unit price and quantity in separate variables. It multiplies the price by the quantity and stores the result in total_price.
Formula:
Total Price = Price per Item × Quantity
Total Price = 50 × 3
Total Price = 150This is a simple example of how variables help organize data and perform calculations.
12. Common Mistakes When Using Python Variables
Using a Variable Before Assigning a Value
Incorrect example:
print(total)Output:
NameError: name 'total' is not definedExplanation: Python cannot find a value assigned to the name total. Assign a value before using the variable.
Correct example:
total = 500
print(total)Output:
500Confusing Uppercase and Lowercase Names
```python
name = "Aman"
Name = "Rahul"
print(name)
print(Name)
```
Output:
Aman
RahulExplanation: Python is case-sensitive. name and Name are two different variable names.
Adding a String and an Integer Directly
Incorrect example:
age = 22
message = "Age: " + age
print(message)Output:
TypeErrorExplanation: Python does not automatically combine a string and an integer with the + operator.
Correct example:
```python
age = 22
message = "Age: " + str(age)
print(message)
```
Output:
Age: 22You can also use an f-string:
age = 22
print(f"Age: {age}")Output:
Age: 2213. Best Practices for Writing Python Variables
Follow these practices to make your programs easier to read and maintain:
- Choose descriptive names such as
student_nameandtotal_price. - Use lowercase letters and underscores for ordinary variable names.
- Avoid unnecessary one-letter names except for short, familiar cases such as loop counters.
- Use uppercase names for values intended to act as constants.
- Do not use Python keywords as variable names.
- Convert and validate user input before performing calculations.
- Keep variable names consistent throughout a project.
Readable variable names make debugging and collaboration easier, especially when a program becomes larger.
14. Frequently Asked Questions
What is a variable in Python?
A variable is a name that refers to a value. It allows you to store and reuse information in a program.
Do Python variables need to be declared?
No. You can create a variable by assigning a value to a name. Python determines the type from the assigned value.
Can a Python variable change its data type?
Yes. A name can refer to values of different types at different times.
```python
value = 100
print(type(value))
value = "Hello"
print(type(value))
```
Output:
<class 'int'>
<class 'str'>What is the difference between int and float?
int represents whole numbers such as 10 and 250. float represents numbers with a decimal component, such as 10.5 and 250.75.
What does the type() function do?
The type() function returns the type of an object. It helps identify whether a value is a string, integer, float, Boolean or another Python type.
Can two variables have the same value?
Yes. For example, a = 10 and b = 10 assign the same integer value to two different names.
What happens if a variable is used before assignment?
Python raises a NameError if the name has not been defined in the current scope.
Are Python variables case-sensitive?
Yes. age, Age and AGE are treated as different names.
Conclusion
Python variables are the foundation of programming because they allow you to store, organize and reuse information. By understanding assignment, data types, naming rules, type conversion and user input, you can start writing useful Python programs.
Practise the examples in a Python interpreter and try changing the values to see how the output changes. Once you are comfortable with variables, continue learning about Python operators, conditions, loops and functions.
Recommended next topics:
- Learn Python for Beginners
- Python Data Types Explained
- Python Operators with Examples
- Python If-Else Statements
- Python Loops for Beginners
Official learning resource: https://docs.python.org/3/tutorial/introduction.html
You’ve reached the end of this guide. Explore more tutorials on PrimeProblem.