0% found this document useful (0 votes)
6 views

Midterm

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Midterm

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

--------------------REVIEW MATERIALS-------------

Introduction to Python 3 Programming

--------------------REVIEW MATERIALS ----------------------------------

Intellectual Property of: Engr. James Francis B. Aguilar and the University of Nueva Caceres
Intended for the use in the UNC Curriculum of COMPUTER FUND & PROGRAMMING
Any unauthorized production of these materials is prohibited and punishable by
Intellectual Property Act of the Philippines

Introduction:

Python facilitates a disciplined approach to computer-program design. In this first programming


chapter, we introduce Python programming and present several examples that illustrate important
features of the language. After presenting basic concepts, we examine the structured programming
approach in the late chapters

INTRODUCTORY APPROACH

▪ High level language programming software


▪ Window Base or Online Python Compiler

I. First Program in Python: Printing a Line of Text

Example 1.1

1. # Fig. 2.1: fig02_01.py


2. # Text-printing program
3. # Printing a line of text in Python
4.
5. print ("Welcome to Python!")

OUTPUT:

Welcome to Python!

This program illustrates several important features of the Python language

• Lines 1-3 begin with the pound symbol (#), which indicates that the remainder of the
line is a comment
• The Python print command (line 5) instructs the computer to display the string of
characters contained between the quotation marks
• A string is a sequence of characters inside the double quotes. The entire line is called a
statement.
• In some programming languages, like C/C++ and Java, statements must end with a
semicolon.
UNIVERSITY OF NUEVA CACERES COMP. FUND & PROGRAMMING

Escape Sequence Description


\n Newline. Position the cursor
at the beginning of the next
line
\t Horizontal tab. Move the
cursor to the next tab stop
\a Alert. Sound the system bell

\\ Backslash. Insert a
backslash character in a
string
\” Double quote. Insert a
double quote character in a
string

Example 1.2 MODIFYING OUR FIRST PYTHON PROGRAM

1. # Fig. 2.4: fig02_04.py


2. # Printing a line with multiple statements.
3.
4. print ("Welcome", end=" ")
5. print ("to Python!")

OUTPUT:

Welcome to Python!

This program illustrates several important features of the Python language

• Line 4 displays the string "Welcome". Normally, after the print statement displays its
string, Python begins a new line.
• However, the comma (,) and end= at the end of line 4 tells Python not to begin a new
line but instead to add a space after the string
• Thus, the next string the program displays (line 5) appears on the same line as the string
Welcome

Prepared by: JAMES FRANCIS B. AGUILAR, ECE 1


UNIVERSITY OF NUEVA CACERES COMP. FUND & PROGRAMMING

Objectives: (Laboratory 2.0)

By the end of activity, the student should be able to:


1. Understand a typical Python program-development environment.
2. Write simple computer program in Python and to use simple input and output
statements

Procedure(s):

I. Compile the following source code

A.

1. # Printing multiple lines with a single print


2.
3. print ("Welcome\nto\nPython\nProgramming!\n")

Output:

B.

1. # Printing on one line with multiple print statement


2.
3. print ("Welcome", end=" ")
4. print ("to", end=" ")
5. print ("Python", end=" ")
6. print ("Programming!")

Output and Explanations:

Question:
Differentiate the given code using print syntax in program
A & B.
___________________________________________________________
___________________________________________________________
_______________________________________________________.

Prepared by: JAMES FRANCIS B. AGUILAR, ECE 2


UNIVERSITY OF NUEVA CACERES COMP. FUND & PROGRAMMING

II. Describe the following Python String method

Use:
name = "write your complete name in lowercase"
EX. name = “juan dela cruz”

Python String Output


Method

name.upper()

name.lower()

name.title()

name.capitalize()

len(name)

III. Using the techniques you learned, write a program that displays these message

a. Display this message using print and string method keyword


(upper(), lower(),capitalize(),. Etc.)

MY FIRST LESSON IN PYTHON PROGRAMMING

1. #THIS IS A COMMENT
2. PRINTING A LINE OF A TEXT

ESCAPE SEQUENCES USED


\n NEW LINE
\t HORIZONTAL TAB
\a ALERT SYSTEM BELL
\\ INSERT BACKSLASH CHARACTER

Prepared by: JAMES FRANCIS B. AGUILAR, ECE 3


UNIVERSITY OF NUEVA CACERES COMP. FUND & PROGRAMMING

b. Display this message using MULTIPLE print keyword

CONVERSION OF NUMBER SYSTEMS

BINARY OCT

000 0
001 1
010 2
011 3
100 4
101 5
110 6
111 7

Questions:

1. What is the function of these code:

# pound symbol
______________________________________________

______________________________________________

______________________________________________

end=" "
______________________________________________

______________________________________________

______________________________________________

print
______________________________________________

______________________________________________

______________________________________________

Prepared by: JAMES FRANCIS B. AGUILAR, ECE 4


UNIVERSITY OF NUEVA CACERES COMP. FUND & PROGRAMMING

Laboratory Exercise 2.1


Memory Concepts, Arithmetic and String

Introduction:

In programming, a variable is a storage that hold data. But unlike C and C++, Python is a type-
inferred language, so you don’t have to explicitly define the variable type. It automatically knows that a
given variables is a string, an integer or a floating number.

The Arithmetic operators are some of the Python programming operator, which are used to
perform arithmetic operations includes operators like Addition, Subtraction, Multiplication, Division and
Modulus. All these operators are binary operators which means they operate on two operands

PYTHON VARIABLES

Example 2.1

1. # assign the value 10 to number variable


2. number = 10
3.
4. print (number)

OUTPUT: 10

Example 2.2

1. # assign value to python_name variable


2. python_name = 'This is a string'
3.
4. print (python_name)

OUTPUT: This is a string

MEMORY CONCEPT (UNDERSTANDING VARIABLES)

▪ Variable names correspond to locations in the computer’s memory


▪ Every variable has a name, a type and a value

DESTRUCTIVE READ-IN

Prepared by: JAMES FRANCIS B. AGUILAR, ECE 5


UNIVERSITY OF NUEVA CACERES COMP. FUND & PROGRAMMING

▪ The process of reading information into a memory wherein the value replaces the previous
value in that location

COMMON PROGRAMMING ERROR

▪ An attempt to divide by zero is normally undefined on computer systems and generally results in
a fatal error

▪ Fatal error are errors that causes the program to terminate immediately without having
successfully performed its job

▪ Non-fatal errors allow programs to run to completion, often producing incorrect results

RULES OF OPERATOR PRECEDENCE


▪ Multiplication, division and remainder operation are applied first

▪ Addition and subtraction operations are evaluated next

▪ Evaluation process from left to right (associativity of the operators)

Example 2.3

1. # assign multiple values to multiple variables


2.
3. a, b, c = 5, 3.2, 'hello'
4.
5. print (a)
6. print (b)
7. print (c)

OUTPUT: 5
3.2
hello

Example 2.4

1. # Simple addition program


2.
3. integer1 = input (“Enter first integer:\t")
4. integer2 = input ("Enter second integer:\t")
5.
6. sum = int(integer1) + int(integer2)
7.
8. print ("Sum is", sum)

OUTPUT: Enter first integer: 45

Prepared by: JAMES FRANCIS B. AGUILAR, ECE 6


UNIVERSITY OF NUEVA CACERES COMP. FUND & PROGRAMMING

Enter second integer: 72


Sum is 117
CASTING
Casting is the process of converting one data type into another
x = int(10)

print("Number is " + str(x))


x = "10"
y = "10"

print(int(x) + int(y))

OPERATORS
Operators: These are special symbols used to perform operations on data. Some
common operators include:
• Arithmetic Operators: (+, -, *, /) for calculations.
• Comparison Operators: (==, !=, <, >, <=, >=) for comparing values.
• Logical Operators: (and, or, not) for combining conditions.

# Example 1: Using variables and data types


number = 10 # Integer
message = "Welcome!" # String

# Example 2: Using arithmetic operators


total = number + 5

Prepared by: JAMES FRANCIS B. AGUILAR, ECE 7


UNIVERSITY OF NUEVA CACERES COMP. FUND & PROGRAMMING

STRING FORMATTING FUNCTION


upper()
converts a string into upper case
string.upper()

lower()
converts a string into lower case
string.lower()

capitalize()
converts a string into upper case
string.capitalize()

split()
splits the string at the specified separator and returns a list
string.split(separator, maxsplit)

title()
converts the first character of each word to uppercase
string.title()

len()
count characters in a string
len(string)

replace()
returns a string where a specified value is replace with a specified value
string.replace(oldvalue, newvalue, count)

Prepared by: JAMES FRANCIS B. AGUILAR, ECE 8


UNIVERSITY OF NUEVA CACERES COMP. FUND & PROGRAMMING

Objectives: (Laboratory 2.1)

1. To be able to analyze a simple math problem and convert it to Python programs


2. To be able to use simple arithmetic operations in Python

Procedure(s):

A. (Digits of an Integer) 40 pts. Write a program that inputs a five-digit integer password,
separates the integer into its digits and prints them separated by three spaces each. [Hint:
Use the integer division and modulus operators.] For example, if the user types in 12345, the
program should print:

1 2 3 4 5

B. (Diameter, Circumference and Area of a Circle)30pts. Write a program that reads in the cross-
sectional radius of the wire as an integer and prints the wire’s diameter, circumference and
area. Use the constant value 3.14159 for π. Do all calculations in output statements.

C. (Power, Voltage and Current) 30pts. Write a program that reads in the voltage and current of
the given system and computes power rating of it.

D. Please write a Python script that assigns values to four variables: str(student_name),
str(course),int(age), and str(gender). Once assigned, kindly print the data in the specified
format, without errors. Ensure that you follow the instructions precisely, using the correct
syntax and format for the code. Please note that the output must be in uppercase, title-case,
string format, and capitalized format for name, course, age, and gender, respectively. Thank
you for your attention to detail.

Prepared by: JAMES FRANCIS B. AGUILAR, ECE 9


UNIVERSITY OF NUEVA CACERES COMP. FUND & PROGRAMMING

Laboratory Exercise 2.2


Decision Making

Introduction:

If the Boolean expression evaluates to true, then the if block will be executed, otherwise, the
else block will be executed. Python programming language assumes any non-zero and non-null values as
true, and if it is either zero or null, then it is assumed as false value.

Python uses indentation to delimit (distinguish) sections of code. Other programming languages
often use braces to delimit sections of code. A suite is a section of code that corresponds to the body of
a control structure.

The If Selection Statement


• The if selection statement performs an indicated action only when the condition is true;
otherwise, the action is skipped.

The If...else Selection Statement

• The if… else selection statements allow the programmer to specify that the different actions are
to be performed when the condition is true than when the condition is false

The If... elif… else Selection Statement

• The if...else statement is used to execute a block of code among two alternatives.
• However, if we need to make a choice between more than two alternatives, then we use the
if...elif...else statement.

Prepared by: JAMES FRANCIS B. AGUILAR, ECE 10


UNIVERSITY OF NUEVA CACERES COMP. FUND & PROGRAMMING

Example 3.1

1. # Compare integers using if structures, relational operators


2. # and equality operators.
3.
4. print ("Enter two integers, and I will tell you")
5. print ("the relationships they satisfy.")
6.
7. # read first string and convert to integer
8. number1 = input("Please enter first integer: ")
9.
10. # read second string and convert to integer
11. number2 = input("Please enter second integer: ")
12.
13. if number1 == number2:
14. print (number1, "is equal to", number2)
15.
16. if number1 != number2:
17. print (number1, "is not equal to", number2)
18.
19. if number1 < number2:
20. print (number1, "is less than", number2)
21.
22. if number1 > number2:
23. print (number1, "is greater than", number2)

Prepared by: JAMES FRANCIS B. AGUILAR, ECE 11


UNIVERSITY OF NUEVA CACERES COMP. FUND & PROGRAMMING

Example 3.2
1. # Example 3.2
2. # A grade program by Engr. JF. Aguilar
3.
4. print ("This program will tell you if you passed or failed")
5.
6. # read first entry and convert the string to float
7. grade = float(input ("\nEnter your grade from 0 to 100:\t"))
8.
9. # the if... elif and else condition
10. if grade > 100:
11. print ("\n\nNOT A VALID GRADE!!!\n\n\n")
12. elif grade == 100:
13. print ("\n\nP E R F E C T !!!.", end=" ")
14. print ("Your grade is A.\n\n")
15. elif grade>=89:
16. print ("Passed: Your grade is A\n\n")
17. elif grade>=79:
18. print("\n\nPassed: Your grade is B\n\n")
19. elif grade>=69:
20. print("Passed: Your grade is C\n\n")
21. elif grade>=59:
22. print("\n\nPassed: Your grade is D\n\n")
23. else:
24. print("\n\nFAILED ! ! ! \n\n\n")
25.

Prepared by: JAMES FRANCIS B. AGUILAR, ECE 12


UNIVERSITY OF NUEVA CACERES COMP. FUND & PROGRAMMING

Objectives: (Laboratory 2.2)

1. To be able to write a simple program using if and else statements


2. To be able to use simple arithmetic operations in decision-making problems

Procedure(s):

A. (Arithmetic, Smallest and Largest) 40 pts. Write a program that inputs three integers from the
keyboard and prints the sum, average, product, smallest, and largest of these numbers. The
screen dialog should appear as follows:

Input three different integers: 100 17 14


Sum is 131
Average is 43
Product is 23800
Smallest is 14
Largest is 100

B. (Odd or Even)30 pts. Write a program that reads an integer and determines and prints whether
it’s odd or even. [Hint: Use the modulus operator. An even number is a multiple of two. Any
multiple of two leaves a remainder of zero when divided by 2.]

C. (If…else statement)30 pts. Write your own Python code that will utilize if…else statements, in
which it differentiates the state of a certain object. Using any of these, <, >, >=, <=, == or! =

Prepared by: JAMES FRANCIS B. AGUILAR, ECE 13


UNIVERSITY OF NUEVA CACERES COMP. FUND & PROGRAMMING

Laboratory Exercise 2.3


Algorithms and Pseudocodes

Introduction:
Before writing a program to solve a particular problem, it is essential to have a thorough
understanding of the problem and a carefully planned approach to solving the problem. When writing a
program, it is equally essential to understand the types of building blocks that are available and to use
proven program-construction principles.

Repetition executes a sequence of statements multiple times and abbreviates the code that
manages the loop variable. It is more like a while statement, except that it tests the condition at the end
of the loop body.

FORMULATING ALGORITHM

Algorithms

A procedure for solving a problem in terms of


• The actions to be executed
• The order in which these actions are to be executed

Control Structures

1. Sequential execution

• Statements in a program are executed one after the other in the order in which they are
written

2. Transfer of control

• Enable the programmer to specify that the next statement to be executed may be other
than the next one in sequence

Pseudocode

• Is an artificial and informal language that helps programmers develop algorithms.

Prepared by: JAMES FRANCIS B. AGUILAR, ECE 14


UNIVERSITY OF NUEVA CACERES COMP. FUND & PROGRAMMING

• The pseudocode is useful for developing algorithms that will be converted to structured
C programs

Example 1:

Pseudocode
1. If student’s grade is greater than or equal to 60
2. Print “Passed”

Equivalent Python program


1. If grade >=60:
2. print ("\n\nPassed\n ")

Example 2:

Pseudocode
1. If student’s grade is greater than or equal to 60
2. Print “Passed”
3. Else
4. Print “Failed”

Equivalent Python Program


1. if (grade >= 60):
2. print ("\n\nPassed\n ")
3. else:
4. print ("\n\nFailed\n ")

Prepared by: JAMES FRANCIS B. AGUILAR, ECE 15


UNIVERSITY OF NUEVA CACERES COMP. FUND & PROGRAMMING

Objectives: (Laboratory 2.3)

1. To be able to generate simple loop programs in Python.


2. To be able to differentiate the while and for loops.

Procedure(s):

I. Compile the following source code and write the output in the box

A.

1. # A counter from 1 to 10
2. # using while repetition statement
3.
4. counter = 1
5.
6. #using while to count from 1 to 10
7. while counter<=10:
8. print (counter, end="\n")
9. counter=counter+1

Output

Write your own pseudocode for Code I.A

Prepared by: JAMES FRANCIS B. AGUILAR, ECE 16


UNIVERSITY OF NUEVA CACERES COMP. FUND & PROGRAMMING

B.
1. # A countdown from 10 to 1
2. # using while repetition statement
3.
4. countdown = 10
5.
6. #using while to reverse count from 10 to 1
7. while countdown >= 1:
8. print (countdown, end="\n")
9. countdown=countdown-1

Output

Write your own pseudocode for Code I.B

Prepared by: JAMES FRANCIS B. AGUILAR, ECE 17


UNIVERSITY OF NUEVA CACERES COMP. FUND & PROGRAMMING

II. Give the description of the following operators

OPERATORS DESCRIPTION

==

>

<

>=

<=

III. Compile the following codes and write a pseudocode

A.

1. # use of range() to define a range of values


2. # range(start, stop, step)
3.
4. values = range(10)
5.
6. # iterate from i = 1 to i = 10
7. for i in values:
8. print(i+1)

Write a pseudocode

Prepared by: JAMES FRANCIS B. AGUILAR, ECE 18


UNIVERSITY OF NUEVA CACERES COMP. FUND & PROGRAMMING

B.

1. # use of range() to define a range of values


2. # range(start, stop, step)
3.
4. values = range(10,0,-1)
5.
6. # iterate from i = 10 in step of -1 to i = 1+1
7. for i in values:
8. print(i)

Write a pseudocode

Questions:

1. What are the functions of these code?

While
______________________________________________

______________________________________________

______________________________________________

Prepared by: JAMES FRANCIS B. AGUILAR, ECE 19


UNIVERSITY OF NUEVA CACERES COMP. FUND & PROGRAMMING

for
______________________________________________

______________________________________________

______________________________________________

counter=counter+1
______________________________________________

______________________________________________

______________________________________________

range() function
______________________________________________

______________________________________________

______________________________________________

2. What is the difference between while and for repetitions in


looping?

___________________________________________________________
___________________________________________________________
___________________________________________________________
___________________________________________________________
_______________

3. Write a code using (while and for) utilizing this loop

1
4
9
16
25
36
49
64

Prepared by: JAMES FRANCIS B. AGUILAR, ECE 20


UNIVERSITY OF NUEVA CACERES COMP. FUND & PROGRAMMING

81

Laboratory Exercise 3.0


Generating a Loops

Introduction:

Tasks performed by computers consist of algorithms. An algorithm is a well-defined procedure


that allows a computer to solve a problem. A particular problem can typically be solved by more than
one algorithm. Optimization is the process of finding the most efficient algorithm for a given task.

THE GENERAL FORMAT OF THE FOR AND WHILE STATEMENT

for element in sequences:


statement(s)

initialization
while loopContinuationTest:
statement(s)
increment

Function range can take one, two or three arguments.


1. If we pass one argument to the function,
that argument called end, is one greater
than the upper bound (HIGHEST VALUE) of the
sequences
2. If we pass two arguments, the first
argument, called start, is the lower bound
-the lowest value in the returned sequence
-and the second argument is end.
3. If we pass three arguments, the first
argument called start, and end,
respectively, and the third argument,
called increment, is the increment value.

range (10) #[0 1 2… 9]


range (0, 10) # 0 – (end-1)

Prepared by: JAMES FRANCIS B. AGUILAR, ECE 21


UNIVERSITY OF NUEVA CACERES COMP. FUND & PROGRAMMING

range (0, 10, 1) #(start)-(end-1)

Example 4.1 (WHILE LOOP)


1. # A counter from 1 to 10
2.
3. counter = 1
4.
5. #using while to count from 1 to 10
6.
7. while counter<=10:
8. print (counter, end="\n")
9. counter=counter+1

Example 4.2 (FOR LOOP)


1. # use of range() to define a range of values
2.
3. values = range(10)
4.
5. # iterate from i = 1 to i = 10
6.
7. for i in values:
8. print(i+1)

FORMULATING ALGORITHM
1. CASE STUDY 1 (Counter-Controlled Repetition)
• This technique uses a variable called a counter to specify the number of times a set of
statements should execute
• Is often called definite repetition because the number of repetitions is known before the
loop begins executing

2. CASE STUDY 2 (Sentinel-Controlled Repetition)


• Formulating algorithms with Top-down, Stepwise Refinement
• Is often called indefinite repetition because the number of repetitions is not known before
the loop begins executing.
• One way to solve this problem is to use a special value a sentinel value (also called a signal
value, a dummy value, or a flag value)

Prepared by: JAMES FRANCIS B. AGUILAR, ECE 22


UNIVERSITY OF NUEVA CACERES COMP. FUND & PROGRAMMING

3. CASE STUDY 3 (Nested-Controlled Structures)


• A double-selection statement will determine whether each result either option 1 or
option 2
• And will increment the appropriate counters accordingly

ASSIGNMENT OPERATORS

• C provides several assignment operators for abbreviating assignment expressions

c=c+3;

 Can be abbreviated with the addition assignment operator += as

c +=3;

 The += operator adds the value of the expression on the right of the operator to the value of
variable on the left of the operator and stores the result in the variable on the left of the
operator

variable=variable operator expression;

variable operator=expression;

PSEUDOCODE

• Is an artificial and informal language that helps programmers develop algorithms


• It is similar to everyday English
• Are not actually executed on computers
• Helps the programmer to think out a program before attempting to write it in a programming
language such as C++

FLOW CHART

• Is a graphical representation of an algorithm


• Are drawn using certain special symbols such as ovals, rectangle, diamonds, and small circles
connected by arrows –flowlines

Prepared by: JAMES FRANCIS B. AGUILAR, ECE 23


UNIVERSITY OF NUEVA CACERES COMP. FUND & PROGRAMMING

EXAMPLE 5.1(PROBLEM SOLVING)


1. One large chemical company pays its salespeople on a commission
basis. The salespeople receive $200 per week plus 9% of their
gross sales for that week. For example, a salesperson who sells
$5000 worth of chemicals in a week receives $200 plus 9% of
$5000, or a total of $650. Develop a program that will input each
salesperson’s gross sales for last week and will calculate and
display that salesperson’s earnings. Process one salesperson’s
figures at a time.

STEP IN CREATING C PROGRAM

1. Create an Algorithm
2. Create a Pseudocode
3. Convert Pseudocode into a Python Equivalent Program

1. CREATE AN ALGORITHM
• STEP 1 -START
• STEP 2 -declare 2 float sales and salary
• STEP 3 -define values of initial sales and salary
• STEP 4 -obtain new values for sales
• STEP 5 -compute for the salary using the equation given
• STEP 6 -store and print the salary
• STEP 7 -repeat STEP 1 if the sentinel is not pressed
otherwise STOP

2. CREATE A PSEUDOCODE
• Input sales in dollars
• While the sales is not equal to -1
• Compute for the salary = 0.09*sales + 200
• Print the sales in 2 decimal places
• Repeat procedure #2 otherwise print PROGRAM ENDED

Prepared by: JAMES FRANCIS B. AGUILAR, ECE 24


UNIVERSITY OF NUEVA CACERES COMP. FUND & PROGRAMMING

3. PYTHON Program

1. ##Python program to compute the salary based on


2. #SALARY = 0.09 * SALES + 200
3.
4. sales = float(input("Enter sales in dollars (-1 to end):\t"))
5.
6. while (sales!=-1):
7. salary=0.09*sales+200;
8. print("Salary is:", round(salary,2) , end="\n\n")
9. sales = float(input("Enter sales in dollars (-1 to
end):\t"))
10.
11. print("PROGRAM ENDED\n\n")

--------------------REVIEW MATERIALS ----------------------------------

Intellectual Property of: Engr. James Francis B. Aguilar and the University of Nueva Caceres
Intended for the use in the UNC Curriculum of COMPUTER FUND & PROGRAMMING
Any unauthorize production of these materials is prohibited and punishable by Intellectual Property Act
of the Philippines

Prepared by: JAMES FRANCIS B. AGUILAR, ECE 25

You might also like