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

[CreativeProgramming]Lecture8_Study Tips for the Midterm Exam

The document provides an overview of Python programming concepts, focusing on conditional statements, functions, and iteration. It covers topics such as if-else statements, nested conditionals, and the use of loops, including while and for loops. Additionally, it includes exercises for practical application, such as assessing BMI and implementing a FizzBuzzWoof script.

Uploaded by

allrounderguno
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 views

[CreativeProgramming]Lecture8_Study Tips for the Midterm Exam

The document provides an overview of Python programming concepts, focusing on conditional statements, functions, and iteration. It covers topics such as if-else statements, nested conditionals, and the use of loops, including while and for loops. Additionally, it includes exercises for practical application, such as assessing BMI and implementing a FizzBuzzWoof script.

Uploaded by

allrounderguno
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/ 30

Creative Programming

Spring 2025
CUL1122 Lecture #08
Study Tips for the Midterm Exam
Week 2: Selection in Python

❖Python Conditional Statements


▪ If Statements
❖Python Conditionals II: Creating Complex Conditions
▪ Double Selection Conditionals: if-else
▪ Multiple Selection Conditionals: if-elif-else
▪ Nested Conditionals: if-if

3
Three Control Flows in a Computer Program

1. Sequencing 2. Selection 3. Iteration


In-order Execution Conditional Execution Repeated Execution

Code 1 Code
If expression If expression
is true Expression is false If expression
is true
Expression
Code 2
Code 1 Code 2

If expression is false
Code 3

4
Python Selection: if Statement

❖The code inside the ‘if’ block is executed based on the evaluation of a
given condition.
▪ If <expression> evaluates to True, then <statement(s)> is executed.
▪ If <expression> evaluates to False, then <statement(s)> is skipped and not
executed.

if <expression>:
expression False
<statement(s)>

True
statement(s)

5
Python Indentation

❖Indentation refers to the spaces at the beginning of each line of code.


❖While indentation in other programming languages may be for
readability only, in Python, it serves a functional purpose.
▪ Python uses indentation to indicate a code block.
▪ All statements within the same code block should have the same level of
indentation.
if num > 0 and num == 1:
print(‘Positive Number’) Python identifies a code block by its
print(‘Natural Number’) indentation.

The default indentation in Python is four spaces.


6
Double Selection Conditionals: if-else
❖This is about choosing between two options.
▪ If the condition is True, you execute Code Block 1; if it’s False, you go with Code
Block 2.
if Condition: False
Condition
Code Block 1
else: True
Code Block 2 Code Block 1 Code Block 2

❖Example:
▪ If the score is 70 or higher,
if score >= 70:
➢Code Block 1: ‘Pass!’ print(‘Pass!’)
▪ Otherwise, else:
print(‘Fail!’)
➢Code Block 2: ‘Fail!’
7
Multiple Selection Conditionals: if-elif-else

❖This is choosing from three or more options.


▪ Conditions are checked one by one, executing the first block that is True.
▪ If all conditions are False and there’s an else statement, that block will be run.
if Condition 1: False if score >= 90:
Cond 1
Code Block 1 print(‘Grade is A.’)
True False
Cond 2 elif score >= 80:
elif Condition 2:
Code Block 1
True False print(‘Grade is B.’)
Code Block 2 Cond 3
Code Block 2 elif score >= 70:
elif Condition 3: True
print(‘Grade is C.’)
Code Block 3 Code Block 3
else:
else: Code Block 4
print(‘Grade is D or F.’)
Code Block 4
8
Nested if Statement

❖A nested if statement includes one or more conditional statements


within a conditional statement.
▪ The code block is executed only if all N conditions are met.
❖Example: Print ‘Smart City’ only if both ‘Seoul’ and ‘Seongdong’ are
True.
if Condition 1: if city == ‘Seoul’:
if Condition 2: if district == ‘Seongdong’:
… print (city + ‘ ’ + district + ‘ is a smart city!’)
if Condition N: else:
Code Block print (city + ‘, my soul!’)

9
Week 3: Selection in Python (cont.)

