0% found this document useful (0 votes)
4 views61 pages

Python Worksheets Handouts

The document provides study notes for ICT 312 Advanced Programming for Teachers, focusing on Python programming for beginners. It includes detailed instructions on installing Python, using the interpreter, and engaging in hands-on activities such as solving programming problems, building projects, and debugging exercises. Additionally, it covers various programming concepts like variables, data types, arithmetic operations, string manipulation, conditional statements, and loops, along with practice problems to reinforce learning.

Uploaded by

ngwenyaphoebe759
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views61 pages

Python Worksheets Handouts

The document provides study notes for ICT 312 Advanced Programming for Teachers, focusing on Python programming for beginners. It includes detailed instructions on installing Python, using the interpreter, and engaging in hands-on activities such as solving programming problems, building projects, and debugging exercises. Additionally, it covers various programming concepts like variables, data types, arithmetic operations, string manipulation, conditional statements, and loops, along with practice problems to reinforce learning.

Uploaded by

ngwenyaphoebe759
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

FACULTY OF EDUCATION

DEPARTMENT OF SCIENCE, TECHNOLOGY AND DESIGN EDUCATION

ICT 312 Advanced programming for teachers

Study Notes for students

Lecturer: F. Jamba

NB: for you to have a fruitful experience in this module to need to carryout and the
activities hands on.

Installing and Interpreting Python Programming for Absolute Beginners

Python is a popular programming language used for a wide range of applications,


including data analysis, web development, and artificial intelligence. Python is a great
language to start with. Here's a step-by-step guide on how to install and interpret
Python programming.

Step 1: Download and Install Python

The first step is to download and install Python on your computer. Here's how to do it:

Go to the Python website and click on the "Download Python" button.

Select the version of Python you want to download. If you're not sure which version to
choose, go with the latest version (currently Python 3.10.0).

Choose your operating system (Windows, macOS, or Linux) and click on the
appropriate link to download the installation file.

Run the installation file and follow the prompts to install Python on your computer.

Step 2: Open the Python Interpreter

After installing Python, you can open the Python interpreter to start writing and
executing code. Here's how to do it:
Open the Command Prompt (Windows) or Terminal (macOS or Linux).

Type python and press Enter. This will start the Python interpreter.

Step 3: Write and Execute Code

Once you've opened the Python interpreter, you can start writing and executing code.
Here's an example of a simple Python program:

Congratulations, you've just written and executed your first Python program!

Solve Programming Problems:

Encourage students to solve programming problems using Python. There are many
websites available such as HackerRank, CodeWars, and Project Euler that offer
programming problems of varying difficulty levels. These sites offer a great way for
students to practice their Python programming skills and improve their problem-solving
abilities.

Build Projects:

Projects are an excellent way for students to apply their Python programming skills to
real-world problems. Encourage students to build projects such as a calculator, a
weather app, or a game. This will help them gain a deeper understanding of how
Python works and how it can be used to solve real-world problems.

Debugging Exercises:

Debugging exercises can help students to identify and fix errors in their Python code.
Create exercises that contain bugs, and ask students to find and fix the bugs. This will
help them to develop their debugging skills, which are an essential part of
programming.

Collaborative Programming:

Encourage students to work collaboratively on programming projects. This will help


them to learn from each other and to develop their teamwork and communication skills.
Collaborative programming can be done either in-person or online, using tools such
as Git and GitHub

Attend Workshops and Meetups:

Encourage students to attend workshops and meetups related to Python


programming. These events offer an opportunity to learn from experienced
programmers, network with other students, and stay up-to-date with the latest trends
and best practices in Python programming.

These activities will help students to fully understand Python programming and
develop their skills as programmers.

some activities that students can do to fully understand variables in Python

Assigning and Printing Variables: The first step to understanding variables in Python
is to know how to assign and print them. Students can write simple programs that
assign values to variables and then print the values to the console.

Data Types:

Variables can store different types of data in Python such as strings, integers, and
floats. Encourage students to create programs that use different data types and
demonstrate how variables can store and manipulate them.
Arithmetic Operations:

Students can write programs that use variables to perform basic arithmetic operations
such as addition, subtraction, multiplication, and division. This will help them
understand how variables can be used in mathematical operations.

String Manipulation:

Python allows for manipulation of strings using variables. Students can write programs
that use variables to concatenate strings, convert strings to upper or lower case, and
search for substrings.

Conditional Statements:

Variables can be used in conditional statements such as if, elif, and else statements.
Encourage students to write programs that use variables in conditional statements to
make decisions based on the value of the variable.

Loops:

Variables can also be used in loops such as for and while loops. Students can write
programs that use variables in loops to iterate over data structures such as lists and
dictionaries.

Project-based Learning:

Finally, encourage students to work on projects that involve using variables. For
example, they can write a program that calculates the area of a rectangle, or a program
that converts Celsius to Fahrenheit using variables.

These activities will help students to fully understand variables in Python and how they
can be used in different contexts.

Variables in Python - Assigning and Printing

Objective: To understand how to assign and print variables in Python


Instructions:

Assigning Variables: Write a Python program that assigns a value to a variable and
prints the value to the console. For example:
Practice Problems: Solve the following problems using Python variables:

a) Write a program that assigns the value of pi (3.14) to a variable and prints it to the
console.

b) Write a program that assigns the value of your name to a variable and prints it to
the console.

c) Write a program that assigns the value of your age to a variable and prints it to the
console.

d) Write a program that calculates the area of a rectangle using variables and prints it
to the console.
e) Write a program that converts Celsius to Fahrenheit using variables and prints the
result to the console.

Variables in Python - Data Types

Objective: To understand how to use different data types in Python variables

Instructions:

String Variables: Write a program that assigns a string to a variable and prints it to
the console. For example:

