Unit I: Introduction to Python
Learn the fundamentals of Python programming language
What is Python?
Python is a high-level, interpreted, general-purpose programming language created by Guido van Rossum and first released in 1991. Python's design philosophy emphasizes code readability with its notable use of significant whitespace.
Key Features of Python
- Easy to Learn: Python has a simple syntax similar to English, making it easy for beginners.
- Interpreted Language: Python code is executed line by line, making debugging easier.
- Cross-platform: Python runs on Windows, macOS, Linux, and many other platforms.
- Extensive Libraries: Python has a rich standard library and thousands of third-party packages.
- Dynamic Typing: You don't need to declare variable types explicitly.
- Object-Oriented: Python supports object-oriented programming paradigm.
Note
Python is named after the British comedy group "Monty Python," not the snake!
Your First Python Program
# This is your first Python program
print("Hello, World!")
# You can also print numbers
print(42)
# And perform calculations
print(10 + 20)
Python Variables
Variables are containers for storing data values. Unlike other programming languages, Python has no command for declaring a variable. A variable is created the moment you first assign a value to it.
Creating Variables
# Creating variables
name = "John" # String variable
age = 25 # Integer variable
height = 5.9 # Float variable
is_student = True # Boolean variable
# Printing variables
print("Name:", name)
print("Age:", age)
print("Height:", height)
print("Is Student:", is_student)
Variable Naming Rules
- A variable name must start with a letter or underscore character
- A variable name cannot start with a number
- Variable names can only contain alphanumeric characters and underscores (A-z, 0-9, _)
- Variable names are case-sensitive (age, Age and AGE are different variables)
# Valid variable names
my_name = "Alice"
myName = "Bob" # camelCase
MyName = "Charlie" # PascalCase
_private = "hidden"
name2 = "David"
CONSTANT_VALUE = 100
# Invalid variable names (will cause errors)
# 2name = "Error" # Cannot start with number
# my-name = "Error" # Cannot use hyphen
# my name = "Error" # Cannot have spaces
Multiple Assignment
# Assign same value to multiple variables
x = y = z = 50
print(x, y, z) # Output: 50 50 50
# Assign different values to multiple variables
a, b, c = 10, 20, 30
print(a, b, c) # Output: 10 20 30
# Swap variables
x = 5
y = 10
x, y = y, x
print("x =", x, "y =", y) # Output: x = 10 y = 5
Best Practice
Use descriptive variable names that explain what the variable holds. For example, use student_name instead of just n.
Python Basic Operators
Operators are used to perform operations on variables and values. Python divides operators into several groups:
1. Arithmetic Operators
| Operator | Name | Example | Result |
|---|---|---|---|
| + | Addition | 5 + 3 | 8 |
| - | Subtraction | 5 - 3 | 2 |
| * | Multiplication | 5 * 3 | 15 |
| / | Division | 5 / 3 | 1.666... |
| // | Floor Division | 5 // 3 | 1 |
| % | Modulus | 5 % 3 | 2 |
| ** | Exponentiation | 5 ** 3 | 125 |
# Arithmetic operators examples
a = 10
b = 3
print("Addition:", a + b) # 13
print("Subtraction:", a - b) # 7
print("Multiplication:", a * b) # 30
print("Division:", a / b) # 3.333...
print("Floor Division:", a // b) # 3
print("Modulus:", a % b) # 1
print("Power:", a ** b) # 1000
2. Comparison Operators
| Operator | Name | Example | Result |
|---|---|---|---|
| == | Equal | 5 == 5 | True |
| != | Not equal | 5 != 3 | True |
| > | Greater than | 5 > 3 | True |
| < | Less than | 5 < 3 | False |
| >= | Greater than or equal | 5 >= 5 | True |
| <= | Less than or equal | 5 <= 3 | False |
3. Assignment Operators
# Assignment operators
x = 10 # Assign
x += 5 # Add and assign (x = x + 5), x = 15
x -= 3 # Subtract and assign (x = x - 3), x = 12
x *= 2 # Multiply and assign (x = x * 2), x = 24
x /= 4 # Divide and assign (x = x / 4), x = 6.0
x //= 2 # Floor divide and assign, x = 3.0
x %= 2 # Modulus and assign, x = 1.0
x **= 3 # Power and assign, x = 1.0
print("Final value:", x)
4. Logical Operators
# Logical operators
a = True
b = False
print("a and b:", a and b) # False (both must be True)
print("a or b:", a or b) # True (at least one must be True)
print("not a:", not a) # False (reverses the value)
# Practical example
age = 25
has_license = True
can_drive = age >= 18 and has_license
print("Can drive:", can_drive) # True
5. Identity & Membership Operators
# Identity operators (is, is not)
x = [1, 2, 3]
y = [1, 2, 3]
z = x
print(x is z) # True (same object)
print(x is y) # False (different objects)
print(x == y) # True (same values)
print(x is not y) # True
# Membership operators (in, not in)
fruits = ["apple", "banana", "cherry"]
print("banana" in fruits) # True
print("grape" not in fruits) # True
# Also works with strings
name = "Python"
print("y" in name) # True
Understanding Python Blocks
In Python, blocks of code are defined by their indentation. Unlike other languages that use braces {}, Python uses whitespace to define the scope and extent of code blocks.
Indentation Rules
- Python uses indentation to define code blocks
- Standard indentation is 4 spaces (or 1 tab)
- All statements within a block must have the same indentation
- Mixing tabs and spaces can cause errors
# Python blocks example
age = 20
# Block starts after colon (:)
if age >= 18:
# This is inside the if block (4 spaces indentation)
print("You are an adult")
print("You can vote")
if age >= 21:
# Nested block (8 spaces indentation)
print("You can also drink in the US")
# This is outside the if block (no indentation)
print("Age verification complete")
# Function block example
def greet(name):
# Function body block
message = f"Hello, {name}!"
print(message)
return message
greet("Alice")
Common Error
Inconsistent indentation will cause an IndentationError. Always use consistent spacing throughout your code.
# WRONG - This will cause an error!
# if True:
# print("Hello")
# print("World") # IndentationError: unexpected indent
# CORRECT
if True:
print("Hello")
print("World") # Same indentation
Python Data Types
In Python, data types define what kind of value a variable can hold. Python has several built-in data types:
Categories of Data Types
| Category | Data Types | Example |
|---|---|---|
| Text | str | "Hello" |
| Numeric | int, float, complex | 10, 10.5, 3+4j |
| Sequence | list, tuple, range | [1,2,3], (1,2,3) |
| Mapping | dict | {"name": "John"} |
| Set | set, frozenset | {1, 2, 3} |
| Boolean | bool | True, False |
| Binary | bytes, bytearray, memoryview | b"Hello" |
| None | NoneType | None |
# Different data types in Python
# String
name = "Python"
print(type(name)) # <class 'str'>
# Integer
age = 30
print(type(age)) # <class 'int'>
# Float
price = 19.99
print(type(price)) # <class 'float'>
# Boolean
is_active = True
print(type(is_active)) # <class 'bool'>
# List
fruits = ["apple", "banana", "cherry"]
print(type(fruits)) # <class 'list'>
# Tuple
coordinates = (10, 20)
print(type(coordinates)) # <class 'tuple'>
# Dictionary
person = {"name": "John", "age": 30}
print(type(person)) # <class 'dict'>
# Set
unique_numbers = {1, 2, 3, 4, 5}
print(type(unique_numbers)) # <class 'set'>
# None
result = None
print(type(result)) # <class 'NoneType'>
Type Conversion
# Type conversion (Casting)
# String to Integer
num_str = "100"
num_int = int(num_str)
print(num_int + 50) # 150
# Integer to String
age = 25
age_str = str(age)
print("I am " + age_str + " years old")
# Float to Integer (truncates decimal)
price = 19.99
price_int = int(price)
print(price_int) # 19
# Integer to Float
count = 10
count_float = float(count)
print(count_float) # 10.0
# String to List
name = "Python"
letters = list(name)
print(letters) # ['P', 'y', 't', 'h', 'o', 'n']
# List to Tuple
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple) # (1, 2, 3)
Numeric Data Types
Python supports three types of numeric data:
1. Integer (int)
Integers are whole numbers without decimal points. They can be positive, negative, or zero.
# Integer examples
positive = 42
negative = -17
zero = 0
large_number = 123456789012345678901234567890 # No limit!
print(type(positive)) # <class 'int'>
# Different number systems
binary = 0b1010 # Binary (base 2) = 10
octal = 0o17 # Octal (base 8) = 15
hexadecimal = 0xFF # Hexadecimal (base 16) = 255
print(f"Binary 0b1010 = {binary}")
print(f"Octal 0o17 = {octal}")
print(f"Hex 0xFF = {hexadecimal}")
# Underscore for readability (Python 3.6+)
billion = 1_000_000_000
print(billion) # 1000000000
2. Float (float)
Floats are numbers with decimal points or numbers expressed in scientific notation.
# Float examples
pi = 3.14159
temperature = -40.5
small = 0.0001
print(type(pi)) # <class 'float'>
# Scientific notation
speed_of_light = 3e8 # 3 × 10^8 = 300000000.0
tiny = 1.5e-10 # 1.5 × 10^-10
print(f"Speed of light: {speed_of_light}")
print(f"Tiny number: {tiny}")
# Float precision warning
result = 0.1 + 0.2
print(result) # 0.30000000000000004 (floating point precision)
# For precise calculations, use decimal module
from decimal import Decimal
precise = Decimal('0.1') + Decimal('0.2')
print(precise) # 0.3
3. Complex Numbers (complex)
Complex numbers have a real and imaginary part, denoted by 'j'.
# Complex number examples
z1 = 3 + 4j
z2 = complex(2, 5) # 2 + 5j
print(type(z1)) # <class 'complex'>
print(z1.real) # 3.0 (real part)
print(z1.imag) # 4.0 (imaginary part)
# Complex arithmetic
z3 = z1 + z2
print(f"Sum: {z3}") # (5+9j)
z4 = z1 * z2
print(f"Product: {z4}") # (-14+23j)
# Absolute value (magnitude)
print(abs(z1)) # 5.0 (√(3² + 4²))
Useful Numeric Functions
# Built-in numeric functions
import math
# Basic functions
print(abs(-10)) # 10 (absolute value)
print(round(3.7)) # 4 (round to nearest)
print(round(3.14159, 2)) # 3.14 (round to 2 decimals)
print(pow(2, 3)) # 8 (power)
print(max(1, 5, 3)) # 5 (maximum)
print(min(1, 5, 3)) # 1 (minimum)
print(sum([1, 2, 3])) # 6 (sum of iterable)
# Math module functions
print(math.sqrt(16)) # 4.0 (square root)
print(math.ceil(3.2)) # 4 (ceiling)
print(math.floor(3.8)) # 3 (floor)
print(math.pi) # 3.141592653589793
print(math.e) # 2.718281828459045
print(math.sin(0)) # 0.0
print(math.log(10)) # 2.302... (natural log)
print(math.log10(100)) # 2.0
Pro Tip
Use the type() function to check the data type of any variable, and isinstance() to verify if an object is of a specific type.