We tailor our content to practical, industry-relevant tech skills. Our materials are continuously updated and refined ensuring we integrate current and widely-adopted programming languages.
The print()
statement in Python is used to show messages on the
screen. It helps us display
words, numbers, or even results of calculations.
Why is print() important?
Example: Printing "Hello, World!"
print("Hello, World!")
Explanation: print
is the command that tells Python
to display something. The
parentheses ()
hold what we want to print, and the text within the
quotes is the string we
display.
Output: Hello, World!
Fun Experiment: Try changing the message inside the
print()
function.
print("I love coding!")
print("Python is fun!")
Key Points to Remember:
print(10 + 5)
.print()
function can be used multiple times in your code.
The input()
function in Python allows users to enter data into the
program.
Why is input() important?
Example: Asking for a Name
name = input("What is your name? ")
print("Hello, " + name + "!")
Example Output:
What is your name? Alex
Hello, Alex!
Fun Experiment: Try asking different questions and responding based on input:
color = input("What is your favorite color? ")
print("Wow! " + color + " is a great color!")
Variables are like containers for storing data values. In Python, we use variables to store values like numbers, words, or even the results of calculations.
Why are variables important?
Example: Storing a Name
name = "Alice"
print("Hello, " + name + "!")
Variables can be used to store all sorts of data.
favorite_food = "Pizza"
print(favorite_food)
age = 12
height = 4.5
print(age)
print(height)
is_student = True
print(is_student)
Types of Values You Can Store:
Updating Variables:
age = 10
print("I am", age, "years old.")
age = 11 # Changing the value
print("Now I am", age, "years old.")
Combining input() with Variables:
name = input("What is your name? ")
print("Nice to meet you, " + name + "!")
Rules for Naming Variables:
Fun Experiment: Try changing values of variables and see how it affects your program.
Data types in Python specify the different types of values that can be stored and manipulated within a program.
Why Data Types are Important:
Common Data Types:
Example of Each Data Type:
# String Example
name = "Alice"
print("Name:", name)
# Integer Example
age = 30
print("Age:", age)
# Float Example
height = 5.9
print("Height:", height)
# Boolean Example
is_student = True
print("Is student:", is_student)
Type Conversion: Changing the data type of a value to another, such as converting a string to an integer.
number_string = "123"
number_int = int(number_string)
print("Converted Number:", number_int)
Experiment with Data Types: Try creating variables of each type and see how Python handles them.
A function in Python is like a magic box that performs a specific task when you call it. Functions help us organize code, avoid repetition, and make our programs easier to read.
Why Are Functions Important?
Creating a Function (Defining a Function)
To create a function in Python, we use the def
keyword, followed by
the function
name and parentheses ()
.
def say_hello():
print("Hello, World!")
Output:
Hello, World!
Calling a Function
Once a function is defined, you can call it by using its name followed by parentheses.
say_hello() # This will call the function and run its code.
Output:
Hello, World!
Functions with Parameters (Inputs)
A function can take inputs (called parameters) to perform a task based on the input.
def greet(name):
print("Hello, " + name + "!")
greet("Alice")
greet("Bob")
Output:
Hello, Alice!
Hello, Bob!
Functions with Return Values
Instead of just printing, a function can return a value to be used later.
def multiply(x, y):
return x * y
result = multiply(4, 3)
print(result)
Output:
12
Default Parameters
Functions can have default values for parameters. If no value is provided when calling the function, the default is used.
def greet(name="friend"):
print("Hello, " + name + "!")
greet() # Uses the default value
greet("Alice") # Uses the provided value
Output:
Hello, friend!
Hello, Alice!
Using Functions with input()
We can take user input and pass it as an argument to a function.
def favorite_color(color):
print("Wow! " + color + " is a beautiful color!")
user_color = input("Enter your favorite color: ")
favorite_color(user_color)
Calling Functions Inside Functions
A function can call another function.
def say_hello():
print("Hello!")
def greet_person(name):
say_hello()
print("Nice to meet you, " + name + "!")
greet_person("Alice")
Output:
Hello!
Nice to meet you, Alice!
Breaking a Problem into Functions
Functions can be used to divide a big problem into smaller tasks.
def calculate_area(length, width):
return length * width
def display_area(length, width):
area = calculate_area(length, width)
print("The area is:", area)
display_area(5, 3)
Output:
The area is: 15
Fun Experiment
Try creating a function that calculates the square of a number:
def square(number):
return number * number
print(square(4)) # Output: 16
print(square(7)) # Output: 49
Key Points to Remember About Functions
def
keyword to define a function.Operators in Python are special symbols or keywords that perform actions on values. They are used for calculations, comparisons, and logic-based tasks.
+ Add: 5 + 3 = 8
- Subtract: 10 - 4 = 6
* Multiply: 6 * 2 = 12
/ Divide: 8 / 2 = 4.0
// Floor Division: 9 // 2 = 4
% Modulus: 10 % 3 = 1
** Exponentiation: 2 ** 3 = 8
== Equal to: 5 == 5 results in True
!= Not equal to: 4 != 3 results in True
> Greater than: 10 > 5 results in True
< Less than: 3 < 5 results in True
>= Greater or equal to: 6 >= 6 results in True
<= Less or equal to: 2 <= 5 results in True
and Both conditions true: (x > 5 and x < 10) results in True
or At least one condition true: (x > 5 or x < 2) results in True
not Reverses the condition: not(x > 5) results in False
x = 5
x += 3 # x = x + 3
x -= 2 # x = x - 2
x *= 4 # x = x * 4
x /= 2 # x = x / 2
fruits = ["apple", "banana", "cherry"]
"apple" in fruits # Returns True
"grape" not in fruits # Returns True
Python follows a specific order of operations which is similar to that in mathematics. This determines how expressions are evaluated.
Try combining different types of operators to see the effect:
x = 10
y = 3
print(x + y) # Addition
print(x > y and x < 15) # Logical
print("apple" in ["apple", "orange"]) # Membership
Key Points to Remember: Understanding different operators and their precedence is crucial for writing effective Python code.
String concatenation is the process of joining two or more strings together. This is useful for creating meaningful sentences, combining user inputs, or formatting text.
We can concatenate strings in Python using the +
operator.
greeting = "Hello"
name = "Alice"
message = greeting + " " + name
print(message)
Output: Hello Alice
Adding Spaces While Concatenating
If you want spaces between words, you need to add them manually as part of the string.
word1 = "Python"
word2 = "is fun"
sentence = word1 + " " + word2
print(sentence)
Output: Python is fun
We can mix strings with variables to create personalized outputs.
name = "Bob"
age = 12
message = "Hi, my name is " + name + " and I am " + str(age) + " years old."
print(message)
Output: Hi, my name is Bob and I am 12 years old.
An f-string
is an easier way to concatenate strings and variables.
Just add an f
before the string and put variables inside curly braces {}
.
name = "Charlie"
age = 15
message = f"My name is {name} and I am {age} years old."
print(message)
Output: My name is Charlie and I am 15 years old.
.format()
for ConcatenationAnother way to concatenate strings is by using the .format()
method.
name = "Alice"
age = 10
message = "My name is {} and I am {} years old.".format(name, age)
print(message)
Output: My name is Alice and I am 10 years old.
You can use concatenation inside loops to build strings dynamically.
words = ["Python", "is", "fun"]
sentence = ""
for word in words:
sentence += word + " "
print(sentence)
Output: Python is fun
+
operator to join strings.f-strings
or .format()
for easier
concatenation with variables.str()
before concatenating.
print("Hello" + "World") # Output: HelloWorld
age = 10
print("I am " + age) # Error: TypeError
print("I am " + str(age)) # Correct way
Try creating a dynamic greeting program:
name = input("What is your name? ")
hobby = input("What is your favorite hobby? ")
print("Hi " + name + "! It's great to know that you love " + hobby + ".")
Output (Example): What is your name? Alice
What is your
favorite hobby? painting
Hi
Alice! It's great to know that you love painting.
Conditional statements in Python allow programs to respond differently based on conditions.
Python includes several types of conditional statements:
age = 15
if age > 12:
print("You are a teenager!")
Output: You are a teenager!
age = 10
if age > 12:
print("You are a teenager!")
else:
print("You are still a child!")
Output: You are still a child!
marks = 85
if marks >= 90:
print("You got an A!")
elif marks >= 75:
print("You got a B!")
else:
print("You need to work harder.")
Output: You got a B!
Nested if statements check conditions within conditions.
age = 18
has_ticket = True
if age >= 18:
if has_ticket:
print("You can enter the movie theater!")
else:
print("You need a ticket!")
else:
print("You're too young to watch this movie.")
Output: You can enter the movie theater!
We can use user input to make decisions.
password = input("Enter the password: ")
if password == "python123":
print("Access granted!")
else:
print("Wrong password!")
Create a simple quiz using conditional statements:
answer = input("What is the capital of Kenya? ")
if answer.lower() == "nairobi":
print("Correct!")
else:
print("Oops! The correct answer is Nairobi.")
Loops in Python allow repetitive actions to be executed multiple times without rewriting the code.
Python supports several types of loops:
for i in range(1, 6):
print(i)
Outputs numbers from 1 to 5.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Outputs each fruit in the list.
count = 1
while count <= 5:
print(count)
count += 1
Counts from 1 to 5.
break is used to exit a loop prematurely, while continue skips to the next iteration.
for num in range(1, 10):
if num == 5:
break
print(num)
Prints numbers 1 to 4 and then stops.
for num in range(1, 6):
if num == 3:
continue
print(num)
Skips number 3 and prints 1, 2, 4, 5.
Loops can be nested inside other loops to perform multi-level actions.
for i in range(1, 4):
for j in range(1, 4):
print(f"i = {i}, j = {j}")
Prints a combination of i and j values.
Create a countdown using a while loop.
countdown = 5
while countdown > 0:
print(countdown)
countdown -= 1
print("Happy New Year!")
Counts down from 5 and then celebrates.
A list in Python is a collection which is ordered and changeable. In Python, lists are written with square brackets.
Lists are created using square brackets:
fruits = ["apple", "banana", "cherry"]
print(fruits)
Outputs: ['apple', 'banana', 'cherry']
You can access the list items by referring to the index number:
print(fruits[0]) # Outputs 'apple'
print(fruits[2]) # Outputs 'cherry'
Change the value of a specific item by referring to its index number:
fruits[1] = "blueberry"
print(fruits) # Outputs ['apple', 'blueberry', 'cherry']
Add items to the end of the list using the append() method or at the specified index using the insert() method:
fruits.append("orange") # Adds 'orange' to the end
fruits.insert(1, "mango") # Inserts 'mango' at index 1
print(fruits) # Outputs ['apple', 'mango', 'blueberry', 'cherry', 'orange']
Remove specified items using the remove() method or remove items by index using the pop() method or del keyword:
fruits.remove("mango") # Removes 'mango'
print(fruits) # Outputs ['apple', 'blueberry', 'cherry', 'orange']
fruits.pop(1) # Removes item at index 1
print(fruits) # Outputs ['apple', 'cherry', 'orange']
del fruits[0] # Deletes item at index 0
print(fruits) # Outputs ['cherry', 'orange']
Iterate over the items of the list using a for loop:
for fruit in fruits:
print(fruit) # Outputs each fruit in the list
Check if an item exists within a list using the in keyword:
if "apple" in fruits:
print("Apple is in the list!") # Confirms that apple is in the list
Use the len() method to get the number of items in a list:
print(len(fruits)) # Outputs the number of items in the list
Sort the list items alphabetically in ascending or descending order using the sort() method:
numbers = [4, 1, 3, 2]
numbers.sort() # Sorts the list in ascending order
print(numbers) # Outputs [1, 2, 3, 4]
numbers.sort(reverse=True) # Sorts the list in descending order
print(numbers) # Outputs [4, 3, 2, 1]
Combine or merge two lists by using the + operator or the extend() method:
list1 = ["cat", "dog"]
list2 = ["bird", "fish"]
combined_list = list1 + list2
print(combined_list) # Outputs ['cat', 'dog', 'bird', 'fish']
Create a list of your favorite hobbies and print them using a loop:
hobbies = ["reading", "drawing", "cycling"]
for hobby in hobbies:
print("I love " + hobby) # Outputs each hobby in a friendly format
A tuple in Python is a collection of items that cannot be changed (immutable). Tuples are written with round brackets and the items are separated by commas.
Tuples are created using round brackets:
fruits = ("apple", "banana", "cherry")
print(fruits)
Outputs: ('apple', 'banana', 'cherry')
Items in a tuple can be accessed by their index, similar to lists:
print(fruits[0]) # Outputs 'apple'
print(fruits[2]) # Outputs 'cherry'
Tuples are immutable, so trying to change them will result in an error:
# This will raise an error
fruits[1] = "blueberry"
You can loop through a tuple using a for loop:
colors = ("red", "blue", "green")
for color in colors:
print(color)
The number of items in a tuple can be determined using the len() function:
print(len(fruits)) # Outputs 3
Two or more tuples can be combined using the + operator:
tuple1 = ("red", "blue")
tuple2 = ("green", "yellow")
combined_tuple = tuple1 + tuple2
print(combined_tuple)
Outputs: ('red', 'blue', 'green', 'yellow')
Parts of a tuple can be accessed using slicing:
numbers = (10, 20, 30, 40, 50)
print(numbers[1:4]) # Outputs (20, 30, 40)
Check if an item exists within a tuple using the in keyword:
if "banana" in fruits:
print("Banana is in the tuple!")
If you need to modify a tuple, you can convert it to a list:
fruits_list = list(fruits)
fruits_list.append("orange")
fruits = tuple(fruits_list)
print(fruits)
Outputs: ('apple', 'banana', 'cherry', 'orange')
Tuples can be used to assign multiple values at once:
person = ("Alice", 25, "Engineer")
name, age, profession = person
print(name) # Outputs 'Alice'
print(age) # Outputs 25
print(profession) # Outputs 'Engineer'
Try creating a tuple with your favorite foods and print them:
foods = ("pizza", "burger", "pasta")
for food in foods:
print("I love " + food)
Dictionaries in Python are collections of key-value pairs that function like a real-life dictionary, allowing you to quickly retrieve information by looking up a key.
Dictionaries are defined with curly braces {}
with items stored as
key-value pairs separated by
colons.
student = {
"name": "Alice",
"age": 12,
"grade": "7th"
}
print(student)
This outputs: {'name': 'Alice', 'age': 12, 'grade': '7th'}
Access dictionary values by key using brackets []
or the
.get()
method.
print(student["name"]) # Outputs 'Alice'
print(student.get("age")) # Outputs 12
Add or update dictionary items by assigning a value to a key.
student["grade"] = "8th" # Updates if exists, adds if not
print(student)
Remove items using .pop()
, del
, or
.clear()
.
student.pop("age") # Removes 'age'
del student["grade"] # Removes 'grade'
student.clear() # Empties dictionary
Iterate through keys, values, or both using loops.
for key in student:
print(key) # Prints all keys
for value in student.values():
print(value) # Prints all values
for key, value in student.items():
print(key, ":", value) # Prints all key-value pairs
Check for the existence of a key using in
.
if "name" in student:
print("Name is available!")
Use methods like keys()
, values()
, and
items()
to interact with
dictionaries.
print(student.keys()) # Outputs all keys
print(student.values()) # Outputs all values
print(student.items()) # Outputs all items
Dictionaries can contain other dictionaries, allowing complex data structures.
school = {
"student1": {"name": "Alice", "age": 12},
"student2": {"name": "Bob", "age": 14}
}
print(school["student1"]["name"]) # Outputs 'Alice'
Create and manipulate your own dictionary with hobbies, friends, or any other interests.
hobbies = {
"hobby1": "reading",
"hobby2": "drawing"
}
for hobby, description in hobbies.items():
print("I enjoy " + description)
Sets in Python are collections of unique items that are unordered and do not allow duplicates. They are ideal for storing distinct values and performing set operations like unions and intersections.
Sets can be created using curly braces {}
or the set()
function. Here is how you
can initialize a set:
fruits = {"apple", "banana", "cherry"}
print(fruits)
numbers = set([1, 2, 3, 3, 4]) # Duplicates are removed
print(numbers)
While sets do not support indexing, you can loop through them or ask if a value exists:
for fruit in fruits:
print(fruit)
Use add()
to add single items and update()
for multiple
items:
fruits.add("orange")
fruits.update(["mango", "grape"])
print(fruits)
Items can be removed using remove()
, discard()
, and
pop()
:
fruits.remove("banana")
fruits.discard("cherry")
random_fruit = fruits.pop()
fruits.clear()
Perform mathematical set operations like union, intersection, and difference:
set1 = {1, 2, 3}
set2 = {2, 3, 4}
print(set1 | set2) # Union
print(set1 & set2) # Intersection
print(set1 - set2) # Difference
print(set1 ^ set2) # Symmetric Difference
While sets cannot contain other sets due to their unhashable nature, they can contain immutable versions called frozensets:
nested_set = {frozenset({1, 2}), frozenset({3, 4})}
print(nested_set)
Create sets of your favorite movies or books and use set operations to combine them with friends' favorites:
my_favorites = {"Star Wars", "The Matrix"}
friends_favorites = {"The Matrix", "Inception"}
print(my_favorites | friends_favorites) # Find all unique favorites
String manipulation involves altering, formatting, and working with strings to achieve desired outputs, using Python's rich set of string handling capabilities.
Method | Description | Example |
---|---|---|
lower() |
Converts a string to lowercase. | "HELLO".lower() results in "hello" |
upper() |
Converts a string to uppercase. | "hello".upper() results in "HELLO" |
capitalize() |
Capitalizes the first letter of the string. | "python".capitalize() results in "Python" |
strip() |
Removes any leading/trailing whitespace from the string. | " hello ".strip() results in "hello" |
replace(old, new) |
Replaces all occurrences of a substring. | "cats".replace("c", "b") results in "bats"
|
split(delimiter) |
Splits the string into a list based on the delimiter. | "a,b,c".split(",") results in ['a', 'b', 'c']
|
join(list) |
Joins the elements of a list into a single string with the string as the delimiter. | " ".join(['Hello', 'World']) results in
"Hello World" |
word = "Python"
print(word[0]) # Output: 'P'
print(word[-1]) # Output: 'n'
print(word[0:2]) # Output: 'Py'
print(word[:2]) # Output: 'Py'
print(word[2:]) # Output: 'thon'
text = "python is fun"
print(text.upper()) # Output: 'PYTHON IS FUN'
print(text.capitalize()) # Output: 'Python is fun'
text = "I like cats"
new_text = text.replace("cats", "dogs")
print(new_text) # Output: 'I like dogs'
name = "Alice"
age = 12
print(f"My name is {name}, and I am {age} years old.") # Using f-string
print("My name is {}, and I am {} years old.".format(name, age)) # Using .format()
Try modifying a user's input and combining various string methods:
name = input("What is your name? ").strip().capitalize()
hobby = input("What is your favorite hobby? ")
print(f"Hello, {name}! It's great to know that you enjoy {hobby.lower()}!")
File Handling in Python allows us to work with files, enabling operations like reading, writing, and creating new files.
To open a file, we use the open()
function with the filename and the
mode (e.g., "r" for read,
"w" for write).
file = open("filename.txt", "r")
content = file.read()
print(content)
file.close()
file = open("example.txt", "r")
for line in file:
print(line.strip())
file.close()
file = open("example.txt", "w")
file.write("Hello, this is written to a file!\n")
file.close()
file = open("example.txt", "a")
file.write("Adding this line to the end of the file.")
file.close()
file = open("newfile.txt", "x")
file.write("New file created!")
file.close()
We use the os
module to check if a file exists and delete it:
import os
if os.path.exists("example.txt"):
os.remove("example.txt")
print("File deleted!")
else:
print("The file does not exist.")
with
Statement for File Handling:The with
statement simplifies file handling by automatically taking
care of closing the file
after its suite finishes:
with open("example.txt", "r") as file:
content = file.read()
print(content)
Create a simple program to take user input and write it to a file:
with open("userdata.txt", "w") as file:
name = input("Enter your name: ")
hobby = input("Enter your hobby: ")
file.write(f"Name: {name}, Hobby: {hobby}")
print("Data saved to file!")
Exception handling in Python allows us to deal with errors during the execution of a program. It helps prevent the program from crashing and allows for more graceful error handling.
try:
# Code that might raise an error
risky_code
except:
# Code to handle the error
handle_error
try:
result = 10 / 0
except:
print("Oops! You can't divide by zero.")
Output: "Oops! You can't divide by zero."
try:
numbers = [1, 2, 3]
print(numbers[5])
except IndexError:
print("Index out of range!")
Output: "Index out of range!"
The else
block runs if no exceptions are raised, and the
finally
block runs
regardless of what happens in the try
and except
.
try:
file = open("example.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found!")
finally:
print("This block always runs.")
Output: Depending on if the file exists, either "File not found!" or the file content, followed by "This block always runs."
try:
x = int("hello") # Causes ValueError
result = 10 / 0 # Causes ZeroDivisionError
except ValueError:
print("Invalid value!")
except ZeroDivisionError:
print("Cannot divide by zero!")
Output: "Invalid value!"
Create a simple program that handles exceptions:
try:
number = int(input("Enter a number: "))
print("You entered:", number)
except ValueError:
print("That's not a valid number!")
These examples show how to manage different types of errors gracefully without letting the program crash unexpectedly.
Classes and Objects are fundamental to understanding Object-Oriented Programming (OOP) in Python, allowing data and functions to be encapsulated into a single entity.
A class is like a blueprint for creating objects, defining the properties and behaviors that the objects will have.
class Car:
def drive(self):
print("The car is driving!")
Objects are instances of a class, created from the class's blueprint.
my_car = Car()
my_car.drive()
Output: "The car is driving!"
__init__
MethodThe __init__
method initializes new objects by setting initial
values for the object's
properties.
class Car:
def __init__(self, brand, color):
self.brand = brand
self.color = color
def describe(self):
print(f"This car is a {self.color} {self.brand}.")
my_car = Car("Toyota", "red")
my_car.describe()
Output: "This car is a red Toyota."
Attributes of objects can be accessed and modified directly using the dot notation.
my_car = Car("Honda", "blue")
print(my_car.brand) # Output: Honda
my_car.color = "green"
print(my_car.color) # Output: green
Methods are functions defined within a class that describe the behaviors of the class's objects.
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print(f"{self.name} is barking!")
my_dog = Dog("Buddy")
my_dog.bark()
Output: "Buddy is barking!"
self
The self
keyword is used in methods to refer to the object on which
the method is being called.
class Person:
def __init__(self, name):
self.name = name
def greet(self):
print(f"Hello, my name is {self.name}.")
Create a class for your favorite animal and make it perform an action.
class Animal:
def __init__(self, name, sound):
self.name = name
self.sound = sound
def make_sound(self):
print(f"The {self.name} goes {self.sound}!")
cat = Animal("cat", "meow")
cat.make_sound()
Output: "The cat goes meow!"
Modules and packages help organize Python code into manageable parts, making it easier to maintain and reuse code across different projects.
A module is a Python file containing functions, classes, or variables. Modules allow you to logically organize your Python code.
# math_tools.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
Modules can be imported into other modules or scripts, enabling you to use functions or classes defined in them.
import math_tools
result = math_tools.add(5, 3)
print(result) # Output: 8
Python includes several built-in modules that provide useful functionalities like mathematical operations and random number generations.
import math
print(math.sqrt(16)) # Output: 4.0
import random
print(random.randint(1, 10)) # Random number between 1 and 10
You can choose to import specific attributes or functions from a module, which is useful when you only need a part of the module.
from math import sqrt, pi
print(sqrt(25)) # Output: 5.0
print(pi) # Output: 3.141592653589793
A package is a directory of Python scripts, each of which is a module that can include functions, classes, and variables.
To create a package, make a directory and add an `__init__.py` file to it, then place your module files in the directory.
from my_package.greetings import say_hello
from my_package.math_tools import multiply
print(say_hello("Alice")) # Output: Hello, Alice!
print(multiply(3, 4)) # Output: 12
External packages can be installed and managed with `pip`, Python's package installer.
pip install requests
Create a package that includes several modules to handle different tasks. For example, a package for handling various math operations like addition, subtraction, and multiplication.
List comprehensions provide a concise way to create lists. They can simplify code that would otherwise use loops and conditionals.
new_list = [expression for item in iterable if condition]
Traditionally, you might use a loop to create a list by appending items one by one.
numbers = [1, 2, 3, 4, 5]
squares = []
for num in numbers:
squares.append(num ** 2)
print(squares) # Output: [1, 4, 9, 16, 25]
A list comprehension can achieve the same result with less code.
numbers = [1, 2, 3, 4, 5]
squares = [num ** 2 for num in numbers]
print(squares) # Output: [1, 4, 9, 16, 25]
You can add conditions to filter items.
numbers = [1, 2, 3, 4, 5, 6]
evens = [num for num in numbers if num % 2 == 0]
print(evens) # Output: [2, 4, 6]
List comprehensions can also include an if-else condition to perform different operations based on the condition.
numbers = [1, 2, 3, 4, 5]
result = ["even" if num % 2 == 0 else "odd" for num in numbers]
print(result) # Output: ['odd', 'even', 'odd', 'even', 'odd']
List comprehensions can be used to manipulate strings efficiently.
words = ["hello", "world", "python"]
uppercase_words = [word.upper() for word in words]
print(uppercase_words) # Output: ['HELLO', 'WORLD', 'PYTHON']
You can incorporate multiple loops within a list comprehension for more complex operations.
numbers = [1, 2, 3]
pairs = [(x, y) for x in numbers for y in numbers]
print(pairs) # Output: [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
You can also use `range()` to create lists that represent a sequence of numbers.
squares = [x ** 2 for x in range(1, 6)]
print(squares) # Output: [1, 4, 9, 16, 25]
Conditions can be combined with loops for filtering and applying complex logic.
numbers = range(1, 11)
even_squares = [x ** 2 for x in numbers if x % 2 == 0]
print(even_squares) # Output: [4, 16, 36, 64, 100]
Experiment with list comprehensions by using them to transform a list of names or to create patterns.
names = ["Alice", "Bob", "Alex", "Charlie"]
a_names = [name.lower() for name in names if name.startswith("A")]
print(a_names) # Output: ['alice', 'alex']
Lambda functions in Python are small, anonymous functions defined with the lambda keyword. They can have any number of arguments but only one expression.
lambda arguments: expression
Here is an example of a simple lambda function that adds two numbers:
add = lambda a, b: a + b
print(add(3, 5)) # Output: 8
Lambda functions are commonly used with other functions, especially with
map()
,
filter()
, and sort()
to apply functions to sequences.
map()
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # Output: [1, 4, 9, 16]
filter()
numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # Output: [2, 4, 6]
sort()
names = ["Alice", "Bob", "Charlie"]
sorted_names = sorted(names, key=lambda name: len(name))
print(sorted_names) # Output: ['Bob', 'Alice', 'Charlie']
Lambda functions can also have default arguments:
add = lambda x, y=5: x + y
print(add(3)) # Output: 8 (3 + 5)
print(add(3, 7)) # Output: 10 (3 + 7)
Here's a fun experiment to try combining lambda functions with map()
and filter()
:
numbers = [1, 2, 3, 4, 5, 6]
squared_evens = list(map(lambda x: x ** 2, filter(lambda x: x % 2 == 0, numbers)))
print(squared_evens) # Output: [4, 16, 36]
Recursion is a programming technique where a function calls itself to solve smaller instances of the same problem. It simplifies complex problems by dividing them into more manageable parts.
A recursive function consists of two parts: a base case that ends the recursion, and a recursive case that calls the function itself.
def countdown(n):
if n == 0:
print("Blast off!")
else:
print(n)
countdown(n - 1)
countdown(5)
This function prints numbers starting from the given number down to zero. When it reaches zero, it prints "Blast off!"
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
print(factorial(5)) # Output: 120
The factorial of a number is the product of all positive integers up to that number. This example uses recursion to calculate the factorial of 5.
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(6)) # Output: 8
The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones. This function calculates the nth Fibonacci number.
def infinite():
infinite()
This is an example of infinite recursion, which will cause a crash or a 'RecursionError' due to the stack overflow.
def sum_numbers(n):
if n == 0:
return 0
else:
return n + sum_numbers(n - 1)
print(sum_numbers(5)) # Output: 15
This recursive function calculates the sum of all numbers from 1 to n. It's a great way to understand how recursion works by breaking down the addition process.
An API (Application Programming Interface) allows two applications to communicate with each other. For instance, fetching weather information for a specific location from a weather service.
The requests
library is a versatile HTTP client for Python that
simplifies working with HTTP
requests.
pip install requests
import requests
response = requests.get("https://api.github.com")
print(response.status_code) # Status code check
print(response.json()) # Parsing JSON response
Most APIs return data in JSON format, which can easily be converted to Python data structures for manipulation.
params = {
"q": "search_query",
"appid": "your_api_key"
}
response = requests.get("https://api.example.com/search", params=params)
data = response.json()
print(data)
response = requests.get("https://api.example.com/data")
if response.status_code == 200:
print("Success!")
else:
print("Error occurred: ", response.status_code)
data = {"key": "value"}
response = requests.post("https://api.example.com/submit", json=data)
print(response.text)
Some APIs require authentication using tokens or API keys, which should be included in request headers.
headers = {
"Authorization": "Bearer your_api_key"
}
response = requests.get("https://api.example.com/protected", headers=headers)
print(response.json())
Combine knowledge of GET requests, query parameters, and JSON handling to fetch and display weather data.
api_url = "https://api.openweathermap.org/data/2.5/weather"
params = {
"q": "London",
"appid": "your_api_key"
}
response = requests.get(api_url, params=params)
weather = response.json()
print("Weather in London: ", weather["main"]["temp"])
Create a simple application that fetches daily quotes from an API and displays them.
response = requests.get("https://api.quotable.com/random")
quote = response.json()
print(quote["content"])
Data visualization involves creating visual representations of data to make it easier to understand and interpret. It's a powerful way to communicate information clearly and effectively.
Matplotlib is a popular Python library for creating static, interactive, and animated visualizations in Python.
pip install matplotlib
Here's how to create a simple line plot showing a linear relationship:
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
plt.plot(x, y)
plt.title("Simple Line Plot")
plt.xlabel("X Axis")
plt.ylabel("Y Axis")
plt.show()
Bar charts are great for comparing categorical data:
categories = ['Red', 'Blue', 'Green', 'Purple']
values = [50, 80, 60, 90]
plt.bar(categories, values)
plt.title("Bar Chart Example")
plt.xlabel("Colors")
plt.ylabel("Values")
plt.show()
Pie charts show parts of a whole as slices:
labels = ['Apples', 'Bananas', 'Cherries', 'Dates']
sizes = [15, 30, 45, 10]
plt.pie(sizes, labels=labels, autopct='%1.1f%%')
plt.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
plt.show()
Histograms help visualize the distributions of data points:
data = [1, 2, 2, 3, 3, 3, 3, 4, 4, 5]
plt.hist(data, bins=5)
plt.title("Histogram")
plt.show()
You can customize the look of your plots with different colors, markers, and line styles:
plt.plot(x, y, marker='o', color='red', linestyle='--')
plt.title("Customized Line Plot")
plt.xlabel("X Axis")
plt.ylabel("Y Axis")
plt.grid(True)
plt.show()
Try creating a scatter plot to explore the relationship between two variables:
x = [5, 2, 9, 4, 7]
y = [10, 5, 8, 4, 2]
plt.scatter(x, y)
plt.title("Scatter Plot Example")
plt.xlabel("Independent Variable")
plt.ylabel("Dependent Variable")
plt.show()
Python projects help apply various concepts learned throughout Python tutorials, combining loops, conditionals, functions, and APIs to solve real-world problems and create functional applications.
def quiz():
questions = {
"What is the capital of Kenya?": "Nairobi",
"What is 2 + 2?": "4",
"Who wrote 'Harry Potter'?": "J.K. Rowling"
}
score = 0
for question, answer in questions.items():
user_answer = input(question + " ")
if user_answer.lower() == answer.lower():
print("Correct!")
score += 1
else:
print(f"Wrong! The correct answer is {answer}.")
print(f"You got {score}/{len(questions)} questions right!")
quiz()
def calculator():
print("Simple Calculator")
print("Choose an operation: +, -, *, /")
operation = input("Enter operation: ")
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
if operation == "+":
print(f"The result is: {num1 + num2}")
elif operation == "-":
print(f"The result is: {num1 - num2}")
elif operation == "*":
print(f"The result is: {num1 * num2}")
elif operation == "/":
if num2 != 0:
print(f"The result is: {num1 / num2}")
else:
print("Error! Division by zero.")
else:
print("Invalid operation.")
calculator()
import random
def number_guessing_game():
number = random.randint(1, 100)
print("Guess the number between 1 and 100!")
while True:
guess = int(input("Enter your guess: "))
if guess < number:
print("Too low!")
elif guess > number:
print("Too high!")
else:
print("Congratulations! You guessed the number!")
break
number_guessing_game()
def to_do_list():
tasks = []
while True:
print("\nTo-Do List:")
for i, task in enumerate(tasks, start=1):
print(f"{i}. {task}")
print("\nOptions: 1. Add Task 2. Remove Task 3. Exit")
choice = input("Choose an option: ")
if choice == "1":
task = input("Enter a new task: ")
tasks.append(task)
elif choice == "2":
task_number = int(input("Enter the task number to remove: "))
if 0 < task_number <= len(tasks):
tasks.pop(task_number - 1)
else:
print("Invalid task number.")
elif choice == "3":
print("Goodbye!")
break
else:
print("Invalid choice. Please try again.")
to_do_list()
import requests
def weather_app():
api_key = "your_api_key" # Replace with your API key
city = input("Enter the city name: ")
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
print(f"City: {data['name']}")
print(f"Temperature: {data['main']['temp']}°C")
print(f"Weather: {data['weather'][0]['description']}")
else:
print("City not found. Please try again.")
weather_app()
Content credit: MIT Scratch. You can find the practical content on their website here.
Introduction to the Scratch interface, coding blocks, and basic project navigation.
Explore Scratch tutorials presented in American Sign Language for accessibility.
Learn how to add, select, and customize sprites to begin creating your projects.
Learn to choose and customize backdrops, and add simple animations to your sprite.
Control sprite movement using keyboard arrow keys.
Learn how to adjust sprite size and scale for better visuals.
Create smooth movement effects using glide blocks.
Animate your sprite to spin and rotate for dynamic effects.
Capture and incorporate your own sounds into Scratch projects.
Control sprite visibility to enhance interactive storytelling.
Apply various visual effects to enhance your sprite animations.
Animate your sprite to simulate flying movements.
Integrate sound blocks to compose music and add sound effects.
Explore interactive projects using video sensing and camera input.
Create projects where characters tell stories using speech and animations.
Create a dynamic animation that brings your name to life.
Develop a character animation showcasing personality and movement.
Combine scenes and animations to tell a cohesive story.
Add dialogue and sound to your animations for interactive storytelling.
Design immersive environments and backdrops that set the scene for your projects.
Create a simple interactive ping pong game using motion and collision blocks.
Develop a game that tests timing and coordination with mouse clicks.
Build a fun chase game where sprites pursue one another.
Create a short cartoon animation using sequential coding blocks.
Combine all your skills to design an interactive adventure game.