Float Variables: Write a program that assigns a float to a variable and prints it to the
console. For example:
Practice Problems: Solve the following problems using Python variables and data
types:
a) Write a program that assigns a string to a variable, converts it to uppercase, and
prints the result.

b) Write a program that assigns two integers to variables and adds them together.
Print the result.

c) Write a program that assigns two float numbers to variables and divides them. Print
the result.

d) Write a program that assigns a float to a variable, converts it to an integer, and


prints the result.

e) Write a program that assigns a string to a variable and checks if it is a palindrome.

Debugging Exercises

Objective: To identify and fix bugs in Python code

Instructions:

Syntax Errors: The following programs contain syntax errors. Find and fix the errors
so that the programs run correctly.
Logical Errors: The following programs contain logical errors. Find and fix the errors
so that the programs produce the correct output.

print(my_list)

Practice Problems: Solve the following problems by finding and fixing the errors in the
code:
a) Write a program that calculates the area of a circle. The program should ask the
user for the radius of the circle and print the area to the console.

b) Write a program that asks the user for their name and age. The program should
print a message that says "Hello [name], you are [age] years old."

c) Write a program that calculates the factorial of a number. The program should ask
the user for a number and print the factorial to the console.

Arithmetic Operations with Variables

Objective: To perform basic arithmetic operations using variables in Python

Instructions:

Addition: Write a program that uses two variables to add two numbers and prints the
result to the console.

Subtraction: Write a program that uses two variables to subtract one number from
another and prints the result to the console.

Multiplication: Write a program that uses two variables to multiply two numbers and
prints the result to the console.

Division: Write a program that uses two variables to divide one number by another
and prints the result to the console.

Modulo: Write a program that uses two variables to calculate the remainder of dividing
one number by another and prints the result to the console.

Order of Operations: Write a program that uses multiple variables to perform a


complex arithmetic operation using the order of operations (PEMDAS) and prints the
result to the console.

Practice Problems:

a) Write a program that uses variables to calculate the area of a rectangle. The
program should ask the user for the length and width of the rectangle, and then print
the area to the console.
b) Write a program that uses variables to calculate the volume of a cylinder. The
program should ask the user for the radius and height of the cylinder, and then print
the volume to the console.

c) Write a program that uses variables to convert temperature from Celsius to


Fahrenheit. The program should ask the user for the temperature in Celsius and then
print the temperature in Fahrenheit to the console.

String Manipulation with Variables

Objective: To manipulate strings using variables in Python

Instructions:

Concatenation: Write a program that uses variables to concatenate two strings and
prints the result to the console.

Upper Case: Write a program that uses a variable to convert a string to upper case
and prints the result to the console.

Lower Case: Write a program that uses a variable to convert a string to lower case
and prints the result to the console.

Substring Search: Write a program that uses variables to search for a substring
within a larger string and prints the result to the console.

String Formatting: Write a program that uses variables and string formatting to create
a sentence that includes information about the user. The program should ask the user
for their name, age, and location, and then print a sentence that includes this
information.

Practice Problems:

a) Write a program that uses variables to create a password. The program should ask
the user for their first name, last name, and birth year, and then create a password by
combining the first letter of their first name, the first three letters of their last name, and
the last two digits of their birth year. The program should then print the password to
the console.

b) Write a program that uses variables to create a username. The program should ask
the user for their first name, last name, and favorite number, and then create a
username by combining the first letter of their first name, the first four letters of their
last name, and their favorite number. The program should then print the username to
the console.

c) Write a program that uses variables to convert a sentence into "camel case". Camel
case is a naming convention where the first letter of each word is capitalized, except
for the first word. For example, "hello world" would become "helloWorld". The program
should ask the user for a sentence and then convert it to camel case using variables.
The program should then print the camel case version of the sentence to the console.

Conditional Statements with Variables

Objective: To use variables in conditional statements to make decisions in Python

Instructions:

If Statements: Write a program that uses an if statement and a variable to check if a


number is even or odd. The program should ask the user for a number and then print
"even" or "odd" to the console based on the value of the variable.

Elif Statements: Write a program that uses an elif statement and a variable to check if
a number is positive, negative, or zero. The program should ask the user for a number
and then print "positive", "negative", or "zero" to the console based on the value of the
variable.

Else Statements: Write a program that uses an else statement and a variable to check
if a number is a multiple of 3 or 5. The program should ask the user for a number and
then print "multiple of 3", "multiple of 5", or "not a multiple of 3 or 5" to the console
based on the value of the variable.

Nested Statements: Write a program that uses nested if statements and variables to
check if a password is strong or weak. The program should ask the user for a password
and then check if it has at least 8 characters, contains at least one uppercase letter,
and contains at least one number. If all of these conditions are true, the program
should print "strong password". Otherwise, it should print "weak password".

Practice Problems:
a) Write a program that uses variables and conditional statements to calculate the cost
of a ride on a roller coaster. The program should ask the user for their height and age,
and then calculate the cost based on the following rules:

If the user is under 48 inches tall, the cost is $5.

If the user is between 48 and 72 inches tall and under 18 years old, the cost is $10.

If the user is between 48 and 72 inches tall and 18 years old or older, the cost is
$15.

If the user is over 72 inches tall, the cost is $20.

The program should then print the cost to the console.

b) Write a program that uses variables and conditional statements to calculate the
shipping cost of an online order. The program should ask the user for the total cost of
the order and the destination country. The program should then calculate the shipping
cost based on the following rules:

If the order is under $50 and the destination is within the US, the shipping cost is
$5.

If the order is between $50 and $100 and the destination is within the US, the
shipping cost is $10.

If the order is over $100 and the destination is within the US, the shipping cost is
free.

If the order is over $100 and the destination is outside the US, the shipping cost is
$20.

For all other orders and destinations, the shipping cost is $15.

The program should then print the shipping cost to the console.

