Phoemela T.
Dela CruzfinalsICT-104
Logprog reviewer –[email protected]
lecture
I. Advanced Repetition Structures Pattern (Error Trap): This
This section focuses on using loops for is typically a while loop
practical, real-world programming that repeats as long as the
challenges like handling user input and input is bad.
managing complex iterative tasks. 1. Get the initial input
A. While Loops and Sentinel- before the loop.
Controlled Loops 2. while input is invalid:
The while loop is a condition- Display an error
controlled loop that repeats a message.
block of statements as long as Re-prompt the
its Boolean condition is True. It user to enter a
is a pretest loop, meaning the new, correct value.
condition is checked before each 3. Once the loop
iteration. condition is False
Syntax: while condition: (meaning the input is
statements. now valid), the
Termination: For a loop program can safely
to stop, something inside process the input.
the loop's body must C. Tracing Nested Loops and
eventually make the loop's Counting Iterations
condition False. If this A nested loop is simply a loop that
doesn't happen, you create is contained entirely inside another
an infinite loop. loop.
Sentinel-Controlled Execution Rule: The
Loop: This is a common inner loop completes all
pattern where a loop of its iterations for each
continues until the user single iteration of the
enters a special value, outer loop.
called a sentinel, to signal Counting Iterations: The
termination. total number of iterations
* The sentinel value must for the inner loop is
be distinctive and cannot calculated as:
be mistaken for regular Total Iterations =
input data. Iterations of Outer Loop
* Example: In a program x Iterations of Inner
calculating property taxes, Loop
the loop continues until the Dry-Run Example: If the
clerk enters a lot number outer loop runs 10 times
of 0, which is the chosen and the inner loop runs 5
sentinel. times, the innermost code
B. Input Validation Patterns block will execute times.
The principle of GIGO (garbage To predict output, you
in, garbage out) reminds us that must dry-run the inner
bad input leads to bad output. To loop completely before
prevent this, we use input moving to the next
validation loops. iteration of the outer loop.
Think of an analog clock:
Phoemela T. Dela CruzfinalsICT-104
Logprog reviewer –
[email protected] lecture
for every single hour the - To execute the
hour hand moves (outer function, you must call
loop), the minute hand it by simply writing its
completes 60 rotations name followed by
(inner loop). parentheses.
Loop Diagrams: Similar - The interpreter jumps
to flowcharts, these visual to the function,
aids help illustrate the flow executes the
of control, showing statements, and then
exactly where the code returns to the point
jumps back to repeat a where the function
process, which is was called. The main
invaluable for function typically
understanding loop logic. defines the overall
II. Functions logic by calling other
Functions are the building blocks for functions.
creating modular, reusable, and B. Local vs. Global Variables
manageable code, supporting a divide Understanding variable scope is
and conquer approach. crucial to prevent difficult-to-trace
A. Defining and Calling Functions bugs.
A function is a group of statements Local Variables: A
that performs a specific task, variable assigned a value
allowing for a divide and conquer inside a function is local to
approach to programming. that function.
Defining (The def - Its scope is limited to
Statement): the function in which
- You use the keyword it was created.
def followed by the - No statement outside
function name and the function can access
parentheses (). it.
- The first line is the Global Variables: A
function header and variable assigned a value
must end with a outside all functions is a
colon :. global variable.
- The indented - It can be accessed by
statements below the all functions in the
header form the block program.
(or body) of the - Using global: If a
function. function needs to
- def function_name(): change (assign a new
# Function Header value to) a global
# Statements in the variable, the variable
Block (indented) must be re-declared
print(“Hello inside the function
from a function!”) using the global
Calling a Function: keyword: global
variable_name.
Phoemela T. Dela CruzfinalsICT-104
Logprog reviewer –
[email protected] lecture
Best Practice: Avoid Value-Returning
using global variables as Functions: These
they make programs hard functions execute their
to debug, difficult to statements and then return
transfer, and create a value back to the
dependencies between statement that called it.
functions. Global - They are defined using
constants are the one the return expression
exception, provided they statement.
are created globally and - To use the result, you
not re-declared inside must capture the
functions. return value in a
C. Passing Arguments and Capturing variable: result =
Return Value value_returning_functi
Functions need to communicate data on().
with the rest of the program. - This is essential for the
Passing Arguments: An divide and conquer
argument is a piece of strategy, allowing one
data sent into a function function to perform a
when it is called. The smaller task and pass
function's header defines a its result to another
parameter variable to function for further
receive that data. processing.
- Positional D. The Math Module
Arguments: The most The math module is part of Python's
common method. standard library and contains useful
Arguments are functions for mathematical
matched to parameters calculations.
based on their position Familiarization: To use
(first argument to first any function or constant
parameter, second to from this module, you
second, etc.). must first write the
- Keyword Arguments: statement:
You can specify which import math
parameter an argument * This loads the module
is for using the format into memory.
parameter=value. The Usage (Dot Notation):
position of the You call the functions
argument then using the dot notation:
becomes irrelevant. module_name.function_na
- Pass by Value: In me().
Python, changes made Examples from Pointers:
to a parameter inside - math.sqrt(x):
the function do not Calculates the square
affect the original root of x.
argument's value in - math.floor(x): Rounds
the calling program. a number down to the
Phoemela T. Dela CruzfinalsICT-104
Logprog reviewer –
[email protected] lecture
nearest whole Methods Return New
number. Strings: String methods
- You can also access (e.g., upper(), replace())
constants like math.pi do not modify the original
for a highly accurate string; they always return a
value of π. new string object
III. Strings containing the result. You
Strings are immutable of characters, must capture this new
fundamental for text manipulation. string in a variable.
A. String Operations: Practice
Concatenation, Repetition,
Indexing, and Slicing.
You must actively practice these
core string operations:
Concatenation (+):
Combines two or more
strings.
Example: greeting =
“Hello” + “World”
Repetition (*): Repeats a
string a specified number
of times.
Example: line = “=” * 10
Indexing: Accesses a
single character by its
position (index starts at 0).
Negative indexes count
from the end ([-1] is the
last character).
Example: my_str[0]
Slicing: Extracts a
substring, or a slice, of the
original string.
Format: string[start :
end] (The character at end
is excluded.)
Example: my_str[1:4]
selects characters from
index 1 up to (but not
including) index 4. Slices
can also include a step
value.
B. String Immutability and Methods
Strings are Immutable:
Once created, a string
cannot be changed in
memory.
Phoemela T. Dela CruzfinalsICT-104
Logprog reviewer –
[email protected] lecture
C. Essential String Methods and Practice Programs
Method Description Practice Goal Application
upper()/lower() Returns a new string in all Normalize Input: Convert
caps/all lowercase. user input to a consistent
case for comparison.
strip() Returns a new string with Normalize Input: Clean
leading and trailing up user input before
whitespace removed. validation.
replace(old, new) Returns a copy of the Practice Programs:
string with all occurrences Sanitizing data.
of old replaced by new.
split(sep) Returns a list of substrings Practice Programs: Parse
delimited by a separator CSV-style text by splitting
sep. on the comma separator.
count(sub) Returns the number of Practice Programs: Count
times a substring sub vowels or specific character
appears. occurrences.