❖Exercise: Assessing Body Mass Index (BMI)

10
Exercise 4: Assessing Body Mass Index (BMI)

❖Create a script to assess body condition based on BMI values.


▪ Calculate BMI by dividing weight by height squared.
▪ Then, evaluate it according to the criteria below:

Regarding the solution for Exercise 4, please refer to Lab4_Solution.py on the LMS.

11
Week 4: Functions in Python

❖Functions
▪ Importance of Functions
▪ Defining a Python Function
▪ Scope of Variables

12
Basic Idea of Functions

❖A function is a code block to perform specific tasks within a program.


▪ It is similar to a machine that receives input data, processes it, and produces a
result.
▪ For example, when you put laundry and detergent into a washing machine, you
receive clean laundry after it runs.
▪ Similarly, when 1) input data is provided to a function
and a task is requested, 2) the function performs
calculations and 3) returns the result.
2 0 10
x x x
x2 x2 x2

4 0 100 13
Importance of Functions

❖1) Modularization: Allows for devising solutions at a higher level


without worrying about the underlying details.
▪ Would anyone want to think about calculating square roots within the complex
computation below?
r = (sqrt(250+110*sqrt(5))/20)*E

❖2) Reusability: Enables problem-solving without the need to write new


code each time, allowing for the reuse of existing functions.
❖3) Development Efficiency: Makes programs more concise and easier to
understand, facilitating error detection and modification.

14
Defining a Python Function

❖The function declaration consists of the function name on the first line,
followed by the function body.

def name(parameters): # Function name is the identifier used to call the function
# Parameters are a list of inputs passed to the function
code # Function body must be indented
code Function # Function body is executed each time the function is called
… Body
return value # ‘return’ ends the function call and sends result back to the caller
# You can omit the ‘return’ if you want to return nothing

: Indentation

15
Scope of Variables: Types
❖1) Local Variables
▪ Valid only within the function.
▪ Created upon function call and disappear when the function ends.
❖2) Global Variables
▪ Valid throughout the script (or program).
▪ Created at the start of the program and cease to exist when the program ends.
❖Example:
▪ Global Variable: A person known throughout the country, such as Elon Musk.
▪ A person who is well-known in a specific local area, such as Mayor Oh Se-hoon.
➢He is famous in Korea but may not be recognized outside of the country.

16
Scope of Variables: Accessing Global Variables

❖Global variables can be accessed and modified within functions by


using the global keyword.

17
Weeks 6-7: Iteration in Python

• Python Loops
• Syntax for Using the while Loop
❖range() and for Loop
▪ Syntax of the range() Function
▪ Steps to Use range() Function
▪ range() Examples
▪ for Loop with range() Function
❖for loop vs. while loop
❖Exercise 6: FizzBuzzWoof Implementation
18
The while Loop in Python

❖A while loop begins with ‘while,’ includes a condition, and ends with a
colon.
❖During each iteration:
▪ 1) The loop condition is checked.
▪ 2) If the condition is True, the code block inside the loop is executed.
▪ 3) Otherwise, the script leaves the The while Loop False
loop and proceeds to the next line while Condition: 1) Cond
of code. Code Block True
2) Code Block

3) …
19
Terminating the Loop Immediately

❖The Python break statement immediately terminates a loop entirely.


❖In the example below, you can exit the loop when i becomes 1,000.
i=0
Iteration
while True: # This loop runs infinitely True
Always True
print(i)
print i
i=i+1 # Increment i by 1
if i == 1000: # Exit the loop when i reaches 1,000 i=i+1
break # Terminate the loop
False
i == 1000
True
break
20
Syntax of the range() Function

❖The built-in function range() generates a sequence of numbers within a


specified range.
❖The syntax for the range() function is as follows:
range(start, stop[, step])

▪ This function requires a stop value, while the start and step values are optional.
❖Parameters
Name Description Default Value
start Specifying the initial value of the sequence. 0
stop Denoting the end value of the sequence (exclusive). N/A
step Defining the increment between consecutive numbers in the sequence. 1
21
range() Function Method #1: range(stop)