Loops with Variables

Objective: To use variables in loops to iterate over data structures in Python

Instructions:
For Loops: Write a program that uses a for loop and a variable to iterate over a list of
numbers and print each number to the console. The program should define a list of
numbers and assign it to a variable, then use the for loop to iterate over the list and
print each number.

While Loops: Write a program that uses a while loop and a variable to count from 1 to
10 and print each number to the console. The program should use a variable to keep
track of the current number, and the while loop to continue counting until the current
number is 10.

Nested Loops: Write a program that uses nested loops and variables to print a
multiplication table. The program should ask the user for a number and then use two
for loops to iterate over the numbers from 1 to 10 and print the product of each pair of
numbers.

Loop Control Statements: Write a program that uses a for loop and a variable to iterate
over a list of numbers and print each number to the console, but skip any number that
is divisible by 3. The program should define a list of numbers and assign it to a variable,
then use the for loop and an if statement with the modulus operator to check if each
number is divisible by 3.

Practice Problems:

a) Write a program that uses a for loop and a variable to iterate over a list of names
and print each name with a greeting to the console. The program should define a list
of names and assign it to a variable, then use the for loop to iterate over the list and
print a personalized greeting for each name.

b) Write a program that uses a while loop and a variable to generate a random number
between 1 and 10. The program should import the random module and use the while
loop to keep generating random numbers until the generated number is 5. The
program should then print the number of attempts it took to generate the number.

Variables

Objective: To develop projects that involve using variables to perform calculations and
conversions in Python

Instructions:
Area of a Rectangle: Write a program that uses variables to calculate the area of a
rectangle. The program should ask the user to input the length and width of the
rectangle, then calculate and print the area to the console. Use descriptive variable
names to make the code easy to read.

Celsius to Fahrenheit: Write a program that uses variables to convert a temperature


in Celsius to Fahrenheit. The program should ask the user to input a temperature in
Celsius, then calculate and print the equivalent temperature in Fahrenheit to the
console. Use descriptive variable names to make the code easy to read.

Tip Calculator: Write a program that uses variables to calculate the tip on a restaurant
bill. The program should ask the user to input the total bill amount and the tip
percentage, then calculate and print the tip amount and the total bill with the tip
included to the console. Use descriptive variable names to make the code easy to
read.

Grade Calculator: Write a program that uses variables to calculate the average
grade on a test. The program should ask the user to input the grades for each student,
then calculate and print the average grade to the console. Use a list variable to store
the grades and a loop to iterate over the list and calculate the average.

Practice Problems:

a) Write a program that uses variables to calculate the distance between two points in
a 2D coordinate system. The program should ask the user to input the x and y
coordinates for each point, then calculate and print the distance between the points to
the console.

b) Write a program that uses variables to calculate the factorial of a number. The
program should ask the user to input a number, then use a loop and a variable to
calculate and print the factorial to the console.
Write simple programs that use conditional statements (if-else, if-elif-else) to solve
basic problems. For example, you can ask them to write a program that takes an input
from the user and determines if it is even or odd.

Have students create a program that uses a loop (while or for loop) to print out a
pattern or sequence of numbers. This will help them understand how control structures
can be used to repeat a task multiple times.

Provide students with a series of programming challenges that require the use of
control structures. For example, you can ask them to write a program that generates
a Fibonacci sequence, or one that calculates the factorial of a number.

Have students debug and fix existing code that contains errors related to control
structures. This will help them develop their problem-solving skills and deepen their
understanding of how control structures work in Python.

Encourage students to work collaboratively on programming projects that involve the


use of control structures. This will help them develop their communication skills and
learn from each other's approaches and strategies.

Overall, the key to fully understanding control structures in Python is practice and
experimentation. By providing students with opportunities to write, debug, and test
code that uses these structures, you can help them develop a strong foundation in
programming and problem-solving.

Conditional Statements in Python

Conditional statements in Python are used to make decisions based on certain


conditions. These statements are executed only if the condition is true. The basic
syntax for conditional statements in Python is:
In this example, the program prompts the user to enter a number. The program then
uses the modulo operator (%) to determine if the number is even or odd. If the number
is even, the program prints "The number is even." Otherwise, it prints "The number is
odd."

Exercise:

Write a Python program that takes two numbers as input from the user and determines
which number is greater.

Solution:
Worksheet:

Instructions:

Write a Python program that takes a user input and determines if the number is
positive, negative, or zero.

Prompt the user to enter a number.

Use an if-else statement to determine if the number is positive, negative, or zero.

If the number is positive, print "The number is positive."

If the number is negative, print "The number is negative."

If the number is zero, print "The number is zero."

Sample Output:
Hints:

Remember to use the int() function to convert the user input from a string to an
integer.

Use the comparison operators (>, <, ==) to compare the input number to zero.

Use an if-else statement to handle each of the three cases (positive, negative, zero).

Loops in Python

Loops in Python are used to execute a block of code repeatedly. There are two types
of loops in Python: for loops and while loops. A for loop is used to iterate over a
sequence of values, while a while loop is used to repeat a block of code while a certain
condition is true.

The basic syntax for a for loop in Python is:


In this example, the program uses the range() function to generate a sequence of
numbers from 1 to 10. The for loop then iterates over each value in the sequence and
prints it to the console.

Exercise:

Write a Python program that uses a while loop to print out the first 10 even numbers.

Solution:

In this example, the program initializes a variable num to 2 and a variable count to 0.
The while loop then executes as long as the count is less than 10. For each iteration
of the loop, the program prints out the current value of num, which is incremented by
2. The count variable is also incremented by 1 to ensure that the loop only executes
10 times.

Instructions:

Write a Python program that uses a for loop to print out a pattern of stars. The program
should prompt the user to enter the number of rows they want in the pattern.

Prompt the user to enter the number of rows they want in the pattern.

