Introduction
In this module, we will explore the foundational building blocks of Python: variables, data types, and operators. These concepts are essential for writing effective Python programs. By the end of this module, you will understand how to store and manipulate data using Python, perform arithmetic operations, and make logical comparisons.
1. Variables in Python
What is a Variable?
A variable is a named location in memory that stores a value. In Python, variables are dynamically typed, meaning you don’t need to declare their type explicitly. The type is inferred based on the assigned value.
Declaring and Assigning Variables
name = "Alice" # String variable
age = 25 # Integer variable
height = 5.7 # Float variable
is_student = True # Boolean variable
Python automatically assigns the appropriate data type based on the value assigned.
Rules for Naming Variables:
✅ Must start with a letter or an underscore (_
).
✅ Cannot start with a number.
✅ Can contain letters, numbers, and underscores (my_var
, _count
, age25
). ✅ Case-sensitive (age
and Age
are different variables).
✅ Avoid using Python keywords (class
, def
, return
, etc.).
Best Practices for Naming Variables:
- Use descriptive names:
user_name
instead ofx
. - Follow the snake_case convention:
total_price
,is_valid_user
. - Keep variable names concise but meaningful.
- Use uppercase names for constants:
PI = 3.14159
.
2. Data Types in Python
Python provides several built-in data types that help store and manipulate different kinds of data efficiently.
Data Type | Example | Description |
---|---|---|
int | 10 , -5 | Whole numbers (positive and negative) |
float | 3.14 , -2.5 | Decimal numbers |
str | 'Hello' , "Python" | Text (sequences of characters) |
bool | True , False | Boolean values (logical states) |
list | [1, 2, 3] | Ordered, mutable collection of items |
tuple | (1, 2, 3) | Ordered, immutable collection |
dict | { "name": "Alice", "age": 25 } | Key-value pairs for structured data |
set | {1, 2, 3} | Unordered collection of unique elements |
Checking Data Types
Use type()
to check the type of a variable:
x = 10
print(type(x)) # Output: <class 'int'>
Type Conversion (Casting)
Convert one data type to another using built-in functions:
x = 10 # Integer
y = float(x) # Convert to float
print(y) # Output: 10.0
Other conversions:
num = "50"
print(int(num)) # Converts string to integer (50)
print(str(123)) # Converts integer to string ('123')
print(bool(0)) # Converts 0 to False, any non-zero value is True
3. Operators in Python
Operators allow you to perform operations on variables and values.
Arithmetic Operators
Used for mathematical calculations:
a = 10
b = 3
print(a + b) # Addition (13)
print(a - b) # Subtraction (7)
print(a * b) # Multiplication (30)
print(a / b) # Division (3.33)
print(a // b) # Floor division (3)
print(a % b) # Modulus (1)
print(a ** b) # Exponentiation (1000)
Comparison Operators
Used for comparing values:
x = 5
y = 10
print(x == y) # False
print(x != y) # True
print(x > y) # False
print(x <= y) # True
Logical Operators
Used for logical conditions:
x = True
y = False
print(x and y) # False
print(x or y) # True
print(not x) # False
Assignment Operators
Used for assigning and updating values:
a = 5
b = 10
a += b # Same as a = a + b
print(a) # Output: 15
Mini Project: Simple Calculator
Project Steps:
- Ask the user for two numbers.
- Perform basic arithmetic operations (addition, subtraction, multiplication, and division).
- Display the results.
- Handle division by zero errors.
- Allow the user to choose an operation.
Code Example:
# Simple Calculator
print("Welcome to the Simple Calculator!")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
operation = input("Choose operation (+, -, *, /): ")
if operation == "+":
print(f"Result: {num1 + num2}")
elif operation == "-":
print(f"Result: {num1 - num2}")
elif operation == "*":
print(f"Result: {num1 * num2}")
elif operation == "/":
if num2 == 0:
print("Error! Division by zero is not allowed.")
else:
print(f"Result: {num1 / num2}")
else:
print("Invalid operation!")
Expected Output:
Welcome to the Simple Calculator!
Enter first number: 8
Enter second number: 2
Choose operation (+, -, *, /): /
Result: 4.0
Enhancements & Challenges:
✅ Modify the program to perform multiple calculations using a loop.
✅ Add more operations (exponentiation, modulus, floor division).
✅ Format output to display only two decimal places.
✅ Implement error handling for invalid inputs.
Conclusion
This module covered the fundamental concepts of variables, data types, and operators in Python. Mastering these basics will help you write efficient and effective Python programs.
🚀 Next Up: We will explore control flow in Python using conditional statements and loops!