❖The most basic way to use the range() function is by specifying only the
end value, denoted as range(stop).
❖When using this form, the range() function automatically starts from 0,
increments by 1, and ends at stop - 1.
❖For example, to print the first 6 numbers starting from 0, you would use
the following code:
range(6)
for i in range(6): 0 0 1 2 3 4 5 6
print(i) sequence
start stop
▪ In this case, the default values are start = 0 and step = 1.

22
range() Function Method #2: range(start, stop)

❖You can also use the range() function by specifying both the start and
stop values, denoted as range(start, stop).
▪ This method is useful when you want the sequence to start from a value other
than 0.
❖When you provide two arguments to range(), it produces integers
starting from the start value up to, but not including, the stop value.
❖For example, to print numbers from 10 to 15, you would use the
following code:
range(10, 16)
for i in range(10, 16): 10 10 11 12 13 14 15 16
print(i) sequence
start stop
23
range() Function Method #3: range(start, stop, step)

❖You can use the range() function with start, stop, and step parameters
to specify increments.
❖When all three arguments are provided, the function creates a
sequence starting from the start value, incrementing by the step value,
and stopping before reaching the stop value.
❖For example, to print multiples of 5 from 10 to 35, you can use the
following code with a step value of 5:
range(10, 40, 5)
for i in range(10, 40, 5): 10 10 15 20 25 30 35 40
print(i) sequence
start stop

24
Syntax for a for Loop

❖In Python, a for loop executes a block of code or statements repeatedly


for a fixed number of times.
❖A for loop typically follows this structure:
for item in iterable:
code block # Code block to be executed for each item in the iterable
# You can access the current item using the variable ‘item’

❖Here’s a breakdown of the components:


Name Description
for This keyword signals the start of the loop.
item This is a variable that represents the current item in the iteration. You can
choose any valid variable name here.
25
Syntax for a for Loop

❖Here’s a breakdown of the components:


Name Description
in This keyword is used to specify the iterable object over which the loop will
iterate.
iterable This is the collection of items that the loop will iterate over. It can be a list,
tuple, dictionary, string, or any other iterable object in Python.
: The colon denotes the end of the loop header and the start of the indented
code block.
Code This block of code executes for each item in the iterable, indicated by
block consistent indentation. You can access the current item using the loop
variable (e.g., item) and perform operations accordingly.

26
for Loop vs. while Loop

❖In programming, there are two types of iteration: definite and indefinite.
❖Definite iteration involves specifying the number of times a designated
block of code will be executed when the loop starts.
❖Using a for loop for a specific number of iterations:
attempts = 0
for i in range(5): # Allow five attempts
password = input(‘Enter your password: ‘)
if password == ‘password123’:
print(‘Access granted!’)
break
else:
print(‘Incorrect password. Try again!’)
attempts = attempts + 1
27
for Loop vs. while Loop

❖On the other hand, indefinite iteration doesn’t specify the number of
loop executions in advance.
❖Instead, the designated block is executed repeatedly as long as a
condition is met.
❖The while loop is primarily used for indefinite iteration.
print(‘Using a while loop to allow for unlimited attempts:’)
while True: # Allow infinite attempts
password = input(‘Enter your password: ‘)
if password == ‘password123’:
print(‘Access granted!’)
break
28
Exercise 6: FizzBuzzWoof Implementation

❖Create a FizzBuzzWoof script that iterates over integers from 1 to 110


and follows these rules:
▪ Print “Fizz”, “Buzz”, or “Woof” for numbers divisible by 3, 5, or 7, respectively.
▪ If a number is divisible by more than one of these, combine the corresponding
words (e.g., 15 → “FizzBuzz”, 21 → “FizzWoof”, 35 → “BuzzWoof”, 105 →
“FizzBuzzWoof”).
▪ If none of the conditions apply, print the number itself.
… 9 10 11 12 13 14 15 16 …
Fizz Buzz 11 Fizz 13 Woof FizzBuzz 16
Regarding the solution for Exercise 6, please refer to Lab6_FizzBuzzWoof.py on the LMS.

29
수고하셨습니다!

30

You might also like