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

Module 3 ICT

The document is a module on Python programming focusing on predefined functions and their applications. It covers learning objectives, prior knowledge, and provides activities for students to practice using functions like abs(), pow(), and random, as well as concepts such as function arguments and the import statement. Additionally, it includes exercises on Boolean expressions and selection statements, emphasizing the importance of programming structures and conditional operators.

Uploaded by

schermainejoyp
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 views15 pages

Module 3 ICT

The document is a module on Python programming focusing on predefined functions and their applications. It covers learning objectives, prior knowledge, and provides activities for students to practice using functions like abs(), pow(), and random, as well as concepts such as function arguments and the import statement. Additionally, it includes exercises on Boolean expressions and selection statements, emphasizing the importance of programming structures and conditional operators.

Uploaded by

schermainejoyp
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/ 15

7

Information and Communications Technology 7


Quarter 3 – Module 3
What is It

Ashton Bron
Schermaine Joy D. Presno Mikylla Anog
Name: Partner:

It’s Time to Explore Deeper Pythons

Python Activity 4: Predefined Functions

“How can I use the built-in code that is already part of Python?”

Learning Objectives
Students will be able to:
Content:
✓ explain the purpose of a predefined function
✓ explain the functions: abs(), pow(), int() round(), random
✓ explain the math library functions: floor() and ceil()
✓ explain the use of the import statement
✓ explain the purpose of a function argument
Process:
✓ write code that uses predefined functions
Prior Knowledge
✓ Python concepts from Activities 1-3
✓ Understanding of flowchart input symbols
Further Reading
✓ Transitioning from Visual Logic to Python: Chapter 4

Let’s go Pythons!
Go to windows search and type Python. Open IDLE and refer to the image below.

1
Let’s organize what’s in your mind

Model 1: Predefined functions in


Python

print(), round(), abs(), pow(),


int(), etc. are known as
predefined functions. Information
that a functionneeds to do its work is
sent to the function between the
parentheses (). This information is
known as an argument.

To use a function, call the function.


input(“Enter your name”) is a call
to the input function sending the
string “Enter your name” as an
argument

It’s time to be critical Pythons

1. Circle the predefined functions in the following program and explain why.

# Loop through the


