0% found this document useful (0 votes)
24 views21 pages

ProgrammingBooklet Level2

Uploaded by

knajjar149
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)
24 views21 pages

ProgrammingBooklet Level2

Uploaded by

knajjar149
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
You are on page 1/ 21

#Programming Booklet

#Coding Practice

Level 2(Grade 7)

• Python Coding Guide


• Coding Tasks and Projects
Table of Content:

Chapter1-Python Coding Guide

• Comments
• Variables
• Strings
• Data Type
• Arithmetic Operators
• Loops
• User Input
• List
• Conditions and IF statement.
• Functions

Chapter2- Coding Practice

2.1- Basic Practice Tasks

• Task1- Calculator Function


• Task2 - Room Area and Perimeter
• Task 3- Shopping List
• Task 4- Display Odd Numbers
• Task5- Greatest Number
• Task6- Ambient Light
• Task7- AM or PM?
• Task 8- 24h to 12h

Page 2
• Task 9- Sum of numbers
• Task 10- Letter grading
• Task 11- Strings
• Python Exercises

2.2- Coding Projects

• Project 1: Sales Data Analysis


• Project 2- Password Strength Checker

Page 3
Chapter1- Python Coding Guide

What is Python?

Python is a popular programming language. It was created by Guido van Rossum, and
released in 1991. It is used for:
• web development (server-side),
• software development,
• mathematics,
• system scripting.

Python Syntax

Python Indentation
Indentation refers to the spaces at the beginning of a code line.
Where in other programming languages the indentation in code is for readability only, the
indentation in Python is very important.
Python uses indentation to indicate a block of code.

Example
if 5 > 2:
print("Five is greater than two!")

1- Comments

• Comments can be used to explain Python code.


• Comments can be used to make the code more readable.
• Comments can be used to prevent execution when testing code

Python has commenting capability for the purpose of in-code documentation.


Comments start with a #, and Python will render the rest of the line as a comment:

Example:
#This is a comment.
print("Hello, World!")

Comments can be placed at the end of a line, and Python will ignore the rest of the line:
Example
print("Hello, World!") #This is a comment

Multi Line Comments


Python does not really have a syntax for multi line comments.
To add a multiline comment you could insert a # for each line:
#This is a comment

Page 4
#written in
#more than just one line
print("Hello, World!")

2- Variables

In Python, variables are created when you assign a value to it:


Example
x=5
y = "Hello, World!"

Variables do not need to be declared with any particular type, and can even change type
after they have been set.

Example
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Many Values to Multiple Variables

Python allows you to assign values to multiple variables in one line:

Example
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)

3- Strings
Strings in python are surrounded by either single quotation marks, or double quotation
marks.

'hello' is the same as "hello".


You can display a string literal with the print() function:

Example
print("Hello")
print('Hello')

Assigning a string to a variable is done with the variable name followed by an equal sign
and the string:
Example
a = "Hello"

Page 5
print(a)

