Unit I: Introduction & Basics

1
Introduction
2
Control Flow
3
Functions
4
Data Structures
5
Files & Exceptions

1.1 Hello World

Python is known for its readability. The simplest program is the print statement.

print("Hello, Python World!")
print(5 + 10)
Why Python? Python's simplicity and readability make it an excellent language for beginners. Its extensive libraries and community support make it powerful for advanced applications.

1.2 Variables

Variables are containers for storing data values. Python has no command for declaring a variable.

x = 5           # Integer
y = "John"      # String
z = 3.14        # Float

print(x)
print(y)
print(type(z))

Quick Quiz

What will be the output of the following code?

x = 5
y = x
x = 10
print(y)

1.3 Data Types

Python has several built-in data types that are used to store different kinds of information.

# Integer
age = 25

# Float
price = 19.99

# String
name = "Python"

# Boolean
is_learning = True

# List
languages = ["Python", "JavaScript", "Java"]

# Dictionary
person = {"name": "John", "age": 30}

# Print types
print(type(age))
print(type(price))
print(type(name))
print(type(is_learning))
print(type(languages))
print(type(person))

Practice Task: Variables and Data Types

Create a program that demonstrates different data types in Python:

  1. Create variables for different data types (integer, float, string, boolean)
  2. Print each variable and its type
  3. Convert between data types (e.g., string to integer)
  4. Perform operations with different data types
# Create variables of different types
num = 42
text = "42"
# Convert string to integer
num_from_text = int(text)
# Perform operations
result = num + num_from_text
print(result)

Unit II: Control Flow

1
Introduction
2
Control Flow
3
Functions
4
Data Structures
5
Files & Exceptions

2.1 If...Else

Python supports the usual logical conditions from mathematics.

a = 200
b = 33
if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")
else:
  print("a is greater than b")

2.2 While Loops

With the while loop we can execute a set of statements as long as a condition is true.

i = 1
while i < 6:
  print(i)
  if i == 3:
    break
  i += 1

2.3 For Loops

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)

# Loop through a string
for x in "banana":
  print(x)

# Loop with range
for x in range(6):
  print(x)

Practice Task: Control Flow

Create a program that uses different control flow structures:

  1. Use if-elif-else to categorize numbers (positive, negative, zero)
  2. Use a while loop to find the sum of numbers from 1 to 10
  3. Use a for loop to iterate through a list and print each item
  4. Use break and continue statements in loops
# Categorize numbers
num = 5
if num > 0:
  print("Positive")
elif num < 0:
  print("Negative")
else:
  print("Zero")

# Sum with while loop
i = 1
total = 0
while i <= 10:
  total += i
  i += 1
print(total)

Unit III: Functions & Arrays

1
Introduction
2
Control Flow
3
Functions
4
Data Structures
5
Files & Exceptions

3.1 Creating Functions

A function is a block of code which only runs when it is called.

def my_function(fname):
  print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")

3.2 Function Parameters

Information can be passed to functions as parameters.

def my_function(country = "Norway"):
  print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")

3.3 Return Values

To let a function return a value, use the return statement.

def my_function(x):
  return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))

Practice Task: Functions

Create a program that demonstrates different function concepts:

  1. Create a function with parameters and a return value
  2. Create a function with default parameter values
  3. Create a function that returns multiple values
  4. Create a recursive function (e.g., factorial)
# Function with parameters and return value
def add_numbers(a, b):
  return a + b

# Function with default parameter
def greet(name, greeting="Hello"):
  print(f"{greeting}, {name}!")

# Function returning multiple values
def get_name_and_age():
  return "John", 30

# Recursive function
def factorial(n):
  if n <= 1:
    return 1
  else:
    return n * factorial(n-1)

Unit IV: Data Structures

1
Introduction
2
Control Flow
3
Functions
4
Data Structures
5
Files & Exceptions

4.1 Lists

Lists are used to store multiple items in a single variable. They are ordered and changeable.

fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits)
print(fruits[1])  # Access item
fruits.remove("banana")
print(fruits)

# List comprehension
squares = [x**2 for x in range(10)]
print(squares)

4.2 Dictionaries

Dictionaries are used to store data values in key:value pairs.

car = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
print(car["brand"])
car["year"] = 2020
print(car)

# Dictionary methods
print(car.keys())
print(car.values())
print(car.items())

4.3 Tuples and Sets

Tuples are ordered and unchangeable. Sets are unordered and unindexed.

# Tuple
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])

# Set
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)

# Set operations
set1 = {"a", "b", "c"}
set2 = {"c", "d", "e"}
print(set1.union(set2))
print(set1.intersection(set2))

Practice Task: Data Structures

Create a program that demonstrates different data structures:

  1. Create a list of numbers and perform various operations (add, remove, sort)
  2. Create a dictionary to store student information
  3. Create a tuple of coordinates and try to modify it (observe the error)
  4. Create a set of unique items and perform set operations
# List operations
numbers = [1, 2, 3, 4, 5]
numbers.append(6)
numbers.remove(3)
numbers.sort()

# Dictionary
student = {"name": "John", "age": 20, "grades": [85, 90, 78]}
print(student["name"])

# Tuple
coordinates = (10, 20)
# coordinates[0] = 15 # This will cause an error

# Set operations
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1.union(set2))

Unit V: Files & Exceptions

1
Introduction
2
Control Flow
3
Functions
4
Data Structures
5
Files & Exceptions

5.1 File Handling

Python has several functions for creating, reading, updating, and deleting files.

# Write to a file
f = open("demofile.txt", "w")
f.write("Hello! Welcome to demofile.txt\n")
f.write("This file is for testing purposes.\n")
f.close()

# Read from a file
f = open("demofile.txt", "r")
print(f.read())
f.close()

# Read line by line
f = open("demofile.txt", "r")
for x in f:
  print(x)
f.close()

5.2 Try Except

The try block lets you test a block of code for errors. The except block lets you handle the error.

try:
  print(x)
except:
  print("An exception occurred: x is not defined")

# Specific exception
try:
  print(x)
except NameError:
  print("Variable x is not defined")
except:
  print("Something else went wrong")

# Finally block
try:
  f = open("demofile.txt", "r")
  try:
    f.write("Lorum Ipsum")
  except:
    print("Something went wrong when writing to the file")
  finally:
    f.close()
except FileNotFoundError:
  print("The file was not found")

Practice Task: Files & Exceptions

Create a program that demonstrates file handling and exception handling:

  1. Create a program that writes user input to a file
  2. Read the file and display its contents
  3. Handle potential file-related exceptions
  4. Create a custom exception and raise it in a specific condition
# Write to file
try:
  user_input = input("Enter something: ")
  with open("user_input.txt", "w") as f:
    f.write(user_input)
except Exception as e:
  print(f"Error: {e}")

# Read from file
try:
  with open("user_input.txt", "r") as f:
    content = f.read()
    print(f"File content: {content}")
except FileNotFoundError:
  print("File not found")

# Custom exception
class CustomError(Exception):
  pass
  # Raise the exception
  raise CustomError("This is a custom error")
Python Interactive
Code
Files
Console
Output: Clear
Ready to run.
main.py
helper.py
data.txt
Console:
Python console ready.
Code copied! Paste it in the editor.