Use a for loop to iterate over the range of values from 1 to the number of rows.

Within the for loop, use another for loop to print out a row of stars.

The number of stars in each row should be equal to the row number.

Sample Output:
Hints:

Use the int() function to convert the user input from a string to an integer.

Use nested for loops to create the pattern of stars.

Remember to use the print() function to output the stars to the console.

Programming Challenges with Control Structures

In order to become proficient with control structures in Python, it's important to practice
using them in a variety of different programming challenges. Here are some
programming challenges that will help you improve your skills:

Fibonacci Sequence

The Fibonacci sequence is a series of numbers where each number is the sum of the
two preceding ones. The sequence starts with 0 and 1, and the next number in the
sequence is the sum of the previous two. Write a Python program that generates the
Fibonacci sequence up to a specified number of terms.

Factorial

The factorial of a number is the product of all positive integers less than or equal to
that number. Write a Python program that calculates the factorial of a number.
Guess the Number

Write a Python program that generates a random number between 1 and 100, and
asks the user to guess what it is. If the user's guess is too high or too low, the program
should give a hint and ask the user to guess again. The program should continue until
the user guesses the correct number.

Rock, Paper, Scissors

Write a Python program that allows the user to play a game of rock, paper, scissors
against the computer. The program should prompt the user for their choice (rock,
paper, or scissors), generate a random choice for the computer, and determine the
winner based on the rules of the game.

Instructions:

Choose one of the programming challenges described above and write a Python
program to solve it. Use conditional statements (if-else, if-elif-else) and loops (while or
for loop) as needed to implement the solution.

Fibonacci Sequence

Prompt the user to enter the number of terms they want in the Fibonacci sequence.
Use a for loop to generate the sequence up to the specified number of terms. Print out
each number in the sequence as it is generated.

Factorial

Prompt the user to enter a positive integer. Use a for loop to calculate the factorial of
the number. Print out the factorial.

Guess the Number

Use the random module to generate a random number between 1 and 100. Use a
while loop to prompt the user to guess the number until they guess correctly. Provide
hints to the user as needed (e.g. "Too high!" or "Too low!").

Rock, Paper, Scissors

Use the random module to generate a random choice for the computer (rock, paper,
or scissors). Prompt the user for their choice (rock, paper, or scissors), and determine
the winner based on the rules of the game. Print out the winner.
Sample Output:

Hints:

Use the int() function to convert user input from a string to an integer.

Use the range() function to generate a sequence of numbers for the Fibonacci
sequence or factorial calculation.

Use the input() function to prompt the user for input.

Use the [Link]() function to generate a random number for the Guess the
Number or Rock, Paper, Scissors games.

Debugging Control Structures in Python

Debugging is an important skill for any programmer to have. In this activity, you will be
given some code that contains errors related to control structures. Your task is to
debug the code and fix the errors so that it runs correctly.

Code with if-else errors:


Instructions:

Debug the code given below by identifying and correcting the errors related to control
structures.

Code with if-else errors:


Hints:

Use proper indentation for code inside control structures (if-else, for loop, while loop).

Make sure that the control structures are properly closed (using colons and
indentation).

Double-check the conditionals used in the control structures to ensure that they are
correct.

Collaborative Programming with Control Structures

Collaboration is an important part of programming. In this activity, you will work in


teams to complete programming projects that involve the use of control structures.
You will be encouraged to share your approaches and strategies with each other and
work collaboratively to find the best solutions to the given problems.

Divide into teams of 2-4 students

Choose one of the following programming projects to work on:

Write a program that generates the first n terms of the Fibonacci sequence, where
n is a user-specified integer.

Write a program that takes a string as input and determines whether it is a


palindrome or not.
Write a program that takes a list of numbers as input and finds the largest and
smallest numbers in the list.

Write a program that takes a list of integers as input and returns a new list that
contains only the even numbers from the original list.

Use control structures (if-else, for loop, while loop) to implement your chosen
program.

Work collaboratively with your team members to find the best solutions to the given
problem.

Test your program thoroughly and debug any errors.

Discuss your approach and strategies with other teams and compare and contrast
the strengths and weaknesses of each approach.

Reflect on your experience working collaboratively and identify areas where you
could improve your communication and teamwork skills.

Sample Output:
Hints:

Use comments to explain your code and make it more readable.

Work together to divide tasks and assign roles within your team.

Be open to feedback and suggestions from other teams, and use them to improve
your own approach.

Remember to test your code thoroughly and debug any errors before sharing it with
others.

Functions

Write a simple function: Ask the students to write a function that takes two numbers
as inputs and returns their sum. This is a simple example, but it will help them
understand the basic syntax of creating a function in Python.

Use parameters and arguments: Ask the students to create a function that takes in a
parameter and an argument. For example, create a function that takes in a name as
a parameter and a greeting as an argument. The function should return a personalized
greeting.

Use conditional statements: Ask the students to write a function that takes a number
as input and returns "even" if the number is even, and "odd" if the number is odd. This
will help them understand how to use conditional statements in functions.

Create a module: Ask the students to create a module with a few functions. For
example, they could create a module with functions for calculating the area of a
rectangle, circle, and triangle.

Use recursion: Ask the students to write a function that uses recursion. For example,
they could create a function that calculates the factorial of a number using recursion.
Write lambda functions: Ask the students to write a few lambda functions. For
example, they could create a lambda function that adds two numbers together.

Use functions with external libraries: Ask the students to use functions from external
libraries, such as the math library. For example, they could create a function that
calculates the square root of a number using the math library.

Handout: Simple Function Example

A function is a block of code that performs a specific task. In Python, functions are
defined using the def keyword followed by the function name, parentheses, and a
colon. The code inside the function is indented.

Here is an example of a simple function that takes two numbers as inputs and returns
their sum:

Now it's your turn! Write a simple function that takes two numbers as inputs and returns
their sum. You can use the example above as a guide.

Simple Function Practice

Write a function called multiply_numbers that takes two numbers as inputs and returns
their product.
Write a function called divide_numbers that takes two numbers as inputs and returns
their quotient.

Write a function called calculate_area that takes the length and width of a rectangle
as inputs and returns the area.

Write a function called calculate_perimeter that takes the length and width of a
rectangle as inputs and returns the perimeter.

Write a function called calculate_volume that takes the length, width, and height of a
rectangular prism as inputs and returns the volume.

Challenge:

Write a function called calculate_hypotenuse that takes the lengths of the two sides of
a right triangle as inputs and returns the length of the hypotenuse.

Handout: Parameters and Arguments Example

In Python, you can define functions that take in parameters and arguments. A
parameter is a variable in the function definition, and an argument is the value passed
to the function when it is called.

Here is an example of a function that takes in a parameter and an argument:


Now it's your turn! Create a function that takes in a name as a parameter and a
greeting as an argument. The function should return a personalized greeting. You can
use the example above as a guide.

Parameters and Arguments Practice

Create a function called double_number that takes in a number as a parameter and


doubles it.

Create a function called add_numbers that takes in two numbers as arguments and
returns their sum.

Create a function called subtract_numbers that takes in two numbers as arguments


and returns their difference.

Create a function called multiply_numbers that takes in two numbers as arguments


and returns their product.

Create a function called divide_numbers that takes in two numbers as arguments and
returns their quotient.

Challenge:

Create a function called calculate_bmi that takes in a person's height and weight as
arguments and returns their body mass index (BMI).

Handout: Conditional Statements Example

In Python, you can use conditional statements to execute different code based on
different conditions. The most common conditional statement is the if statement, which
executes a block of code if a condition is true.

Here is an example of a function that uses a conditional statement to determine if a


number is even or odd:
Now it's your turn! Write a function that takes a number as input and returns "even" if
the number is even, and "odd" if the number is odd. You can use the example above
as a guide.

Worksheet: Conditional Statements Practic

Write a function called is_positive that takes a number as input and returns "positive"
if the number is greater than zero, "negative" if the number is less than zero, and "zero"
if the number is zero.

Write a function called is_vowel that takes a letter as input and returns "vowel" if the
letter is a vowel, and "consonant" if the letter is a consonant.

Write a function called is_divisible that takes two numbers as input and returns
"divisible" if the first number is divisible by the second number, and "not divisible"
[Link] a function called is_leap_year that takes a year as input and returns
"leap year" if the year is a leap year, and "not a leap year" otherwise.
Write a function called is_palindrome that takes a word as input and returns
"palindrome" if the word is a palindrome (the same forwards and backwards), and "not
a palindrome" otherwise.

Challenge:

Write a function called calculate_grade that takes a student's score as input and
returns their letter grade based on the following scale: A (90-100), B (80-89), C (70-
79), D (60-69), F (below 60).

Handout: Creating a Module Example

In Python, you can create a module to group related functions together. A module is
just a file containing Python definitions and statements.

Here is an example of a module containing functions for calculating the area of a


rectangle, circle, and triangle:

To use these functions, you would import the shapes module and call the functions
with the appropriate arguments, like this:
Now it's your turn! Create a module with a few functions. For example, you could
create a module with functions for calculating the area of a rectangle, circle, and
triangle. You can use the example above as a guide.

Worksheet: Creating a Module Practice

Create a module called math_functions with a function called add_numbers that takes
two numbers as arguments and returns their sum.

Add a function called subtract_numbers to the math_functions module that takes two
numbers as arguments and returns their difference.

Add a function called multiply_numbers to the math_functions module that takes two
numbers as arguments and returns their product.

Add a function called divide_numbers to the math_functions module that takes two
numbers as arguments and returns their quotient.

Create a new module called string_functions with a function called reverse_string that
takes a string as an argument and returns the string reversed.

Challenge:

Create a module called temperature_conversion with two functions:


celsius_to_fahrenheit and fahrenheit_to_celsius. These functions should take a
temperature as an argument and return the temperature converted to the appropriate
unit.

Recursion Example

In Python, recursion is a technique where a function calls itself. Recursion can be a


powerful tool for solving problems that can be broken down into smaller, similar
problems.

Here is an example of a recursive function that calculates the factorial of a number:

Now it's your turn! Create a function that uses recursion. For example, you could
create a function that calculates the Fibonacci sequence using recursion. You can use
the example above as a guide.

Recursion Practice

Create a recursive function called countdown that takes a positive integer as an


argument and prints out the numbers from that integer down to 1. For example,
countdown(5) should print out:
Create a recursive function called power that takes two arguments, base and
exponent, and returns base raised to the power of exponent. For example, power(2,
3) should return 8.

Create a recursive function called reverse_string that takes a string as an argument


and returns the string reversed. For example, reverse_string("hello") should return
"olleh".

Create a recursive function called fibonacci that takes a positive integer as an


argument and returns the nth number in the Fibonacci sequence. The Fibonacci
sequence is a series of numbers in which each number is the sum of the two preceding
numbers, starting from 0 and 1. For example, fibonacci(7) should return 13.

Create a recursive function called factorial that takes a positive integer as an argument
and returns the factorial of that number. The factorial of a number is the product of all
positive integers less than or equal to that number. For example, factorial(5) should
return 120.

Challenge:

Create a recursive function called binary_search that takes a sorted list of integers
and a target integer as arguments and returns the index of the target integer in the list,
or -1 if the target integer is not in the list. The binary search algorithm works by
repeatedly dividing the sorted list in half and checking whether the target integer is in
the left half or the right half, until the target integer is found or the list is empty.
Lambda Functions Example

