Table of Contents
What are Variables in Python?
name = "John" print(name)
John
How to Declare Variables?
Variables are created by assigning a value using the assignment operator (=).variable_name = data you want to store
age = 20city = "Delhi"
Rules for Naming Variables
When creating or declaring variables in Python, follow these rules:1. Variable names should always start with a letter or underscore(_): A variable name should begin with a letter (A-Z, a-z) or an underscore (_). Starting a variable name with a number is not allowed in Python.
2. Variable names cannot contain special characters: Python variable names cannot contain special characters such as @, #, $, %, or &. Only letters, numbers, and underscores are allowed.Valid:
name = "Alex"
_age = 18
Invalid:
2name = "Alex"
#age = 18
3. Variable names are case-sensitive: These two variables are treated as different variables because Python is case-sensitive.Valid:
username = "John"
Invalid:
user@name = "John"
4. Avoid Python Keywords: Keywords such as if, for, print, and class cannot be used as variable names.name = "John"
Name = "Alex"
5. Variable Names Cannot Contain Spaces: Python does not allow spaces in variable names. If you need multiple words, use an underscore (_) instead.Valid:
couse_name = "python"
Invalid:
class = "python"
Invalid:
student name = "Rahul"
Valid:
student_name = "Rahul"
Types of Variables in Python
1. Integer Variable: Stores whole numbers without any decimal value. Integers are commonly used for counting, indexing, and mathematical operations.
Example:
2. Float Variable: Stores numbers that contain decimal points. Floats are useful when working with measurements, percentages, or scientific calculations.age = 18
Example:
3. String Variable: Stores text data enclosed in single, double, or triple quotes. Strings are used to represent names, messages, and other textual information.price = 99.99
Example:
4. Boolean Variable: Stores one of two values: True or False. Booleans are mainly used in decision-making and conditional statements.name = "Python"
Example:
5. List Variable: A list is used to store multiple values in a single variable. The values are enclosed within squareis_student = True
brackets []. Lists are ordered, mutable, and can contain different data types.
Example:
fruits = ["Apple", "Banana", "Mango"]
Below is the Python program to implement variables:
6. Tuple: Stores multiple values in a fixed, ordered collection. Unlike lists, tuples cannot be modified after creation.
Example:
coordinates = (10,20)
7. Set: Stores unique values without maintaining a specific order. Sets are useful for removing duplicates and performing set operations.
Example:
colors = {"red", "green", "blue"}
8. Dictionary: Stored data as key-value pairs. Dictionaries are widely used for representing structured information.
Example:
student = {"name": "John": "25"}
9. None Type: Represents the absence of a value. It is often used as a placeholder when a variable does not have a meaningful value yet.
Example:
result = None
Below is the Python program to implement variables:
# Python program to implement variables
# Integer Variable
age = 25
# Float Variable
salary = 55000.75
# String Variable
name = "Rashi"
# Boolean Variable
is_student = False
# List Variable
languages = ["Python", "Java", "C++"]
# Tuple Variable
coordinates = (10, 20)
# Set Variable
colors = {"Red", "Green", "Blue"}
# Dictionary Variable
student = {
"name": "Rashi",
"age": 25,
"course": "Python"
}
# None Variable
result = None
# Displaying Values and Data Types
print("Integer:", age, "Type:", type(age))
print("Float:", salary, "Type:", type(salary))
print("String:", name, "Type:", type(name))
print("Boolean:", is_student, "Type:", type(is_student))
print("List:", languages, "Type:", type(languages))
print("Tuple:", coordinates, "Type:", type(coordinates))
print("Set:", colors, "Type:", type(colors))
print("Dictionary:", student, "Type:", type(student))
print("None:", result, "Type:", type(result))
Output:
Integer: 25 Type: class 'int'
Float: 55000.75 Type: class 'float'
String: Rashi Type: class 'str'
Boolean: False Type: class 'bool'
List: ['Python', 'Java', 'C++'] Type: class 'list'
Tuple: (10, 20) Type: class 'tuple'
Set: {'Red', 'Blue', 'Green'} Type: class 'set'
Dictionary: {'name': 'Rashi', 'age': 25, 'course': 'Python'} Type: class 'dict'
None: None Type: class 'NoneType'
Explanation:
The above program demonstrates the most commonly used variable types in Python and prints both their values and corresponding data types using the type() function.
Multiple Variable Assignment
Syntax:
variable1, variable2, variable3 = value1, value2, value3
# Python program to implement multiple
# value assignment
name, age, city = "John", 25, "Delhi"
print("Name:", name)
print("Age:", age)
print("City:", city)
Output:
Name: John
Age: 25
City: Delhi
Example 2: Assigning same value
# Python program to assign same values x = y = z = 100 print(x) print(y) print(z)
100
100
100
Changing Variable Values
Syntax:
variable_name = new_value
# Python program to change variable value
# Initial value
age = 25
print("Before changing:", age)
# Changing the value
age = 30
print("After changing:", age)
Output:
Example 2: Changing Data TypeBefore changing: 25
After changing: 30
Python also allows a variable to store values of different data types.
# Python program to change variable data type value = 100 print(value) value = "Python" print(value)Output:
Explanation:100
Python
In this example, the variable value first stores an integer and later stores a string, demonstrating Python’s dynamic typing feature.
Importance of Variables
- Store and Manage Data: Variables help store different types of data, such as numbers, text, and collections, so they can be accessed and used throughout the program.
- Improve Code Readability: Meaningful variable names make programs easier to understand, debug, and maintain for both developers and learners.
- Enable Data Reusability: Once a value is stored in a variable, it can be used multiple times without rewriting the same value repeatedly.
- Support Dynamic Program Execution: Variables allow values to change during runtime, making programs interactive and capable of handling user input.
- Simplify Calculations and Operations: Variables make it easy to perform mathematical, logical, and data-processing operations by storing intermediate and final results.
Common Mistakes Beginners Make
1. Using Spaces in Variable Names: Variable names cannot contain spaces. Use an underscore (_) instead.2. Starting Variable Names with Numbers: A variable name cannot start with a number. It must begin with a letter or underscore.Wrong:
user name = "John"Correct:
user_name = "John"
3. Using Reserved Keywords: Python keywords cannot be used as variable names because they have special meanings in the language.Wrong:
123age = 18Correct:
age123 = 18
4. Using Variables Before Assigning a Value: A variable must be assigned a value before it can be used. Otherwise, Python will generate an error.Wrong:
class = "Python"Correct:
course_name = "Python"
5. Using Meaningless Variable Names: Beginners mostly use unclear variable names that make the code difficult to understand.Wrong:
print(name)Correct:
name = "Rahul"
print(name)
Poor Practice:
a = "Rahul"
b = 18Better Practice:
student_name = "Rahul"
student_age = 18
Conclusion
Frequently Asked Questions
1. What is a variable in Python?2. How do you create a variable in Python?A variable is a named container used to store data that can be accessed and modified during program execution.
3. Can the value of a variable be changed?A variable is created by assigning a value using the = operator.
4. Is Python case-sensitive for variables?Yes, variables in Python can be reassigned with new values at any time.
5. What types of data can variables store?Yes, name and Name are treated as different variables.
Variables can store integers, floats, strings, booleans, and many other data types.
0 Comments