1. Python Variables
What is a Variable?
A variable in Python is like a labeled box where you can store data (e.g., numbers, text, or other values) to use later in your program. You can think of it as a name that points to a value, allowing you to reuse or modify that value easily.
Key Characteristics of Variables in Python
- Dynamic Typing: You don’t need to specify the type of data (e.g., integer, string) when creating a variable. Python figures it out automatically.
- Reusable: You can change the value of a variable at any time.
- Named by You: You choose the variable name, but it must follow certain rules (explained below).
Creating a Variable
To create a variable, you:
- Choose a name for the variable.
- Use the assignment operator (
=
) to assign a value to it. - The value can be a number, text, or other data.
Example:
# Creating a variable named 'age' and assigning it the value 25
age = 25
# Creating a variable named 'name' and assigning it the value "Alice"
name = "Alice"
# Printing the variables
print(age) # Output: 25
print(name) # Output: Alice
- Here,
age
is a variable storing the number25
, andname
stores the text"Alice"
. - The
=
operator assigns the value on the right to the variable name on the left.
Variable Naming Rules
To avoid errors, follow these rules when naming variables:
- Allowed Characters: Use letters (a-z, A-Z), digits (0-9), or underscores (
_
).
- Valid:
age
,my_name
,score2
- Invalid:
2score
,my-name
,my name
(spaces are not allowed)
- Start with a Letter or Underscore: Variable names cannot start with a digit.
- Valid:
name
,_count
- Invalid:
2name
- Case-Sensitive:
Age
andage
are different variables. - No Reserved Words: You can’t use Python keywords like
if
,for
, orprint
as variable names.
- Example:
print = 10
will cause an error becauseprint
is a built-in function.
- Descriptive Names: Use meaningful names to make your code readable.
- Good:
total_price
,user_name
- Bad:
x
,abc
(unless the context is clear)
Updating Variables
You can change a variable’s value by assigning a new value to it:
# Initial value
score = 100
print(score) # Output: 100
# Update the value
score = 200
print(score) # Output: 200
You can also update a variable based on its current value:
# Increase score by 50
score = score + 50
print(score) # Output: 250
Multiple Variables
You can assign multiple variables in one line:
# Assign multiple variables at once
x, y, z = 10, 20, 30
print(x) # Output: 10
print(y) # Output: 20
print(z) # Output: 30
Or assign the same value to multiple variables:
a = b = c = 5
print(a, b, c) # Output: 5 5 5
Real-World Example
Imagine you’re building a simple budget tracker:
# Variables for a budget tracker
item_name = "Coffee"
price = 5.50
quantity = 2
total_cost = price * quantity # Calculate total cost
print(f"You bought {quantity} {item_name}s for ${total_cost}") # Output: You bought 2 Coffees for $11.0
item_name
stores the item’s name (a string).price
stores the cost per item (a float).quantity
stores how many items (an integer).total_cost
calculates the total by multiplyingprice
andquantity
.
2. Python Literals
What is a Literal?
A literal is a raw value written directly in your code. It’s the actual data you assign to variables or use in expressions. Think of literals as the “ingredients” you put into your variable “boxes.”
Types of Literals in Python
Python supports several types of literals:
1. Numeric Literals
These represent numbers. They can be integers, floating-point numbers, or complex numbers.
- Integer Literals: Whole numbers (positive, negative, or zero).
age = 25 # Integer literal
negative = -10 # Negative integer literal
print(age, negative) # Output: 25 -10
- Float Literals: Numbers with a decimal point.
price = 19.99 # Float literal
temperature = -2.5 # Negative float literal
print(price, temperature) # Output: 19.99 -2.5
- Complex Literals: Numbers with a real and imaginary part (used in advanced math).
complex_num = 3 + 4j # Complex literal (3 is real, 4j is imaginary)
print(complex_num) # Output: (3+4j)
2. String Literals
These represent text, enclosed in single quotes ('
) or double quotes ("
).
- Single-Line Strings:
name = "Alice" # String literal with double quotes
greeting = 'Hello!' # String literal with single quotes
print(name, greeting) # Output: Alice Hello!
- Multi-Line Strings: Use triple quotes (
'''
or"""
) for text spanning multiple lines.
message = """This is a
multi-line
string literal."""
print(message)
# Output:
# This is a
# multi-line
# string literal.
3. Boolean Literals
These represent True
or False
, used for logical operations.
is_adult = True # Boolean literal
is_student = False # Boolean literal
print(is_adult, is_student) # Output: True False
4. None Literal
None
represents the absence of a value, like an empty box.
result = None # None literal
print(result) # Output: None
5. List, Tuple, Dictionary, and Set Literals
These are used for collections of data (we’ll focus on their literal forms here):
- List Literal: A collection of items in square brackets
[]
.
numbers = [1, 2, 3, 4] # List literal
print(numbers) # Output: [1, 2, 3, 4]
- Tuple Literal: An immutable collection in parenthesis
()
.
coordinates = (10, 20) # Tuple literal
print(coordinates) # Output: (10, 20)
- Dictionary Literal: Key-value pairs in curly braces
{}
.
person = {"name": "Bob", "age": 30} # Dictionary literal
print(person) # Output: {'name': 'Bob', 'age': 30}
- Set Literal: A collection of unique items in curly braces
{}
.
unique_nums = {1, 2, 2, 3} # Set literal (duplicates are removed)
print(unique_nums) # Output: {1, 2, 3}
Using Literals with Variables
Literals are often assigned to variables or used directly in expressions:
# Assign literals to variables
count = 42 # Integer literal
message = "Welcome" # String literal
is_active = True # Boolean literal
# Use literals directly in expressions
total = count + 8 # 8 is an integer literal
print(total) # Output: 50
print(message + " to Python!") # " to Python!" is a string literal
# Output: Welcome to Python!
Real-World Example with Variables and Literals
Let’s create a program simulating a simple shopping cart:
# Variables with literals
item = "Laptop" # String literal
price = 999.99 # Float literal
in_stock = True # Boolean literal
discount = 0.1 # Float literal (10% discount)
tax_rate = 0.08 # Float literal (8% tax)
# Calculate final price
subtotal = price * (1 - discount) # Apply 10% discount
tax = subtotal * tax_rate # Calculate tax
final_price = subtotal + tax # Total price
# Print details
print(f"Item: {item}") # Output: Item: Laptop
print(f"Subtotal after discount: ${subtotal:.2f}") # Output: Subtotal after discount: $899.99
print(f"Tax: ${tax:.2f}") # Output: Tax: $72.00
print(f"Final price: ${final_price:.2f}") # Output: Final price: $971.99
print(f"In stock: {in_stock}") # Output: In stock: True
- Variables:
item
,price
,in_stock
,discount
,tax_rate
,subtotal
,tax
,final_price
. - Literals:
"Laptop"
,999.99
,True
,0.1
,0.08
, etc. - The program uses variables and literals to calculate and display a shopping cart’s details.
Putting It All Together
- Variables: Think of them as labeled containers in a kitchen. You can store ingredients (data) in them, like sugar (
sugar = 2
) or flour (flour = "white"
), and use them in recipes (calculations). - Literals: These are the raw ingredients themselves, like the number
2
or the text"white"
, that you put into your containers or use directly in your cooking.
Practice Tasks
- Create a variable
city
and assign it the string literal"New York"
. Print it. - Create variables
length
andwidth
with integer literals (e.g.,10
and5
). Calculate and print the area (length * width
). - Write a program with variables
product
(string literal, e.g.,"Book"
),price
(float literal, e.g.,29.99
), andon_sale
(boolean literalTrue
). Print a message like:"Book is $29.99 and on sale: True"
. - Use a multi-line string literal to store a short description of yourself (e.g., name, age, hobby) and print it.
- Create a list literal with 3 of your favorite foods and assign it to a variable
favorites
. Print the list.
Example Solution for Task 3
# Shopping item details
product = "Book" # String literal
price = 29.99 # Float literal
on_sale = True # Boolean literal
print(f"{product} is ${price} and on sale: {on_sale}")
# Output: Book is $29.99 and on sale: True