In Python, a lambda function is a small anonymous function that can have any number
of arguments, but can only have one expression. Lambda functions are useful when
you need a small, one-time-use function.

Here is an example of a lambda function that adds two numbers:

To use this function, you would create the function using the lambda keyword, followed
by the parameters and a colon, and then the expression. You can then call the function
like any other function.

Now it's your turn! Create a few lambda functions. For example, you could create a
lambda function that subtracts two numbers, or a lambda function that doubles a
number. You can use the example above as a guide.

Worksheet: Lambda Functions Practice

Create a lambda function called multiply that takes two arguments and returns the
product of the two numbers.

Create a lambda function called is_even that takes a single integer argument and
returns True if the integer is even, and False otherwise.

Create a lambda function called cube that takes a single number argument and returns
the cube of that number.

Create a lambda function called average that takes a list of numbers and returns the
average of those numbers.
Create a lambda function called make_title that takes a string argument and returns
the string with the first letter of each word capitalized. For example, "the quick brown
fox" should become "The Quick Brown Fox".

Challenge:

Create a lambda function called fizz_buzz that takes a single integer argument and
returns the following:

If the integer is divisible by 3, return "Fizz".

If the integer is divisible by 5, return "Buzz".

If the integer is divisible by both 3 and 5, return "FizzBuzz".

Otherwise, return the integer as a string.

For example, fizz_buzz(15) should return "FizzBuzz", and fizz_buzz(4) should return
"4".

Handout: Using External Libraries in Functions

Python has many external libraries that you can use to perform advanced operations.
One such library is the math library, which provides mathematical functions like square
roots, trigonometric functions, and logarithms.

Here is an example of a function that calculates the square root of a number using the
math library:
To use functions from an external library, you need to first import the library using the
import keyword. You can then call the functions from the library just like any other
function.

Now it's your turn! Create a function that uses a function from an external library, such
as the sin function from the math library. You can use the example above as a guide.

Worksheet: Using External Libraries Practice

Create a function called calculate_hypotenuse that takes two arguments, a and b,


representing the lengths of the legs of a right triangle. The function should use the
math library to calculate the length of the hypotenuse of the triangle and return the
result.

Create a function called calculate_volume that takes three arguments, r, h, and π (pi),
representing the radius, height, and pi value, respectively, of a cylinder. The function
should use the math library to calculate the volume of the cylinder and return the result.

Create a function called calculate_area that takes two arguments, r and π (pi),
representing the radius and pi value, respectively, of a circle. The function should use
the math library to calculate the area of the circle and return the result.

Create a function called convert_degrees_to_radians that takes a single argument,


deg, representing an angle in degrees. The function should use the math library to
convert the angle to radians and return the result.

Create a function called calculate_distance that takes four arguments, x1, y1, x2, and
y2, representing the coordinates of two points in a two-dimensional plane. The function
should use the math library to calculate the distance between the two points and return
the result.

Challenge:

Create a function called calculate_mortgage_payment that takes three arguments, P,


r, and n, representing the principal, interest rate, and number of payments,
respectively, of a mortgage. The function should use the math library to calculate the
monthly mortgage payment using the formula:

where M is the monthly mortgage payment. The function should return the result
rounded to two decimal places.

can you suggest activities that students can do to fully understand File Input/Output in
python

Here are some activities that students can do to fully understand File Input/Output in
Python:

Reading a file:

Have students create a text file with some sample data.

Ask them to write a Python program that opens the file and reads the data from it.

They can then print out the data to the console or perform some other operation on
it.

Writing to a file:
Have students write a Python program that takes some user input and saves it to a
file.

They can then open the file and verify that the data was written correctly.

Appending to a file:

Have students modify their writing program to append new data to the file instead
of overwriting it.

They can then verify that the data was appended correctly.

CSV file operations:

Have students create a CSV file with some sample data.

Ask them to write a Python program that reads the data from the CSV file and
performs some operation on it, such as calculating averages or sorting the data.

They can then write the results back to a new CSV file.

Error handling:

Have students intentionally introduce errors into their file I/O programs, such as
trying to read from a file that doesn't exist or writing to a read-only file.

Ask them to modify their programs to handle these errors using try-except blocks.
By completing these activities, students should gain a solid understanding of File
Input/Output in Python and be able to apply this knowledge to real-world programming
problems.

Have students create a text file with some sample data.

Ask them to write a Python program that opens the file and reads the data from it.

They can then print out the data to the console or perform some other operation on
it."

Handout 1: Reading a file:

To learn how to read data from a file in Python.

Instructions:

Create a text file with some sample data. For example, you can create a file called
"[Link]" and add some lines of text to it.

Write a Python program that opens the file and reads the data from it.

Use the following code snippet to read the data from the file:

print(data)

Run the program and verify that it prints out the data from the file to the console.

Modify the program to perform some other operation on the data, such as counting
the number of lines or characters in the file.
What is the name of the file you created?

What is the output of the program?

How can you modify the program to count the number of lines in the file?

Handout 2: Reading a file with a for loop

Objective:

To learn how to read data from a file using a for loop in Python.

Instructions:

Create a text file with some sample data. For example, you can create a file called
"[Link]" and add some lines of text to it.

Write a Python program that opens the file and reads the data from it using a for
loop.

Use the following code snippet to read the data from the file:

Run the program and verify that it prints out each line of the file to the console.

Modify the program to perform some other operation on the data, such as searching
for a specific word or phrase in the file.

What is the name of the file you created?

What is the output of the program?

How can you modify the program to search for a specific word or phrase in the file?
These handouts and worksheets should help students understand how to read data
from a file in Python using different techniques. By completing these activities,
students will gain confidence in their ability to work with files and

Have students write a Python program that takes some user input and saves it to a
file.

They can then open the file and verify that the data was written correctly."

Sure, here are some handouts and worksheets that can help students understand how
to write to a file in Python:

Handout 1: Writing to a file

Instructions:

Write a Python program that takes some user input and saves it to a file.

Use the following code snippet to write the data to the file:

Run the program and enter some data when prompted.

Verify that the data was written to the file by opening it in a text editor.

Worksheet 1: Writing to a file

Objective:

To practice writing data to a file in Python.


Instructions:

Write a Python program that takes some user input and saves it to a file.

Use the following code snippet to write the data to the file:

Run the program and enter some data when prompted.

Answer the following questions:

What is the name of the file the data was saved to?

What happens if you run the program again with different input?

How can you modify the program to append the data to the file instead of overwriting
it?

Handout 2: Writing to a file with a for loop

Instructions:

Write a Python program that uses a for loop to write some data to a file.

Use the following code snippet to write the data to the file:

Run the program and verify that the data was written to the file.

Open the file in a text editor and verify that the data is in the correct format.
Worksheet 2: Writing to a file with a for loop

Write a Python program that uses a for loop to write some data to a file.

Use the following code snippet to write the data to the file:

with open("[Link]", "w") as file:

for i in range(1, 11):

[Link](str(i) + "\n")

Run the program and verify that the data was written to the file.

Answer the following questions:

What is the name of the file the data was saved to?

What happens if you change the range of the for loop?

How can you modify the program to write the data in a different format?

These handouts and worksheets should help students understand how to write data
to a file in Python using different techniques. By completing these activities, students
will gain confidence in their ability to work with files and manipulate data.

Handout 1: Appending to a file

Instructions:

Modify your writing program to append new data to the file instead of overwriting it.

Use the following code snippet to append the data to the file:
Run the program and enter some data when prompted.

Verify that the data was appended to the file by opening it in a text editor.

Worksheet 1: Appending to a file

Instructions:

Modify your writing program to append new data to the file instead of overwriting it.

Use the following code snippet to append the data to the file:

Run the program and enter some data when prompted.

Answer the following questions:

What is the name of the file the data was saved to?

What happens if you run the program again with different input?

How can you modify the program to write the data in a different format?

Handout 2: Appending to a file with a for loop

Objective:

To learn how to append data to a file using a for loop in Python.

Instructions:
Modify your program to use a for loop to append new data to the file.

Use the following code snippet to append the data to the file:

Sure, here are some handouts and worksheets that can help students understand how
to append data to a file in Python:

with open("[Link]", "a") as file:

data = input("Enter some data: ")

[Link](data + "\n")

Run the program and enter some data when prompted.

Verify that the data was appended to the file by opening it in a text editor.

Handout 2: Appending to a file with a for loop

Instructions:

Modify your program to use a for loop to append new data to the file.

Use the following code snippet to append the data to the file:

with open("[Link]", "a") as file:

for i in range(11, 21):

[Link](str(i) + "\n")
Run the program and verify that the data was appended to the file.

Open the file in a text editor and verify that the data is in the correct format.

Instructions:

Modify your program to use a for loop to append new data to the file.

Use the following code snippet to append the data to the file:

Run the program and verify that the data was appended to the file.

Answer the following questions:

What is the name of the file the data was saved to?

What happens if you change the range of the for loop?

How can you modify the program to append the data in a different format?

These handouts and worksheets should help students understand how to append data
to a file in Python using different techniques. By completing these activities, students
will gain confidence in their ability to work with files and manipulate data.

create a CSV file with some sample data.

Ask them to write a Python program that reads the data from the CSV file and performs
some operation on it, such as calculating averages or sorting the data.

They can then write the results back to a new CSV file."
Sure, here are some handouts and worksheets that can help students understand
CSV file operations in Python:

Handout 1: Reading from a CSV file

Objective:

To learn how to read data from a CSV file in Python.

Instructions:

Create a CSV file with some sample data, such as the following:

Run the program and verify that the data was read correctly.

Worksheet 1: Reading from a CSV file

Instructions:
Create a CSV file with some sample data, such as the following:

Run the program and verify that the data was read correctly.

Answer the following questions:

What is the name of the CSV file?

What does the [Link]() function do?

How can you modify the program to only print specific columns from the CSV file?

Handout 2: Writing to a CSV file

Instructions:

Modify your program to calculate the average age of the people in the CSV file.

Write the result to a new CSV file with the following format:
Run the program and verify that the data was written correctly.

Worksheet 2: Writing to a CSV file

Instructions:

Modify your program to calculate the average age of the people in the CSV file.

Write the result to a new CSV file with the following format:

Run the program and verify that the data was written correctly.
Answer the following questions:

What is the name of the output file?

What does the [Link]() function do?

How can you modify the program to calculate a different statistic, such as the
median age?

These handouts and worksheets should help students understand how to perform
CSV file operations in Python. By completing these activities, students will gain
confidence in their ability to work with CSV files and manipulate data.

Handout 1: Reading a non-existent file

Instructions:

Modify your file reading program to try to read from a file that doesn't exist.

Use a try-except block to catch the FileNotFoundError that will be raised.

Use the following code snippet to handle the error:

Run the program and verify that the error is handled correctly.

Handout 2: Writing to a read-only file

Instructions:
Modify your file writing program to try to write to a read-only file.

Use a try-except block to catch the PermissionError that will be raised.

Use the following code snippet to handle the error:

Run the program and verify that the error is handled correctly.

Worksheet: Handling File I/O Errors

Instructions:

Create a program that reads from a CSV file and prints the data to the console.

Intentionally introduce an error into the program, such as trying to read from a file that
doesn't exist.

Use a try-except block to catch the error and handle it appropriately.

Modify the program to write the data to a new CSV file.

Intentionally introduce an error into the program, such as trying to write to a read-
only file.

Use a try-except block to catch the error and handle it appropriately.

Answer the following questions:

What is the purpose of a try-except block?

