Python Programming
Python Basics
Python Basics
Section titled “Python Basics”In this lesson, we’ll explore the fundamental building blocks of Python: variables, data types, and operators.
Variables
Section titled “Variables”Variables are containers for storing data values. In Python, you don’t need to declare a variable type - Python figures it out automatically.
# Creating variablesname = "Alice"age = 25height = 5.7is_student = True
# Printing variablesprint(name) # Output: Aliceprint(age) # Output: 25print(height) # Output: 5.7print(is_student) # Output: TrueVariable Naming Rules
Section titled “Variable Naming Rules”- Must start with a letter or underscore
- Can contain letters, numbers, and underscores
- Case-sensitive (
nameandNameare different) - Cannot use reserved keywords (
if,for,class, etc.)
# Good variable namesuser_name = "Bob"userAge = 30_private = "secret"MAX_SIZE = 100
# Bad variable names (will cause errors)# 2name = "Error" # Cannot start with number# my-name = "Error" # Cannot use hyphens# class = "Error" # Cannot use reserved wordsPython Naming Conventions
Section titled “Python Naming Conventions”# snake_case for variables and functions (recommended)first_name = "John"total_count = 42
# UPPER_CASE for constantsMAX_CONNECTIONS = 100PI = 3.14159
# PascalCase for classesclass UserProfile: passData Types
Section titled “Data Types”Python has several built-in data types:
Numeric Types
Section titled “Numeric Types”# Integer (int) - whole numberscount = 42negative = -10big_number = 1_000_000 # Underscores for readability
# Float - decimal numbersprice = 19.99temperature = -5.5scientific = 1.5e-4 # Scientific notation (0.00015)
# Complex numberscomplex_num = 3 + 4jStrings
Section titled “Strings”# Strings - text datasingle_quotes = 'Hello'double_quotes = "World"multiline = """This is amultiline string"""
# String operationsgreeting = "Hello"name = "World"message = greeting + " " + name # Concatenation: "Hello World"repeated = "Ha" * 3 # Repetition: "HaHaHa"
# String indexing (0-based)text = "Python"print(text[0]) # 'P' (first character)print(text[-1]) # 'n' (last character)print(text[0:3]) # 'Pyt' (slicing)
# Useful string methodstext = " hello world "print(text.upper()) # " HELLO WORLD "print(text.lower()) # " hello world "print(text.strip()) # "hello world"print(text.replace("world", "Python")) # " hello Python "print(len(text)) # 15
# f-strings (formatted strings) - Python 3.6+name = "Alice"age = 25print(f"My name is {name} and I'm {age} years old")Booleans
Section titled “Booleans”# Boolean - True or Falseis_active = Trueis_logged_in = False
# Boolean operationsprint(True and False) # Falseprint(True or False) # Trueprint(not True) # False
# Truthy and Falsy values# Falsy: False, 0, 0.0, "", [], {}, None# Truthy: Everything elseNone Type
Section titled “None Type”# None represents absence of valueresult = None
if result is None: print("No result yet")Type Checking and Conversion
Section titled “Type Checking and Conversion”# Check typex = 42print(type(x)) # <class 'int'>
y = "hello"print(type(y)) # <class 'str'>
# Type conversion (casting)num_str = "42"num_int = int(num_str) # String to integer: 42num_float = float(num_str) # String to float: 42.0
num = 42num_as_str = str(num) # Integer to string: "42"
# Be careful with invalid conversions# int("hello") # ValueError!Operators
Section titled “Operators”Arithmetic Operators
Section titled “Arithmetic Operators”a = 10b = 3
print(a + b) # Addition: 13print(a - b) # Subtraction: 7print(a * b) # Multiplication: 30print(a / b) # Division: 3.333...print(a // b) # Floor division: 3print(a % b) # Modulus (remainder): 1print(a ** b) # Exponentiation: 1000Comparison Operators
Section titled “Comparison Operators”a = 10b = 5
print(a == b) # Equal: Falseprint(a != b) # Not equal: Trueprint(a > b) # Greater than: Trueprint(a < b) # Less than: Falseprint(a >= b) # Greater or equal: Trueprint(a <= b) # Less or equal: FalseLogical Operators
Section titled “Logical Operators”x = Truey = False
print(x and y) # False (both must be True)print(x or y) # True (at least one True)print(not x) # False (negation)
# Practical exampleage = 25has_license = True
can_drive = age >= 18 and has_licenseprint(can_drive) # TrueAssignment Operators
Section titled “Assignment Operators”x = 10 # Assignx += 5 # Add and assign (x = x + 5) → 15x -= 3 # Subtract and assign → 12x *= 2 # Multiply and assign → 24x /= 4 # Divide and assign → 6.0x //= 2 # Floor divide and assign → 3.0x **= 2 # Power and assign → 9.0x %= 4 # Modulus and assign → 1.0User Input
Section titled “User Input”# Getting input from username = input("What is your name? ")print(f"Hello, {name}!")
# Input is always a string - convert if neededage_str = input("Enter your age: ")age = int(age_str) # Convert to integerbirth_year = 2024 - ageprint(f"You were born around {birth_year}")Practice Exercises
Section titled “Practice Exercises”Exercise 1: Variable Swap
Section titled “Exercise 1: Variable Swap”Swap the values of two variables without using a third variable.
# Your task: Swap a and ba = 5b = 10# After swap: a should be 10, b should be 5Solution
a = 5b = 10a, b = b, a # Python's tuple unpacking!print(a, b) # 10, 5Exercise 2: Temperature Converter
Section titled “Exercise 2: Temperature Converter”Convert temperature from Celsius to Fahrenheit.
# Formula: F = (C Ă— 9/5) + 32celsius = 25# Calculate fahrenheitSolution
celsius = 25fahrenheit = (celsius * 9/5) + 32print(f"{celsius}°C = {fahrenheit}°F") # 25°C = 77.0°FExercise 3: String Manipulation
Section titled “Exercise 3: String Manipulation”Given a user’s full name, extract and print the initials.
full_name = "John Michael Smith"# Output should be: J.M.S.Solution
full_name = "John Michael Smith"parts = full_name.split()initials = ".".join([name[0] for name in parts]) + "."print(initials) # J.M.S.Summary
Section titled “Summary”In this lesson, you learned:
- âś… How to create and name variables
- ✅ Python’s main data types (int, float, str, bool, None)
- âś… Type checking and conversion
- âś… Arithmetic, comparison, logical, and assignment operators
- âś… Getting user input
Next Steps
Section titled “Next Steps”In the next lesson, we’ll explore data structures in Python:
- Lists, Tuples, and Sets
- Dictionaries
- Common operations on collections