Multiline Strings
You can assign a multiline string to a variable by using three quotes:
Example
You can use three double quotes:
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."""

print(a)
Try it Yourself »
Or three single quotes: '''

4- Data Type and Casting

Built-in Data Types


Variables can store data of different types, and different types can do different things.

Python has the following data types built-in by default, in these categories:

Text Type: str


Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray,
memoryview

Casting:

If you want to specify the data type of a variable, this can be done with casting.

Example
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0

Get the Type

You can get the data type of a variable with the type() function.

Page 6
Example
x=5
y = "John"
print(type(x))
print(type(y))

Setting the Data Type

In Python, the data type is set when you assign a value to a variable:

Example Data Type


x = "Hello World" str
x = 20 int
x = 20.5 float
x = 1j complex
x = ["apple", "banana", "cherry"] List

Type Conversion

You can convert from one type to another with the int(), float(), and str() methods:
Example
Convert from one type to another:

x = 1 # int
y = 2.8 # float

#convert from int to float:


a = float(x)
#convert from float to int:
b = int(y)
print(a) →
print(b) →

5- Arithmetic Operators

Arithmetic operators are used with numeric values to perform common mathematical
operations:

Operator Name Example


+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y

Page 7
6- Loops

A. For Loop

for loop is used for iterating over a sequence


Looping Through a list

Print each fruit in a fruit list:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)

Looping Through a String

Loop through the letters in the word "banana":

for x in "banana":
print(x)

The range() Function


To loop through a set of code a specified number of times, we can use the range() function,

The range() function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a specified number.

Example

Using the range() function:

for x in range(6):
print(x). # This will print (x) 6 times

Note that range(6) is the values 0 to 5.

B. While Loop

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

Example

Print i as long as i is less than 6:

Page 8
i=1
while i < 6:
print(i)
i += 1
Note: remember to increment i, or else the loop will continue forever.

7- User Input

Python allows for user input. That means we are able to ask the user for input.

Python 3.6 uses the input() method.

Example
username = input("Enter username:")
print("Username is: " + username)

8- List
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store collections of data, the other 3
are Tuple, Set, and Dictionary, all with different qualities and usage.

Lists are created using square brackets:


Example

Create a List:

thislist = ["apple", "banana", "cherry"]

print(thislist)

List Items
List items are ordered, changeable, and allow duplicate values.
List items are indexed, the first item has index [0], the second item has index [1] etc.

List Length
To determine how many items a list has, use the len() function:

Example
Print the number of items in the list:
thislist = ["apple", "banana", "cherry"] print(len(thislist))

Page 9
9- Conditions and If statements

Python supports the usual logical conditions from mathematics:


• _Equals: a == b
• _Not Equals: a != b
• _Less than: a < b
• _Less than or equal to: a <= b
• _Greater than: a > b
• _Greater than or equal to: a >= b

These conditions can be used in several ways, most commonly in "if statements" and loops.

Example
a = 33
b = 200
if b > a:
print("b is greater than a") # notice the indentation

Else & Elif


The else keyword catches anything which isn't caught by the preceding conditions.

The elif keyword is pythons way of saying "if the previous conditions were not true, then
try this condition".

Example1
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")

Example2

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

Nested If
You can have if statements inside if statements, this is called nested if statements.
Example

Page 10
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")

10- Functions

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

You can pass data, known as parameters, into a function.

A function can return data as a result.

A. Creating a Function

In Python a function is defined using the def keyword:

Example
def my_function():
print("Hello from a function")
B. Calling a Function

To call a function, use the function name followed by parenthesis:

Example
def my_function():
print("Hello from a function")

my_function()

Page 11
Chapter2- Coding Practice

2.1- Basic Practice Tasks

Task1- Calculator Function

Write a program that performs the following:

Create a function calculation() that:


• Accepts two variables from the user input and calculate addition and subtraction.
• It must return both addition and subtraction in a single return call.

Call the function with values of your choice.

Task2 - Room Area and Perimeter

Write a program that performs the following:

• Ask the user to enter the room dimensions: Length & Width (Store them in two
variables)

• Calculate the area using the formula: A = W*L then display it.

• Calculate the perimeter using the formula: P = (W+L)*2 then display it.

Make sure to have the output in proper statements

Task 3- Shopping List

Write a program that performs the following:

• Ask the user to enter different items, store them in a list variable.

• Offer different options to the user like: adding new item, remove item, Display the
list, search for specific item to check if there or not.

Use appropriate Python functions to perform each.

Page 12
Task 4- Display Odd Numbers

Write a program to display all odd numbers between 0-50.

Hint: Use while loop, with specific start and specific increment(+2)!

Task5- Greatest Number

Write a program to perform the following:

• Accept 3 user-input numbers


• Check the greatest among them.
• Print the greatest in a proper statement ( “ The greatest number is : ….”)

Task6- Ambient Light

Ambient light program will be uploaded to the microcontroller to detect the darkness.
Write a program that performs the following:

• Ask the user to enter the light sensor reading value (usually between 0-1023)

• Check the input value, if it was less than 100, then display “Dark”
• Otherwise, display “Light”

Task7- AM or PM?

Write a program that performs the following:

• Ask the user to enter the enter the time as an hour value (24-hour clock).
• Check to specify if the entered time is AM or PM.
• The output should be like “The time…. hour value… is pm”

Hint: -It’s AM if the hour value <12


- Make sure to cast the input to Int

Page 13
Task 8- 24h to 12h

Modify the program to convert the entered 24- hour clock to the 12-hour clock value with
showing am/pm beside the 12-hour value

Example:
Input Output
10 10 AM
14 2 PM

Task 9- Sum of numbers

Write a program that performs the following:

• Ask the user to enter a number


• Calculate the sum of all number from 1 to the entered number(using for loop).

Example: for the input 5, the output should be the result of 1+2+3+4+5.

Task 10- Letter grading

He school has following rules for passing grade system:

o 50 to 60 - C
o 60 to 80 - B
o Above 80 – A

Write a program to perform the following:

• Ask the user to enter the mark (1-100)


• Check if the user has the passing mark (>=50), print the corresponding grading
letter.
• Otherwise, alert the user that he did not pass.

Page 14
Task 11- Strings

String Methods

Python has a set of built-in methods that you can use on strings.

Note: All string methods return new values. They do not change the original string.

Method Description

capitalize() Converts the first character to upper case

lower() Converts string into lower case

upper() Converts a string into upper case

center() Returns a centered string

count() Returns the number of times a specified value occurs in a string

Write a program that performs the following:

• Ask the user to enter a string of 3 words.


• Convert the first character of the string to upper case and print it.
• Display the entire string on upper case.
• Display the centered word
• Display how many times the letter a occurs in the string.

For more practice: Python Exercises

Page 15
2.2- Coding Projects

Project 1: Sales Data Analysis

In this project, you'll be working with a set of sales data to perform various tasks related to
analysis and reporting. The goal is to enhance your Python skills by incorporating good
coding practices and applying fundamental concepts such as data types, variable creation,
and mathematical operations.

This Project provides evidence for GC3.1-GC3.5

Tasks:

1. Set Up the Project:

• Create a new Python script (e.g., sales_analysis.py).


• Initialize the script with comments providing an overview of the project and your
name.

2. Data Preparation:

• Create variables to store essential information about a product, such as product


name, unit price, and quantity sold.
• Utilize comments to explain the purpose of each variable.

3. String Variables and Multiline Strings:

• Create a string variable using single quotes to store the name of the product.
• Assign a multiline string to another variable using three quotes to store a brief
description of the product.

4. Data Type Casting:

• Create variables to represent the total sales and average price per unit.
• Use appropriate data types (int, float) and practice casting when necessary.
• Comment on the reason behind choosing specific data types.

5. Mathematical Operations:

Perform common mathematical operations using the main arithmetic operators


(+, -, *, /) to:
• Calculate the total revenue generated from the sales data.
• Calculate the profit margin percentage (profit divided by total revenue).

Page 16
6. Display Results:

• Print out the calculated values with meaningful messages.


• Include comments to explain the purpose of each output statement.

7. Challenge (Optional):

Implement user input to allow users to input sales data dynamically (e.g., quantity sold,
unit price).
Adjust your calculations based on user input.
Ensure the code remains readable and well-commented.

Expected Output:

Page 17
Project 2- Password Strength Checker

In this project, you'll develop a Python program that assesses the strength of a user-
entered password. The program will utilize various concepts, including loops, conditional
statements, functions, and user input, to provide real-time feedback on the password's
strength.

This Project provides evidence for GC3.6-GC13.

Tasks:

1- Set Up the Project:

• Create a new Python script (e.g., password_checker.py).


• Introduce the script with comments providing an overview of the project and
your name.

2- User Input and Looping:

• Use the input() function to prompt the user to enter a password.


• Implement a while loop to keep asking for a password until it meets certain
criteria.

3- For Loop to Print Each Letter:

• Use a for loop to iterate through the entered password and print each letter on a
new line.
• Ensure the loop also counts and prints the total number of characters in the
password.

4- Password Strength Criteria:

• Implement an if statement to check if the entered password:


o Has a minimum length of 8 characters.
o Includes both uppercase and lowercase letters.
o Contains at least one numeric digit.
o Contains at least one special character (e.g., @, #, $).

5- Conditional Statements:

• Use basic logical operations (<, >, ==, !=) in the if statements to check the
conditions mentioned above.
• Print messages indicating the strength of the password based on the fulfilled
conditions.

Page 18
6- Function Creation and Calling:

• Define a function named check_password_strength to encapsulate the password-


checking logic.
• Call the function with the user-entered password.

7- User Feedback:

• Print a final message indicating whether the password is strong or needs


improvement.
• Provide specific feedback based on the conditions that were met or not met.

Submission:

• Submit the Python script (.py file) with comments explaining each step of your
code.
• Include any additional documentation or comments that might help others
understand and use your script..

Expected Output :

Use case1:

Page 19
Use case2:

Page 20
Page 21

You might also like