What types of errors can occur when working with files?

How can you handle errors when working with files in Python?
By completing these activities, students will gain a better understanding of how to
handle different types of errors and write code that is more robust and reliable.

Explore the Python Standard Library: The Python Standard Library is a collection of
modules that come with Python. Students can explore the different modules and see
what functions and classes are available. They can also try using some of the modules
in their own code.

Install and use third-party packages: Students can install third-party packages using
pip or conda and then try using them in their code. They can start with popular
packages like NumPy, Pandas, Matplotlib, and Scikit-learn.

Build a small project using a package: Students can choose a package that they find
interesting and build a small project using it. For example, they can use NumPy to
perform some mathematical operations, or use Matplotlib to create some data
visualizations.

Write a custom package: Students can write their own package with some useful
functions or classes that they can reuse in their own code. They can then install the
package and try using it in different projects.

Read documentation: Students can read the documentation of different packages to


understand how to use them and what functions and classes are available. They can
also look at examples and try to replicate them in their own code.

Participate in online communities: Students can join online communities like Stack
Overflow or Reddit to ask questions and get help with using different packages. They
can also help others who are struggling with similar problems.

By doing these activities, students can gain a deeper understanding of libraries and
packages in Python programming and learn how to use them effectively in their own
projects.

Overview of the Python Standard Library: Provide an overview of the Python


Standard Library and its purpose. Include a list of commonly used modules, such as
os, sys, and math.

:
Example: Using the math module to calculate the square root of a number

Explanation: This code imports the math module and uses its sqrt function to calculate
the square root of the variable number, which is assigned the value 25. The result is
then printed to the console.

Module Reference Sheet: Provide a reference sheet that lists different modules in the
Python Standard Library and their functions and classes. This can serve as a quick
reference guide for students as they work on their projects.

By using these handouts and worksheets, students can explore the different modules
in the Python Standard Library and gain a better understanding of what each module
does and how it can be used in their own code. They can also practice using the
modules in their own code and refer back to the reference sheet and code examples
as needed.

Introduction to Third-Party Packages:

Provide an overview of what third-party packages are, why they are useful, and how
they can be installed using pip or conda.

Package Installation Worksheet: Provide a worksheet that guides students through


installing different third-party packages using pip or conda. The worksheet should
include a list of popular packages, such as NumPy, Pandas, Matplotlib, and Scikit-
learn, and step-by-step instructions for how to install each package. For example:
Package: NumPy

How to install using pip:

Code Examples: Provide code examples that demonstrate how to use different
third-party packages in Python. For each example, include an explanation of what the
code does and how it works. For example:

Example: Using NumPy to perform mathematical operations on arrays

Explanation: This code imports the NumPy package and creates two arrays, x and y.
It then uses the [Link] function to add the two arrays together element-wise and prints
the result to the console.
Package Reference Sheet: Provide a reference sheet that lists different third-party
packages and their functions and classes. This can serve as a quick reference guide
for students as they work on their projects.

Choosing a Package: Provide a list of popular packages and their functions to help
students choose a package that they find interesting. Examples of popular packages
include NumPy, Pandas, Matplotlib, and Scikit-learn.

Project Proposal Worksheet: Provide a worksheet that guides students through


brainstorming and proposing a project idea that utilizes their chosen package. The
worksheet should include prompts to help students identify what they want to
accomplish with their project, what data they will use (if applicable), and how the
package will be used in the project.

Project Plan Worksheet: Provide a worksheet that helps students plan out the
different steps they will need to take to complete their project. The worksheet should
include sections for identifying the package functions or classes they will use, writing
pseudocode for their code, and creating a timeline for completing the project.

Code Review Worksheet: Provide a worksheet that helps students review and
improve their code. The worksheet should include prompts for reviewing their code for
readability, efficiency, and accuracy, and identifying potential areas for improvement.

Introduction to Documentation: Provide an overview of what documentation is, why


it is important, and where to find documentation for different packages.

Documentation Worksheet: Provide a worksheet that guides students through


reading the documentation for a specific package. The worksheet should include
prompts for identifying the purpose of the package, identifying the available functions
and classes, and writing pseudocode for how to use the package in their own code.

Examples Worksheet: Provide a worksheet that guides students through replicating


examples from the documentation. The worksheet should include prompts for
identifying the purpose of the example, writing the code to replicate the example, and
explaining how the example can be used in their own code.
Code Review Worksheet: Provide a worksheet that helps students review and
improve their code based on the documentation. The worksheet should include
prompts for identifying potential areas for improvement in their code, and for explaining
how the code can be improved based on the documentation.

By using these handouts and worksheets, students can learn how to read
documentation in Python and gain a deeper understanding of how to use different
packages in real-world applications. They can also practice important skills such as
identifying the purpose and functionality of different packages, writing pseudocode,
and code review, and receive feedback on their work.

Introduction to Online Communities: Provide an overview of what online


communities are, why they are important, and how to join and participate in different
communities.

Asking for Help Worksheet: Provide a worksheet that guides students through
asking for help in an online community. The worksheet should include prompts for
identifying the problem, providing relevant code and context, and asking specific
questions that can help others understand the problem and provide useful feedback.

Helping Others Worksheet: Provide a worksheet that guides students through


helping others in an online community. The worksheet should include prompts for
identifying problems that others are struggling with, writing helpful and informative
responses, and providing examples and code snippets that can help others solve their
problems.

Netiquette Worksheet: Provide a worksheet that helps students understand and


practice appropriate behavior and communication in online communities. The
worksheet should include prompts for identifying appropriate and inappropriate
behavior, and providing examples of how to communicate effectively and respectfully
in different situations.

By using these handouts and worksheets, students can learn how to participate in
online communities and get help with using different packages. They can also practice
important skills such as problem-solving, communication, and collaboration, and
receive feedback on their work.

You might also like