What is a Variable?
Basic Syntax
To create a variable, you simply assign a value to it using the equals sign (=).
-
For example:
- name = "Alice"
- temperature = 22.5
- age = 30
Key Characteristics of Variables
1. Naming: Variable names can include letters, numbers, and underscores but cannot start with a number. Names are case-sensitive (age and Age are different).2. Data Types: Variables can hold different types of data, such as:
- Integers (int): Whole numbers (e.g., 42)
- Floats (float): Decimal numbers (e.g., 3.14)
- Strings (str): Text (e.g., "Hello")
- Booleans (bool): True or False values.
Examples on variables in python
Example 1: Storing Personal Information
Imagine you are storing information about a person:
name = "John Doe" age = 28 height = 5.9 # in feetis_student = True
Here, you’re using variables to store the name, age, height, and student status of a person.
Example 2: Calculating ExpensesIf you want to track your expenses for a week:
monday_expense = 20.50
tuesday_expense = 15.75
wednesday_expense = 30.00
total_expense = monday_expense + tuesday_expense + wednesday_expense
print("Total weekly expense:", total_expense)
This example shows how variables help you perform calculations and keep track of data.
Example 3: Inventory ManagementConsider a simple inventory system for a store:
item_name = "Apples"
item_price = 1.50
item_quantity = 100
total_value = item_price * item_quantity
print(f"Total value of {item_name}: ${total_value}")
Reassigning Variables
You can change the value of a variable at any time:
age = 30
print(age) # Output: 30
age = 31
print(age) # Output: 31
Variable Scope
Variables have different scopes, which define where they can be accessed.
There are two main types:
1. Local Variables: Variables defined inside a function. They can only be accessed within
that function.
2. Global Variables: Variables defined outside of any function. They can be accessed
throughout the entire program.
Example of Scope
def my_function():
local_var = 10 # Local variable
print(local_var)
my_function()
# print(local_var) # This would raise an error because local_var is not accessible here.
global_var = 20 # Global variable
def another_function():
print(global_var) # This can access global_var
another_function() # Output: 20