Fundamentals of Programming
Fundamentals of Programming
Fundamentals of Programming
Computer Program
A collection of instructions that can be executed by a computer to perform a specific
task.
Question...
How did a computer (or an app, smartphone, etc.) simplified your life, as a
person/student? Programming Languages
A vocabulary containing a set of grammatical rules intended to convey instructions
to a computer to perform specific tasks.
• Machine Language
• Assembly Language
• Procedural Language
Examples include Python, C++, Java, C#
Algorithm
A set of rules that precisely defines a sequence of operations.
Algorithm
• Logical process by which a problem can be solved or a decision made, it
can be presented through Flowchart and Pseudocode
• Algorithms are used extensively in computer programming to arrive at a
solution for a problem Types of Algorithms
● Sequence
• Linear type of programming or algorithms.
● Branching (Selection)
• Example: Write an algorithm to find the greater number between two
numbers.
Start
Read(Input A and B)
If A greater than A then C = A
If B greater than A then C = B
Print C
End
Types of Algorithms
● Loop (Repetition Structure)
• Unbounded – number of iterations depends on the eventuality that the
termination condition is satisfied.
• Bounded – refer to those whose number of iterations is known beforehand.
• Infinite – trip around the loop.
Algorithm
Guide when developing an Algorithm:
1. Identify the problem
2. Determine the input and the processes
3. Write down the algorithm
Problem: Calculate the average of three numbers Input:
Three numbers (a, b, and c) Process:
Add the three numbers together Divide the sum by 3 to get the average Output:
The average of the three numbers
Conditional Statement
It refers to statements that will result to a Boolean value, which is either True or
False.
Let’s Check
• Today is Thursday
• Letter A is a number
• The temperature is 28 °C
• Elon Musk invented diesel engine
NOTE: Actual programming constructs follows specific rules of how to write
conditional statements, this will discussed in the succeeding topics.
Relational Operators
An operator that tests some kind of relation between two entities.
It refers to the symbols used to compare the relationship between two values.
Logical Operators-Allow a program to make a decision based on multiple conditions.
It refers to keywords used to perform chained operations on multiple or complex
conditions.
and or not
Logical Operators
1. Enable fire alarm, if smoke is detected AND level is greater than 5.
temperature is above 50 °C
1. Turn OFF device, if OR device is idle.
available
1. Enable generator, if power is NOT.
Logical Operators
Example of a Conditional Statements that uses any relational and logical operators.
X = 10
Y =5
If x > y and x % 2 == 0
Therefore, x is greater than y and x is an even number.
Otherwise, either x is not greater than y or x is not an even number .
What is a Flowchart?
It refers to the visual representation that illustrates the step-by-step sequence
of actions, decisions, and processes necessary to complete or solve a specific
task.
Flowchart symbols
Initialization Block
Declaration refers to the mentioning what variables are being read for later usage.
Initialization refers to setting of initial values to a specific variable.
NOTE: Only one entering and one exiting arrow is allowed for each initialization
block.
Advantages of using flowchart
• Easier for the programmer to explain the logic of the program
• Flowcharts provide a strong documentation in the overall documentation of
the software system.
• A flowchart is very helpful in the process of debugging a program.
What is Pseudocode
• Pseudocode is another programming analysis tool, which is used for planning program logic.
• “Pseudo” means imitation or false, and “code” refers to the instructions written in a programming
language.
• So, it is an imitation of actual computer instructions.
What is Pseudocode 2
What is Pseudocoding
It refers to the
method of designing algorithms using a simplified
and human-readable representation of a code.
NOTE: There is no strict or standardized rule of what specific words are to be used when writing
pseudocodes, it should also not be bounded to a specific language used in programming.
What is Pseudocode 3
Sequence Logic
Sequence logic is used for performing instructions one after another in sequence.
Process 1 Process 2
Pseudocode
What is Pseudocode/Sequence Logic 4
Selection Logic
Selection logic is used for selecting the proper path, out of two or more alternative paths, in the
program logic
It uses control structures called IF.....THEN, IF.....
THEN......ELSE .
IF condition
THEN Process 1 ELSE Process 2
ENDIF
What is Pseudocode/Selection Logic 5
Pseudocode
• SET: Preparing the variable to be used.
• READ / INPUT: use this when asking input from the user or reading data
from the storage.
• COMPUTE: when you want to compute something or performs an operation.
• DISPLAY / PRINT: use to display the output.
• IF... THEN / ELSE: decision-making process.
• REPEAT... UNTIL or DO... WHILE: when there is an iteration/looping
Python Basics Lesson 2
Outline:
1. Input/PrintFunction
2. OutputFormatting
3. ImportFunction
4. String Operations
5. List Methods
6. Slicing
7. Operators and Basic Mathematical Function
8. Built-in Functions
Input/Output (I/O)
The purpose of a program is to get an input, process it, optionally store it, and display the results
afterwards. Python has functions that allow the programmer to get user input and display messages.
Input Function
• The input() function takes input from the user and returns it.
• To store a value, it can be assigned to a variable using the syntax below.
<variable> = input(<message>) Example:
value = input("Enter a value: ")
Input Function
Example:
number = input(“Enter a number: “)
Enter a number: 10 10
Note that the inputted value 10 is a string. You need to convert this into a number. Use int() or float()
functions.
Input Function
number = int(input("Enter a number: "))
the value must be compatible when in comes of conversion
Print Function
• In order to display something, the print() function can be used.
Example:
value = input("Enter a value: ")
print(value)
Output Formatting
Sometimes we would like to format our output to make it look attractive. This can be done by using the
str.format() method. This method is visible to any string object.
Output Formatting
For example: x = 5; y = 10
print(“The value of x is {} and y is {}”.format(x,y)) Output:
The value of x is 5 and y is 10.
The curly braces {} are used as placeholders.
Output Formatting
Another example:
print(‘ I love {0} and {1} ‘ .format(‘bread’, ’butter’)) print( ‘ I love {1} and {0}’ .format(‘bread’, ’butter’))
Output:
I love bread and butter I love butter and bread
The curly braces {} are used as placeholders. We can specify the
order in which they are printed by using numbers (tuple index).
Output Formatting
We can also use keyword arguments to format the string.
print(‘Hello {name}, {adj}’.format(adj =
‘Handsome’, name = ‘John’))
Result:
Hello John, Handsome
Output Formatting
Another way to format:
Example: x =5
y = 10
print(f“The value of x is {x} and y is {y}”)
Output: The value of x is 5 and y is 10
Output Formatting
Example: x =5
y = 10
total = x + y
print(f"The sum of the two integer is {total}")
Output: The sum of the two integer is 15
Output Formatting
Import in Python
• Definitions inside a module can be imported to another module or the interactive interpreter in
Python.
• We use the import keyword to do this. Example:
import math
print(math.pi)
Import in Python
import math pi = math.pi
print(f"The value of pi is {pi}.")
result = math.factorial(5) print(f"5 factorial: {result}")
Import in Python
import math
pi = math.pi
print("The value of pi is", pi)
result = math.factorial(5) print("5 factorial: ", result)
Import in Python
• We can also import some specific attributes and functions only, using the from keyword.
Example:
from math import pi
pi
Import in Python
Example:
from statistics import mean, median
numbers = [1, 2, 3, 4, 5] average = mean(numbers) middle = median(numbers)
print(f"The mean is: {average}") print(f"The median is: {middle}")
Import in Python
Math Module:
https://docs.python.org/3/library/math.html
String Operations
String Operations
NOTE: Applicable on strings only.
String Operations
NOTE: Applicable on strings only.
String Operations
NOTE: Applicable on strings only.
String Operations
the strip() method is a string method that returns a copy of the string with leading and trailing
whitespace removed.
String Operations
the upper() method is a string method that returns a copy of the string with all characters converted to
uppercase.
String Operations
the lower() method is a string method that returns a copy of the string with all characters converted to
lowercase.
String Operations
the capitalize() method is a string method that returns a copy of the string with the first character
converted to uppercase and all other characters converted to lowercase.
String Operations
the title() method is a string method that returns a copy of the string with the first character of each
word capitalized and the remaining characters in lowercase.
String Operations
String Operations
List Methods
List can be modified by adding or removing a value.
Other methods can also be applied to further manipulate its contents.
List Methods
inventory = [] # create a list # Add a new item
inventory.append("screw")
# insert a new item at a specific index
inventory.insert(0, "hammer")
List Methods
inventory = [“hammer", “screw"]
# remove at specific index
inventory.pop(1)
# remove the first occurrence
inventory.remove(“hammer")
List Methods
inventory = [“hammer", “screw”]
# count total occurrences
count = inventory.count("hammer") print(f"Occurrence: {count}")
# get index of first occurence
index = inventory.index("screw") print(f"Index: {index}")
# get the total items in the list; using len() function
print(len(inventory))
List Methods
inventory = [“hammer", “screw”]
# change value on specific index
inventory[1] = "screw driver"
# access value on specific index
print(inventory[1])
List Methods
inventory = [“hammer", “screw driver”]
more_items = ["pliers", "tie wire"]
# extend list with more items
inventory.extend(more_items)
# clear all contents
inventory.clear()
Slicing
What is Slicing?
A way to get values in an ordered sequence.
NOTE: Applicable on Strings, Lists, and Tuples only
Slicing
Slicing
Operators and
Basic Mathematical Function
Arithmetic operators
Arithmetic operators are used to perform mathematical operations like addition, subtraction,
multiplication, etc.
Arithmetic operators
Arithmetic operators
Example
Note: we can also use this:
a=x+y
print(f"x + y = {a}")
x = 15 y=4
print('x + y =',x+y) # Output: x + y = 19
print('x - y =',x-y) # Output: x - y = 11
print('x * y =',x*y) # Output: x * y = 60
Arithmetic operators
Example
x = 15 y=4
print('x / y =',x/y) # Output: x / y = 3.75
print('x // y =',x//y) # Output: x // y = 3
print('x ** y =',x**y) # Output: x ** y = 50625
Arithmetic operators
Increment
age = 5
age += 1 # increment print(age)
Output: 6
Comparison operators
Comparison operators are used to compare values. It returns either True or False according to the
condition.
Comparison operators
Comparison operators
Example
Note: we can also use this:
a=x>y
print(f"x > y = {a}")
x = 10 y = 12
# Output: x > y is False
print('x > y is',x>y) # Output: x < y is True
print('x < y is',x<y)
# Output: x == y is False
print('x == y is',x==y)
Comparison operators
Example
x = 10 y = 12
# Output: x != y is True
print('x != y is',x!=y) # Output: x >= y is False
print('x >= y is',x>=y)
# Output: x <= y is True
print('x <= y is',x<=y)
Assignment operators
Assignment operators are used in Python to assign values to variables.
Assignment operators
Sample Program
1.Compute the area of a triangle given the length of its three sides: a,b,c w ith formulas:
Sample Program
NOTE:
In the str.format method, the last placeholder has a value of :0.2f, was used to format the number of
decimal places to be displayed. It follows this syntax:
{<index>:<format-specifier>}
import
math
a
= int(input ('Side a: '))
b
= int(input ('Side b: '))
c
= int(input ('Side c: '))
s
A
= (a + b + c) / 2
= math.sqrt(s*(s-a) * (s-b) * (s-c))
print
sides:
(f"The area of a triangle given the length of three
\
\na = {a}\nb = {b}\nc = {c}\nis: {A:0.2f}")
Sample Program
2. Calculating the Area and Perimeter of a Rectangle
Sample Program
w = int(input ('Width: '))
l = int(input (‘Length: '))
A=w*l
print(f"The area of a rectangle is {A}")
Sample Program
w = int(input ('Width: '))
l = int(input ('Length: '))
P = 2 * (w + l)
print(f"The perimeter of a rectangle is
{P}")
Sample Program
w = int(input ('Width: '))
l = int(input ('Lenght: '))
A=w*l
P = 2 * (w + l)
print(f"Area of the rectangle: {A}\
\nPerimeter of a rectangle: {P}")
Built-in Functions
These are pre-loaded "commands" that simplifies the work of any programmers.
Built-in Functions
Built-in Functions
NOTE: Used on strings that are numeric in nature.
Built-in Functions
NOTE: Used on Strings, Lists, Tuples, and Sets
NOTE: Used on Lists, Tuples, and Sets containing numeric values only.