- Understand Python syntax and basic programming concepts
- Learn variables, data types, and operators
- Master control structures (if, loops)
- Apply functions and basic input/output operations
- Develop problem-solving skills with Python
Introduction to Python
Python is a high-level, interpreted programming language known for its simplicity and readability. It's widely used in web development, data science, automation, and software development.
Key Features
- Simple Syntax: Easy to read and write
- Interpreted: No compilation step needed
- Cross-platform: Runs on Windows, Mac, Linux
- Large Standard Library: Built-in modules for common tasks
- Dynamic Typing: Variables don't need type declarations
- Object-Oriented: Supports OOP principles
Variables and Data Types
Variables store data values and Python has several built-in data types.
Variable Assignment
# Variable assignment
name = "Alice"
age = 25
height = 5.6
is_student = True
# Multiple assignment
x, y, z = 1, 2, 3
a = b = c = 0
Basic Data Types
# Integers
count = 42
negative = -10
# Floats
price = 19.99
temperature = -5.5
# Strings
message = "Hello, World!"
single_quotes = 'Python is great'
# Booleans
is_valid = True
is_complete = False
# Check data type
print(type(count)) #
print(type(price)) #
print(type(message)) #
Operators
Python provides various operators for performing operations on variables and values.
Arithmetic Operators
# Basic arithmetic
a = 10
b = 3
addition = a + b # 13
subtraction = a - b # 7
multiplication = a * b # 30
division = a / b # 3.333...
floor_division = a // b # 3
modulus = a % b # 1
exponentiation = a ** b # 1000
Comparison Operators
# Comparison operators
x = 5
y = 10
equal = x == y # False
not_equal = x != y # True
greater = x > y # False
less = x < y # True
greater_equal = x >= y # False
less_equal = x <= y # True
Logical Operators
# Logical operators
a = True
b = False
and_result = a and b # False
or_result = a or b # True
not_result = not a # False
# With conditions
age = 20
has_license = True
can_drive = age >= 18 and has_license # True
Strings
Strings are sequences of characters used to store text data.
String Operations
# String creation
name = "Python"
greeting = 'Hello'
# String concatenation
message = greeting + " " + name # "Hello Python"
# String repetition
repeated = "Ha" * 3 # "HaHaHa"
# String indexing
first_char = name[0] # "P"
last_char = name[-1] # "n"
# String slicing
substring = name[1:4] # "yth"
String Methods
# Common string methods
text = " Hello World "
upper_text = text.upper() # " HELLO WORLD "
lower_text = text.lower() # " hello world "
stripped = text.strip() # "Hello World"
replaced = text.replace("World", "Python") # " Hello Python "
split_text = text.strip().split() # ["Hello", "World"]
# String formatting
name = "Alice"
age = 25
formatted = f"My name is {name} and I am {age} years old"
print(formatted)
Input and Output
Python provides simple functions for getting user input and displaying output.
Output with print()
# Basic printing
print("Hello, World!")
print("The answer is", 42)
# Multiple values
name = "Alice"
age = 25
print("Name:", name, "Age:", age)
# Formatted output
print(f"Name: {name}, Age: {age}")
# Print with separators
print("A", "B", "C", sep="-") # A-B-C
Input with input()
# Getting user input
name = input("Enter your name: ")
print(f"Hello, {name}!")
# Converting input to numbers
age_str = input("Enter your age: ")
age = int(age_str)
# Direct conversion
height = float(input("Enter your height: "))
Control Structures
Control structures determine the flow of program execution.
Conditional Statements
# if statement
age = 18
if age >= 18:
print("You are an adult")
# if-else statement
score = 85
if score >= 60:
print("You passed!")
else:
print("You failed!")
# if-elif-else statement
grade = 85
if grade >= 90:
print("Grade: A")
elif grade >= 80:
print("Grade: B")
elif grade >= 70:
print("Grade: C")
else:
print("Grade: F")
Loops
# for loop with range
for i in range(5):
print(i) # 0, 1, 2, 3, 4
# for loop with range parameters
for i in range(1, 6):
print(i) # 1, 2, 3, 4, 5
# for loop with step
for i in range(0, 10, 2):
print(i) # 0, 2, 4, 6, 8
# while loop
count = 0
while count < 5:
print(count)
count += 1
# Loop control
for i in range(10):
if i == 3:
continue # Skip iteration
if i == 7:
break # Exit loop
print(i)
Lists
Lists are ordered collections that can store multiple items.
List Basics
# Creating lists
numbers = [1, 2, 3, 4, 5]
names = ["Alice", "Bob", "Charlie"]
mixed = [1, "hello", 3.14, True]
# Accessing elements
first = numbers[0] # 1
last = numbers[-1] # 5
# List slicing
subset = numbers[1:4] # [2, 3, 4]
# List length
length = len(numbers) # 5
List Methods
# Modifying lists
fruits = ["apple", "banana"]
# Adding elements
fruits.append("orange") # ["apple", "banana", "orange"]
fruits.insert(1, "grape") # ["apple", "grape", "banana", "orange"]
# Removing elements
fruits.remove("banana") # ["apple", "grape", "orange"]
last_fruit = fruits.pop() # "orange", list becomes ["apple", "grape"]
# Other operations
fruits.sort() # Sort in place
fruits.reverse() # Reverse in place
count = fruits.count("apple") # Count occurrences
Functions
Functions are reusable blocks of code that perform specific tasks.
Defining Functions
# Basic function
def greet():
print("Hello, World!")
# Call the function
greet()
# Function with parameters
def greet_person(name):
print(f"Hello, {name}!")
greet_person("Alice")
# Function with return value
def add_numbers(a, b):
return a + b
result = add_numbers(5, 3) # 8
Function Parameters
# Default parameters
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet("Alice") # Hello, Alice!
greet("Bob", "Hi") # Hi, Bob!
# Multiple return values
def get_name_age():
return "Alice", 25
name, age = get_name_age()
# Variable arguments
def sum_all(*numbers):
return sum(numbers)
total = sum_all(1, 2, 3, 4, 5) # 15
Error Handling
Handle errors gracefully to prevent program crashes.
Try-Except Blocks
# Basic error handling
try:
number = int(input("Enter a number: "))
result = 10 / number
print(f"Result: {result}")
except ValueError:
print("Invalid input! Please enter a number.")
except ZeroDivisionError:
print("Cannot divide by zero!")
# General exception handling
try:
# Some risky operation
pass
except Exception as e:
print(f"An error occurred: {e}")
finally:
print("This always executes")
File Operations
Read from and write to files for data persistence.
Reading Files
# Reading entire file
try:
with open("data.txt", "r") as file:
content = file.read()
print(content)
except FileNotFoundError:
print("File not found!")
# Reading line by line
with open("data.txt", "r") as file:
for line in file:
print(line.strip())
Writing Files
# Writing to file
with open("output.txt", "w") as file:
file.write("Hello, World!\n")
file.write("Python is great!")
# Appending to file
with open("output.txt", "a") as file:
file.write("\nAppended text")
Common Programming Patterns
Useful patterns for solving common programming problems.
Input Validation
# Validate numeric input
def get_valid_number(prompt):
while True:
try:
return float(input(prompt))
except ValueError:
print("Please enter a valid number!")
age = get_valid_number("Enter your age: ")
Menu Systems
# Simple menu system
def show_menu():
print("1. Option 1")
print("2. Option 2")
print("3. Exit")
while True:
show_menu()
choice = input("Enter choice: ")
if choice == "1":
print("You chose option 1")
elif choice == "2":
print("You chose option 2")
elif choice == "3":
print("Goodbye!")
break
else:
print("Invalid choice!")
Best Practices
Guidelines for writing clean, readable Python code.
Code Style
- Use descriptive variable names
- Follow PEP 8 style guidelines
- Use consistent indentation (4 spaces)
- Add comments to explain complex logic
- Keep functions small and focused
- Use meaningful function names
Example: Well-Structured Program
# Calculator program with good structure
def add(a, b):
"""Add two numbers and return the result."""
return a + b
def subtract(a, b):
"""Subtract b from a and return the result."""
return a - b
def get_number(prompt):
"""Get a valid number from user input."""
while True:
try:
return float(input(prompt))
except ValueError:
print("Please enter a valid number!")
def main():
"""Main program function."""
print("Simple Calculator")
num1 = get_number("Enter first number: ")
num2 = get_number("Enter second number: ")
print(f"Addition: {add(num1, num2)}")
print(f"Subtraction: {subtract(num1, num2)}")
if __name__ == "__main__":
main()