python
examples
examples.py🐍python
"""
01 - Python Basics: Examples
Run this file to see all examples in action!
"""
print("=" * 60)
print("PYTHON BASICS - EXAMPLES")
print("=" * 60)
# =============================================================================
# 1. VARIABLES AND DATA TYPES
# =============================================================================
print("\n--- 1. Variables and Data Types ---\n")
# Creating variables (no type declaration needed!)
name = "Alice" # String - text data
age = 25 # Integer - whole numbers
height = 5.6 # Float - decimal numbers
is_student = True # Boolean - True/False
nothing = None # None - represents no value
print(f"Name: {name} (type: {type(name).__name__})")
print(f"Age: {age} (type: {type(age).__name__})")
print(f"Height: {height} (type: {type(height).__name__})")
print(f"Is Student: {is_student} (type: {type(is_student).__name__})")
print(f"Nothing: {nothing} (type: {type(nothing).__name__})")
# Multiple assignment
x, y, z = 10, 20, 30
print(f"\nMultiple assignment: x={x}, y={y}, z={z}")
# Same value to multiple variables
a = b = c = 100
print(f"Same value: a={a}, b={b}, c={c}")
# =============================================================================
# 2. INPUT AND OUTPUT
# =============================================================================
print("\n--- 2. Input and Output ---\n")
# Different print styles
print("Hello, World!") # Simple print
print("Item1", "Item2", "Item3") # Multiple values
print("a", "b", "c", sep=" - ") # Custom separator
print("Line 1", end=" | ") # Custom end
print("Line 2")
# Formatted output (f-strings - the modern way!)
user_name = "Bob"
user_age = 30
print(f"Hello, {user_name}! You are {user_age} years old.")
# Format specifiers
price = 49.99
print(f"Price: ${price:.2f}") # 2 decimal places
print(f"Price: ${price:10.2f}") # Right-aligned, width 10
print(f"Price: ${price:<10.2f}") # Left-aligned, width 10
# NOTE: Uncomment below to test input()
# user_input = input("Enter your name: ")
# print(f"Hello, {user_input}!")
# =============================================================================
# 3. ARITHMETIC OPERATORS
# =============================================================================
print("\n--- 3. Arithmetic Operators ---\n")
a, b = 17, 5
print(f"a = {a}, b = {b}")
print(f"a + b = {a + b}") # Addition: 22
print(f"a - b = {a - b}") # Subtraction: 12
print(f"a * b = {a * b}") # Multiplication: 85
print(f"a / b = {a / b}") # Division: 3.4 (float result)
print(f"a // b = {a // b}") # Floor Division: 3 (integer result)
print(f"a % b = {a % b}") # Modulus: 2 (remainder)
print(f"a ** b = {a ** b}") # Exponentiation: 1419857
# =============================================================================
# 4. COMPARISON OPERATORS
# =============================================================================
print("\n--- 4. Comparison Operators ---\n")
x, y = 10, 5
print(f"x = {x}, y = {y}")
print(f"x == y: {x == y}") # Equal: False
print(f"x != y: {x != y}") # Not equal: True
print(f"x > y: {x > y}") # Greater than: True
print(f"x < y: {x < y}") # Less than: False
print(f"x >= y: {x >= y}") # Greater or equal: True
print(f"x <= y: {x <= y}") # Less or equal: False
# =============================================================================
# 5. LOGICAL OPERATORS
# =============================================================================
print("\n--- 5. Logical Operators ---\n")
p, q = True, False
print(f"p = {p}, q = {q}")
print(f"p and q: {p and q}") # False (both must be True)
print(f"p or q: {p or q}") # True (at least one True)
print(f"not p: {not p}") # False (inverts)
print(f"not q: {not q}") # True
# Practical example
age = 25
has_license = True
can_drive = age >= 18 and has_license
print(f"\nAge: {age}, Has License: {has_license}")
print(f"Can Drive: {can_drive}")
# =============================================================================
# 6. ASSIGNMENT OPERATORS
# =============================================================================
print("\n--- 6. Assignment Operators ---\n")
num = 100
print(f"Initial: num = {num}")
num += 10 # num = num + 10
print(f"num += 10: {num}")
num -= 20 # num = num - 20
print(f"num -= 20: {num}")
num *= 2 # num = num * 2
print(f"num *= 2: {num}")
num /= 3 # num = num / 3
print(f"num /= 3: {num}")
num //= 2 # num = num // 2
print(f"num //= 2: {num}")
num **= 2 # num = num ** 2
print(f"num **= 2: {num}")
# =============================================================================
# 7. BITWISE OPERATORS
# =============================================================================
print("\n--- 7. Bitwise Operators ---\n")
a, b = 5, 3
print(f"a = {a} (binary: {bin(a)})")
print(f"b = {b} (binary: {bin(b)})")
print(f"a & b = {a & b} (binary: {bin(a & b)})") # AND
print(f"a | b = {a | b} (binary: {bin(a | b)})") # OR
print(f"a ^ b = {a ^ b} (binary: {bin(a ^ b)})") # XOR
print(f"~a = {~a}") # NOT
print(f"a << 1 = {a << 1}") # Left shift
print(f"a >> 1 = {a >> 1}") # Right shift
# =============================================================================
# 8. IDENTITY AND MEMBERSHIP OPERATORS
# =============================================================================
print("\n--- 8. Identity and Membership Operators ---\n")
# Identity operators (is, is not)
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1
print(f"list1: {list1}")
print(f"list2: {list2}")
print(f"list3: {list3}")
print(f"list1 is list2: {list1 is list2}") # False (different objects)
print(f"list1 is list3: {list1 is list3}") # True (same object)
print(f"list1 == list2: {list1 == list2}") # True (same values)
# Membership operators (in, not in)
fruits = ["apple", "banana", "cherry"]
print(f"\nfruits: {fruits}")
print(f"'apple' in fruits: {'apple' in fruits}")
print(f"'mango' in fruits: {'mango' in fruits}")
print(f"'mango' not in fruits: {'mango' not in fruits}")
# =============================================================================
# 9. TYPE CASTING
# =============================================================================
print("\n--- 9. Type Casting ---\n")
# String to numbers
str_num = "42"
int_num = int(str_num)
float_num = float(str_num)
print(f"String '{str_num}' → int: {int_num}, float: {float_num}")
# Number to string
number = 123
str_number = str(number)
print(f"Number {number} → String: '{str_number}'")
# Float to int (truncates)
pi = 3.99999
truncated = int(pi)
print(f"Float {pi} → int: {truncated} (truncated, not rounded!)")
# Boolean conversions
print(f"\nbool(0): {bool(0)}") # False
print(f"bool(1): {bool(1)}") # True
print(f"bool(-5): {bool(-5)}") # True (any non-zero)
print(f"bool(''): {bool('')}") # False (empty string)
print(f"bool('Hi'): {bool('Hi')}") # True
print(f"bool([]): {bool([])}") # False (empty list)
print(f"bool([1,2]): {bool([1,2])}") # True
# =============================================================================
# 10. MATH FUNCTIONS
# =============================================================================
print("\n--- 10. Math Functions ---\n")
# Built-in math functions
print("Built-in functions:")
print(f"abs(-42) = {abs(-42)}")
print(f"round(3.7) = {round(3.7)}")
print(f"round(3.14159, 2) = {round(3.14159, 2)}")
print(f"pow(2, 8) = {pow(2, 8)}")
print(f"min(5, 2, 8, 1) = {min(5, 2, 8, 1)}")
print(f"max(5, 2, 8, 1) = {max(5, 2, 8, 1)}")
print(f"sum([1, 2, 3, 4, 5]) = {sum([1, 2, 3, 4, 5])}")
print(f"divmod(17, 5) = {divmod(17, 5)}") # (quotient, remainder)
# Math module
import math
print("\nMath module functions:")
print(f"math.pi = {math.pi}")
print(f"math.e = {math.e}")
print(f"math.sqrt(64) = {math.sqrt(64)}")
print(f"math.ceil(3.2) = {math.ceil(3.2)}")
print(f"math.floor(3.8) = {math.floor(3.8)}")
print(f"math.factorial(5) = {math.factorial(5)}")
print(f"math.gcd(48, 18) = {math.gcd(48, 18)}")
print(f"math.log10(1000) = {math.log10(1000)}")
print(f"math.sin(math.pi/2) = {math.sin(math.pi/2)}")
# =============================================================================
# 11. PRACTICAL EXAMPLES
# =============================================================================
print("\n--- 11. Practical Examples ---\n")
# Example 1: Calculate area of a circle
radius = 5
area = math.pi * radius ** 2
print(f"Circle with radius {radius}: Area = {area:.2f}")
# Example 2: Temperature conversion
celsius = 37
fahrenheit = (celsius * 9/5) + 32
print(f"Temperature: {celsius}°C = {fahrenheit}°F")
# Example 3: Check if a number is even or odd
number = 17
result = "Even" if number % 2 == 0 else "Odd"
print(f"Number {number} is {result}")
# Example 4: Swap two variables
x, y = 10, 20
print(f"Before swap: x = {x}, y = {y}")
x, y = y, x # Python's elegant swap!
print(f"After swap: x = {x}, y = {y}")
# Example 5: Calculate compound interest
principal = 1000
rate = 0.05 # 5%
time = 3 # years
amount = principal * (1 + rate) ** time
print(f"Compound Interest: ${principal} at {rate*100}% for {time} years = ${amount:.2f}")
print("\n" + "=" * 60)
print("END OF EXAMPLES")
print("=" * 60)