numbers 1-10 and print
the corresponding
# Loop through the
multiplication table
numbers 1-10
There are two predefined functions in thisand
for codeprint
i in the input11):
range(1, () and print ()or the input(“enter
the corresponding
your name:”) and print(“name:”,name). The input () functions
print(f"{num} x {i} = for the user to enter their
name by displaying the message “enter your
multiplication tablename”* and
{num i}") then the input is stored in the
variable name. The print() for
predefined function
i in range(1, 11):will display the name inserted by the user so
he can see what he has inputted.
print(f"{num} x {i} =
2. Draw a line between each {numstatement
* i}") in the Python program and its
corresponding statement in the flowchart.
Corresponding Statement:
Output: abs(-4.67)
Output: power(5,3)
Output: power(49, .5)
Output: int(34.8)
Output: round(6.9)
Output: random(50)

2
3. Enter and execute the Python program on the previous page.

a. What is the output for each statement?

• print(abs(-4.67)) answer: 4.67


• print(pow(5,3)) answer: 125
• print(pow(49,.5)) answer: 7.0
• print(int(34.8)) answer: 34
• print(round(6.9)) answer:7
• import random
print(random.randint(1,100))
answer:76

b. What is the difference between the round()function and the int()


function? The difference between the int() and round() functions is the int() will drop the decimal portion of a
number and convert it to an integer or it always rounds down to the nearest integer, for example. print
(int(34.8)) the answer will be 34 while round()can round a number to the nearest integer or a specific
number of decimal places for example. print (round(6.9)) the answer would be 7.

4. What is the output for each line of code? Verify your answers by
executing the code and explain theanswer given by the interpreter.
a. abs(4.5) a. abs(4.5) returns the absolute value of 4.5,
b. int(“678”) which is 4.5.
b. int("678") converts the string "678" to the
c. round(-5.6) integer 678.
c. round(-5.6) rounds the number -5.6 to the
d. import random nearest integer, which is -6.
random.randint(4,10) d. random.randint(4,10) generates and returns
a random integer between 4 and 10, inclusive.

What is the purpose of “import random”? What happens if you omit


that line of code?
The purpose of code import random is used to import the random in Python. The random provides a set of functions
for generating random numbers and performing other operations that involve randomness, such as shuffling lists and
selecting random elements. If you omit the line code the import random, will not have access to the functions and
classes provided by the random. Any attempt to call a function or use a class from the random without importing it
first would result in a NameError, indicating that the name is not defined.

5. Write a definition of a predefined function.


Predefined functions perform specific operations and are designed to make common
programming tasks easier and more efficient. Examples of predefined functions in
Python include print(), len(), abs(), range(), type(), and str(), among many others.
6. Circle the argument in the following predefined function:
number = 45.78
answer = round(number)
There is no limit to the number
7. How many arguments can a function have? of arguments a function can
have in Python.
8. answer = pow(4,3). What is/are the argument(s) in this code?
There are two arguments, in answer = pow(4,3). Which is the base, and the exponent. In this case, the base is 4
and the exponent is 3, so the pow() function will return 4 to the 3 power, and the answer would be 64.

9. If a function contains more than one argument, do you think the order
of the arguments makes adifference? Explain your answer.
Yes, the order of arguments can make a significant difference in the behavior of a
function. Arguments are passed to a function in the order they are defined in the function
signature. If the order of the arguments is changed when calling the function, the
behavior of the function will change as well because that is how you code it.

3
4. Execute the following code:

import math
x = 4.7
y = 5.3
z = -4.8
a = -3.2
print(math.ceil(x))
print(math.ceil(y))
print(math.ceil(z))
print(math.ceil(a))
print(math.floor(x))
print(math.floor(y))
print(math.floor(z))
print(math.floor(a))

a. Explain what the ceil() function does.


The ceil() function is a predefined function where it rounds a given number up to the
nearest integer, also known as the "ceiling" of the number.

b. Explain the purpose of the floor() function.


The floor() function is a predefined function where it rounds a given number down to
the nearest integer, also known as the "floor" of the number.

c. Why are the calls to the math() and ceil() functions preceded by
“math.”?
The calls to the math() and ceil() functions are preceded by "math." because these
functions are defined in the math module of the Python standard library.

Let’s get it on Pythons!


(NOTE PT-OUTPUT 1: On this part, you need to screencast or video record while doing the hands-on activity)

Application Questions: Use the Python interpreter to design and check your work

1. Write a line of code that prints the integer portion of the number 21.45.
X=int(21.45)
print(x)
Answer= 21

2. Write code that prompts the user for a floating-point number and prints
the smallest integer that islarger than the number the user entered.
import math
num =float(input(“Enter a floating-point number:”))
next_int=math.ceil(num)
print(f”The smallest integer that is larger than {num} is {next_int}.”)

3. Write a line of code that prints a random number between one and 6.
import random
print(random.randint(1, 6))

4
4. Assume that a user enters any number and that the number is stored
in the variable userNumber.Write a line of code that converts the input
to a float. Then write a line of code that prints the positive value of the
user’s input.
userNumber = input("Enter a number: ")
userNumber = float(userNumber)
print(abs(userNumber))

5. Write a line of code that calculates the square root of 900 and stores the
result in the variable answer.
import math
answer = math.sqrt(900)
print(answer)

5
What’s More

Let’s get this done Pythons


Python Activity 5: Boolean Expressions and Selection Statements
“True or False and Making Choices”

Learning Objectives

Students will be able to:


Content:
✓ explain the three types of programming structures
✓ explain how conditional operators and logical operators are used
in programming
✓ use conditional operators with strings and numeric values
✓ implement the Python syntax of an if/else statement
✓ determine good test data for programs that include if/else
statements
Process:
✓ write code that includes if statements and if/else statements
✓ write correct Boolean expressions and compound expressions
Prior Knowledge
✓ Python concepts from Activities 1-4
✓ Understanding of flowchart input symbols
Further Reading
✓ Transitioning from Visual Logic to Python: Chapter 5

It’s time to be critical Pythons

Model 1: Programming Structures


Sequence Structure Decision or Branching Structure Looping Structure

6
1. Each of the flowchart symbols in the chart above represents lines or
segments of code. After examining the chart, write a description of:

a. sequence structure
The sequence structure is represented by the rectangular symbol in the flowchart. It represents a
series of instructions or code that are executed in a sequential order, one after the other, without
any branching or repetition.
b. decision or branching structure
The decision or branching structure is represented by the diamond-shaped symbol in the
flowchart. It is used to make decisions based on a certain condition. If the condition is true, the
program will follow one path of execution, and if it is false, it will follow another path of execution.
c. looping structure
The looping structure is represented by the oval-shaped symbol in the flowchart. It is used to execute a series
of instructions or code repeatedly, until a certain condition is met. The loop may be executed a fixed number of
times or until a certain condition is satisfied, such as when a particular value is reached.

2. Which structure best describes the types of Python programs you have
written so far? Do you think this structure is the best structure to use
for all programs? Why or why not?
The structure that best describes the types of Python programs I have written so far is the
sequence structure. However, depending on the task at hand, I have also used decision
structures and looping structures. I don't think any one structure is the best to use for all
programs, as the best structure to use will depend on the specific task at hand and the
complexity of the program.

3. Which structure allows the programmer to create code that decides what
code is executed?
The decision or branching structure allows the programmer to create code that decides
what code is executed based on a certain condition.

Model 2: Conditional Operators


Conditional operators, also known as relational operators, are used to
compare the relationshipbetween two operands. Expressions that can only
result in one of two answers are known as
Boolean expression.

4. Determine the meaning of each of the following conditional operators.


If you are not sure of the meaning of any symbol, create some example
expressions, type them into the Python interpreter (see figure to the
right) and examine the results.

a. <
a. < : less than, it returns true if the value on the
b. > left is less than the value on the right.
c. <= b. > : greater than, it returns true if the value on
d. >= the left is greater than the value on the right.
e. != c. <= : less than or equal to, it returns true if the
f. == value on the left is less than or equal to the value
on the right.
d. >= : greater than or equal to, it returns true if
the value on the left is greater than or equal to
the value on the right.
e. != : not equal to, it returns true if the value on
the left is7not equal to the value on the right.
f. == : equal to, it returns true if the value on the
left is equal to the value on the right.
5. What is the result of each of the following expressions?
Assume x = 4, y = 5, z = 4
a. False
a. x > y
b. True
b. x < y c. False
c. x == y d. True
d. x != y e. True
e. x >= z f. True
f. x <= z g. True
g. x + y > 2 * x h. False
h. y * x – z != 4 % 4 + 16 i. True
i. pow(x,2) == abs(-16)

6. What is the result of the following expressions?


Assume word1 = “hello”, word2 = “good-bye”

a. word1 == word2 false


b. word1 != word2 true
c. word1 < word2 true
d. word1 >= word2 false

7. Explain how the conditional operators are used when the operands are
strings.
When the operands of the conditional operators are strings, the operators compare the values of
the characters in the strings based on their ASCII values. For example, "apple" < "banana" because
the ASCII value of "a" is less than the ASCII value of "b". If the two strings are of different lengths,
the comparison is made character by character until a difference is found, or until the end of one of
the strings is reached.
8. There are only two possible answers to the expressions in questions 5
and 6. What are they?
The two possible answers to the expressions in questions 5 and 6 are True and
False.

Model 3: IF/ELSE Statement


Flow chart Python Program

9. What is the Python code equivalent of the diamond flowchart symbol in


the program above?
This code checks whether the value of the variable grade is greater than or equal to
94. If it is, the code inside the if statement, which is the print("Excellent!") statement
in this case, will be executed. If the condition is not true, the code inside the if
statement will be skipped.

8
10. Enter and execute the following code. Use various values for the
original cost and the sale price.

11. Explain what the following lines of code do. Each line appears in the
program above.

a. originalPrice = int(originalPriceString)
This line converts the string value of originalPriceString to an integer and
assigns it to the variable originalPrice.

b. percentOff =(originalPrice salePrice)/originalPrice * 100


This line calculates the percentage off by subtracting the sale price from the
original price, dividing the result by the original price, and multiplying by 100.
The result is assigned to the variable percentOff.
print("Sale price: $%.2f" %salePrice)
This line prints the sale price with two decimal places.

c. print("Percent off: %2d" % percentOff + "%")


This line prints the percentage off as a whole number with a percent sign.

d. if percentOff >= 50:


print("You got a great sale!")
This line checks if the percentage off is greater than or equal to 50%, and if it is,
prints two messages: one indicating that the sale was great and the other
congratulating the user.
12. Revise the program in #10. If the percent off is 50% or more print
“Congratulations!” in addition to what is already printed. Use a second
print statement to do this. Write the code for this part of the program.
originalPriceString = input("Enter the original cost of the item: ")
originalPrice = float(originalPriceString)
salePriceString = input("Enter the sale price: ")
salePrice = float(salePriceString)
percentOff = (originalPrice - salePrice) / originalPrice * 100
print("Original price: $%.2f" % originalPrice)
print("Sale price: $%.2f" % salePrice)
print("Percent off: %2.0f%%" % percentOff)
if percentOff >= 50:
print("You got a great sale!")
print("Congratulations!")
print("Done!")
13. Revise the program in #12 so that it prints “Done!” when the program
is complete – no matter what the percent off is. How does the
placement of this line of code differs from the placement of the code
created for #12?
originalPriceString = input("Enter the original cost of the item: ") The placement of the
originalPrice = float(originalPriceString)
print("Done!") statement is
salePriceString = input("Enter the sale price: ")
salePrice = float(salePriceString) different from the code added in
percentOff = (originalPrice - salePrice) / originalPrice * 100 question 12 because it is placed
print("Original price: $%.2f" % originalPrice) outside the if block, which
print("Sale price: $%.2f" % salePrice) means it will always be
print("Percent off: %2.0f%%" % percentOff)
if percentOff >= 50:
executed regardless of the value
print("You got a great sale!") of percentOff.
print("Congratulations!") 9
print("Done!")
Python Program

Flowchart

14. Compare the flowchart above with the corresponding Python Program.
Carefully compare if/elsestatement in the two programs. Enter and
execute the Python program above.

a. Test the program at least three times. List the three-test data you
used and the corresponding output. Explain why they were the
best data to use as a test for the program.
Test 1: temperature = 200 => Output: "The water is not boiling."
Test 2: temperature = 212 => Output: "Water is boiling."
Test 3: temperature = 250 => Output: "Water is boiling."

b. Now you want to add another print statement to the Python


program above so that it printed “That’s really hot!” when the
water is 212 degrees or hotter. Rewrite the code below with this
statement included.
temperatureString = input("Enter the water temperature in degrees Fahrenheit: ")
temperature = int(temperatureString)

if temperature >= 212:


print("Water is boiling.")
if temperature >= 300:
print("That's
FYI: We can really
usehot!")
logical operators to determine logic between
else:
print("The water is not boiling.")

print("Done!")

10
15. Sometimes you want to test more than one condition to determine
which code segment should be executed? You can use the following
logical operators to create compound conditions. Examineeach
operator and a sample of its use. Provide an explanation of how each
operator works.

Operator Example Explanation


both conditions must be true for the entire
and (age >= 17) and (hasLicense = = true) expression to be true. If either condition is false, the
entire expression will be false.
used to create a compound condition that requires at
or (cost < 20.00) or (shipping = = 0.00) least one of the conditions to be true in order for the
overall expression to be true.
used to create a negation of a condition. It returns
not not (credits> 120) True if the original condition is false, and vice
versa.

16. Assume the value of the variable numBooks is 40. State the
values of each of the Booleanexpression.

Expression Value
(numBooks > 5) and (numBooks < 100) true

(numBooks < 5) or (numBooks > 100) false

not(numBooks * 10 == 100) true

17. Suppose you want to determine if a student is ready to graduate. The 3


criteria for graduation are that the student has earned at least 120
credits, their major GPA is at least 2.0 and their general GPA is also at
least 2.0.

if numCredits
Missing >=expression
Boolean 120 and majorGPA >= 2.0 and overallGPA >= 2.0:

18. Which Boolean expression would be the correct test for Python code?
a. numCredits >= 120 or majorGPA >= 2.0 or overallGPA >= 2.0
b. numCredits > 120 and majorGPA > 2.0 or overallGPA > 2.0
c. numCredits > 119 and majorGPA >= 2.0 and overallGPA >= 2.0
d. numCredits >= 120 and majorGPA >= 2.0 and overallGPA >= 2.0

11
19. Enter and execute the program in #16. Include your choice for the
correct Boolean expression. Create several data sets to test all
possibilities for the Boolean expression. List the data you usedto test
all possibilities for the expression.

Data
numCredits majorGPA overallGPA Expression Result (True or False)
Set
1 119 1.5 1.8 False
2 120 1.5 1.8 False
3 119 2.0 1.8 False
4 119 1.5 2.0 False
5 120 2.0 1.8 False
6 120 1.5 2.0 False
7 119 2.0 2.0 False
8 120 2.0 2.0 False
9
10

Let’s get it on Pythons!


(NOTE PT-OUTPUT 1: On this part, you need to screencast or video record while doing the hands-on activity)

Application Questions: Use the Python interpreter to design and check your
work

1. Write a Boolean expression that tests if the value stored in the variable
num1 is equal to the value stored in the variable num2.
num1 == num2

2. Write a Boolean expression that tests if the value stored in the variable
time is less than the valuestored in the variable maxTime or if the
value stored in the variable cost is less than the value stored in the
variable maxCost
time < maxTime or cost < maxCost

3. Write the code for an if statement that adds 5 to the variable num1 if
the value stored in the variable testA equals 25. Otherwise subtract 5
from num1.
if testA == 25:
num1 += 5
else:
num1 -= 5
4. Write the code for an if statement that prints a random number
between one and 6 if the value stored in the variable isValid equals the
Boolean value true.
if isValid == True:
import random
print(random.randint(1, 6))

12
# prompt user for cost of two items
item1_cost = float(input("Enter the cost of item 1: "))
item2_cost = float(input("Enter the cost of item 2: "))
5. Write a Python program that prompts# the user for the cost of two items
calculate total cost of items
to be purchased. Then prompt the user for= their
total_cost item1_costpayment.
+ item2_cost If they enter
an amount that is less than the total cost of the
# prompt user for payment two items, print a
message that tells them how much they still owe. Otherwise, print a
payment = float(input("Enter your payment: "))

messagethat thanks them for their payment and


# check if payment tells
is less them
than total cost how much
if payment < total_cost:
change they will receive. Thoroughly test your =code
amount_due total_costfor all possible input.
- payment
print("You still owe: $" + str(amount_due))
else:
change = payment - total_cost
print("Thank you for your payment. Your change is: $" + str(change))

6. Write a Python program that prompts the user for a word. If the word
comes between the word’s apple and pear alphabetically, print a
message
# prompt userthat tells the user that the word is valid, otherwise,tell the user
for a word
the
wordword is out
= input("Enter a word:or
") range.

# check if word is valid


if 'apple' < word < 'pear':
print("The word is valid.")
else:
print("The word is out of range.")

7. Write a Python program that prompts the user for a multiple of 5


between 1 and 100. Print amessage telling the user whether the
number they entered is valid.
# prompt user for a multiple of 5 between 1 and 100
num = int(input("Enter a multiple of 5 between 1 and 100: "))

# check if number is valid


if num % 5 == 0 and 1 <= num <= 100:
print("The number is valid.")
else:
print("The number is invalid.")

References
https://www.python.org/
https://www.python.org/downloads/
https://wiki.python.org/moin/PythonBooks
https://www.programiz.com/python-programming
https://www.programiz.com/python-programming/online-compiler/

For inquiries or feedback, please write or call:

Department of Education – Schools Division Office of Makati City

Gov. Noble St., Brgy. Guadalupe Nuevo


City of Makati, Metropolitan Manila, Philippines 1212

Telefax: (632) 8882-5861 / 8882-5862

Email Address: makati.city@deped.gov.ph

13

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy