0% found this document useful (0 votes)
20 views25 pages

Week3 Python Notes

The document provides an overview of Python's conditional statements, loops, list comprehensions, and functions. It explains the syntax and usage of if, if...else, and if...elif...else statements, as well as for and while loops, including their control statements like break and continue. Additionally, it covers the definition and benefits of functions, including built-in and user-defined functions, and introduces concepts like lambda functions and recursion.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views25 pages

Week3 Python Notes

The document provides an overview of Python's conditional statements, loops, list comprehensions, and functions. It explains the syntax and usage of if, if...else, and if...elif...else statements, as well as for and while loops, including their control statements like break and continue. Additionally, it covers the definition and benefits of functions, including built-in and user-defined functions, and introduces concepts like lambda functions and recursion.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

WEEK3 PYTHON NOTES

Conditional statements.

As you start this lesson, make sure you have a good understanding of boolean variables and
expressions since they are building blocks of conditional statements.

Conditional statements help in the decision-making process, for example,

 “Are you hungry? If so, then eat” is a conditional statement

Phrased as: - If you’re hungry, then eat

Let's break this down to pick a boolean expression in our conditional statement.

 “Are you hungry” is the boolean expression here, so the conditional statement is checking
if it’s True.
 If “are you hungry” == True, the conditional statement will be executed and you will eat.
 If [you are hungry], then [eat food]

In computer programming, we use the if statement to run a block code only when a certain
condition is met.

In Python, there are three forms of the if...else statement.


1. if statement
2. if...else statement
3. if...elif...else statement

1. Python if Statement

The basic syntax for the if statement:

# Example of a basic if statement


temperature = 30

if temperature > 25:


print("It's a hot day!")

The if statement evaluates the condition.

1. If condition is evaluated to True, the code inside the body of if is executed.


2. If condition is evaluated to False, the code inside the body of if is skipped.

https://youtu.be/5DfYajSQOFY

Practice more on using if conditional statements with:

- Relational operators: (>, >=, <, <=)

- Boolean operators: (and, or, not)

2. Python if...else Statement

Syntax

# Example of an if-else statement


temperature = 20

if temperature > 25:


print("It's a hot day!")
else:
print("It's a cool day!")
If the condition evaluates to True,

 the code inside if is executed


 the code inside else is skipped

If the condition evaluates to False,

 the code inside else is executed


 the code inside if is skipped

https://youtu.be/5DBbf65_nck

3. Python if...elif...else 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.

The syntax of the if...elif...else statement is:

# Example of an if...elif...else statement


temperature = 15

if temperature > 25:


print("It's a hot day!")
elif temperature > 15:
print("It's a warm day!")
else:
print("It's a cold day!")

Here,

1. If the condition evaluates to true, code block 1 is executed.


2. If condition1 evaluates to false, then condition2 is evaluated.
3. If condition 2 is true, code block 2 is executed.
4. If condition 2 is false, code block 3 is executed.

Test YourSelf with the Question Below :

Write an if/elif/else statement for a college with a grading system as shown below:

 If grade is 90 or higher, print "A"


 Else if grade is 80 or higher, print "B"
 Else if grade is 70 or higher, print "C"
 Else if grade is 60 or higher, print "D"
 Else, print "F"

More Resources for if statements

https://www.programiz.com/python-programming/if-elif-else

https://www.codecademy.com/resources/docs/python/conditionals

Python Loops

In computer programming, loops are used to repeat a block of code. We perform a process of
iteration (repeating tasks).

There are 2 types of loops in Python:

 for loop
 while loop

Programming languages like Python implement two types of iteration:

1. Indefinite iteration, where the number of times the loop is executed depends on how
many times a condition is met.
2. Definite iteration, where the number of times the loop will be executed is defined in
advance (usually based on the collection size).

In a for loop, we will know in advance how many times the loop will need to iterate because we
will be working on a collection with a predefined length.

With for loops, on each iteration, we will be able to perform an action on each element of the
collection.

For loop syntax:

# Example of a for loop


fruits = ["apple", "banana", "cherry"]

for fruit in fruits:


print(f"I love {fruit}!")

Example Explanation:

1. List: fruits is a list containing "apple", "banana", and "cherry".


2. Loop: The for loop iterates through each item in the list.
3. Action: During each iteration, fruit represents the current item, and print outputs a
message for each fruit.

Let’s break down each of these components:

1. A for keyword indicates the start of a for loop.


2. A <temporary variable> is used to represent the value of the element in the collection the
loop is currently on.
3. An in keyword separates the temporary variable from the collection used for iteration.
4. A <collection> to loop over. In our examples, we will be using a list.
5. An <action> to do anything on each iteration of the loop.

https://youtu.be/Dxn8HSm7EtI

For Loops: Using Range

A range is a series of values between two numeric intervals.

We use Python's built-in function range() to define a range of values.

For example,

five_steps = range(5)

# five_steps is now a collection with 5 elements:

# 0, 1, 2, 3, 4

# Example of a for loop with range


for number in range(1, 6): # Loops from 1 to 5
print(f"Number: {number}")

Example Explanation:

1. range(1, 6): Generates numbers starting from 1 up to (but not including) 6.


2. Loop: The for loop iterates over each number in this range.
3. Action: During each iteration, number represent the current value, and print outputs it.

While Loops

A while loop performs a set of instructions as long as a given condition is true.

https://youtu.be/Dxn8HSm7EtI

While loop structure


# Example of a while loop
count = 1

while count <= 5:


print(f"Count: {count}")
count += 1 # Increment the counter

Explanation:

1. Initialization: count = 1 sets the starting value.


2. Condition: while count <= 5 keeps the loop running as long as count is less than or equal
to 5.
3. Action: Inside the loop:
o It prints the current value of count.
o The count the variable is incremented by 1 (count += 1) to eventually meet the
exit condition.

Loop controls: Break and continue

The break statement is used to terminate the loop immediately when it is encountered.

# Example of loop controls: break and continue


for number in range(1, 10): # Loop through numbers 1 to 9
if number == 5:
print("Breaking the loop at 5")
break # Exit the loop when number is 5
elif number % 2 == 0:
print(f"Skipping {number} because it's even")
continue # Skip the rest of the loop body for even numbers
print(f"Processing number: {number}")

Explanation:

1. break: Stops the loop entirely when number == 5.


2. continue: Skips the current iteration when number is even and moves to the next loop
iteration.

Python continue Statement

The continue statement is used to skip the current iteration of the loop and the control flow of the
program goes to the next iteration.

While the break control statement will come in handy, there are other situations where we don’t
want to end the loop entirely. What if we only want to skip the current iteration of the loop?
Nested Loops

In Python, loops can be nested inside other loops. Nested loops can be used to access items of
lists which are inside other lists. The item selected from the outer loop can be used as the list for
the inner loop to iterate over.

Example code

# Example of a nested loop


for i in range(1, 4): # Outer loop
for j in range(1, 4): # Inner loop
print(f"Outer loop: {i}, Inner loop: {j}")

More Resources for loops

https://www.codecademy.com/resources/docs/python/loops

https://www.programiz.com/python-programming/if-elif-else

https://www.programiz.com/python-programming/for-loop

https://www.programiz.com/python-programming/while-loop

https://www.programiz.com/python-programming/break-continue

List comprehensions in Python provide a concise and elegant way to create and manipulate lists.
They offer a more readable and expressive alternative to traditional loops for generating lists.

What is a List Comprehension?

A list comprehension is a compact syntax for creating a list by evaluating an expression for each
element in an iterable (like a list or range), optionally filtering elements based on a condition.

Syntax:

[expression for item in iterable if condition]

 expression: The value or transformation applied to each element.


 item: A variable that represents each element in the iterable.
 iterable: A sequence (like a list, tuple, or range) to iterate over.
 condition: (Optional) A filter that determines whether to include the element.

Basic Example

# Traditional loop
squares = []
for x in range(5):
squares.append(x**2)

# List comprehension
squares = [x**2 for x in range(5)]
print(squares) # Output: [0, 1, 4, 9, 16]

Here, is the list of comprehension [x**2 for x in range(5)] creates a list of squares of numbers
from 0 to 4.

Using Conditions in List Comprehensions

You can include a condition to filter items.

# List comprehension with a condition


even_numbers = [x for x in range(10) if x % 2 == 0]
print(even_numbers) # Output: [0, 2, 4, 6, 8]

Nested List Comprehensions

List comprehensions can be nested to handle complex operations, such as creating a matrix.

# Create a 3x3 matrix using nested list comprehensions


matrix = [[i * j for j in range(1, 4)] for i in range(1, 4)]
print(matrix) # Output: [[1, 2, 3], [2, 4, 6], [3, 6, 9]]

Examples of List Comprehensions

1. Transforming Data:
names = ["Alice", "Bob", "Charlie"]
uppercased_names = [name.upper() for name in names]
print(uppercased_names) # Output: ['ALICE', 'BOB', 'CHARLIE']

2. Filtering Data:

numbers = [10, 15, 20, 25, 30]


divisible_by_5 = [num for num in numbers if num % 5 == 0]
print(divisible_by_5) # Output: [10, 15, 20, 25, 30]

3. Flattening a List:

nested_list = [[1, 2], [3, 4], [5, 6]]


flat_list = [item for sublist in nested_list for item in sublist]
print(flat_list) # Output: [1, 2, 3, 4, 5, 6]

Advantages of List Comprehensions

1. Conciseness: More compact than traditional loops.


2. Readability: Easier to understand when used appropriately.
3. Performance: Faster than loops in many cases due to optimization.

When Not to Use List Comprehensions

While list comprehensions are powerful, they can become hard to read if they are too complex.
In such cases, traditional loops or generator functions may be more appropriate.

# Complex list comprehension (less readable)


result = [x * y for x in range(10) for y in range(5) if x + y > 5]

# Better as a loop (more readable)


result = []
for x in range(10):
for y in range(5):
if x + y > 5:
result.append(x * y)

Conclusion
List comprehensions are a versatile and efficient tool in Python, enabling you to write cleaner
and faster code. They are ideal for transforming, filtering, or generating lists in a Pythonic way.
Start practicing them to enhance your coding skills!

Functions are a fundamental part of Python programming. They allow you to encapsulate
reusable blocks of code to make programs modular, easier to understand, and maintain.

What is a Function?

A function is a block of code designed to perform a specific task. You define a function once and
can use it multiple times throughout your code.

Syntax:

def function_name(parameters):
"""Optional docstring explaining the function."""
# Code block
return value # Optional return statement

Types of Functions

1. Built-in Functions: Predefined functions in Python (e.g., print(), len(), type()).


2. User-defined Functions: Functions created by the user.

Defining and Calling a Function

Here’s how you define and call a function in Python:

# Function definition
def greet(name):
"""Greet a person by their name."""
return f"Hello, {name}!"

# Function call
print(greet("Alice")) # Output: Hello, Alice!

Key Components of a Function


1. Function Name: Should be descriptive and follow naming conventions.
2. Parameters: Variables passed into the function.
3. Docstring: An optional description of what the function does.
4. Return Statement: Outputs a value from the function (optional).

Parameters and Arguments

Functions can accept zero or more arguments.

1. Positional Arguments:

def add(a, b):


return a + b

print(add(3, 5)) # Output: 8

2. Default Arguments:

def greet(name="Guest"):
return f"Hello, {name}!"

print(greet()) # Output: Hello, Guest!


print(greet("Alice")) # Output: Hello, Alice!

3. Keyword Arguments:

def introduce(name, age):


return f"My name is {name}, and I'm {age} years old."

print(introduce(age=25, name="Bob")) # Output: My name is Bob, and I'm 25 years old.

Returning Values

A function can return values using the return statement.

def square(number):
return number ** 2

result = square(4)
print(result) # Output: 16
Anonymous Functions: Lambda

Python supports anonymous functions using the lambda keyword. They are useful for short,
simple functions.

# Lambda function for adding two numbers


add = lambda x, y: x + y
print(add(3, 5)) # Output: 8

# Using lambda with map()


numbers = [1, 2, 3, 4]
squares = list(map(lambda x: x**2, numbers))
print(squares) # Output: [1, 4, 9, 16]

Recursive Functions

A function can call itself, enabling recursive problem-solving.

def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)

print(factorial(5)) # Output: 120

Benefits of Functions

1. Reusability: Write once, and use multiple times.


2. Modularity: Break programs into smaller, manageable parts.
3. Improved Readability: Descriptive names make code easier to understand.

Conclusion

Functions are a powerful tool that makes your code cleaner, more efficient, and easier to
maintain. Mastering their use is essential for any Python developer. Start experimenting with
different types of functions to understand their versatility!

PYTHON WEEK3 CODING CHALLENGE

Coding Challenges for basic control flows and functions


1. Large Power

Create a method that tests whether the result of taking the power of one number to another
number provides an answer which is greater than 5000. We will use a conditional statement to
return True if the result is greater than 5000 or return False if it is not. In order to accomplish
this, we will need the following steps:

1. Define the function to accept two input parameters called base and exponent
2. Calculate the result of base to the power of exponent
3. Use an if statement to test if the result is greater than 5000. If it is then return True.
Otherwise, return False

Coding Question

Create a function named large_power() that takes two parameters named base and exponent.

If base raised to the exponent is greater than 5000, return True, otherwise return False

2.Divisible By Ten

Create a function that determines whether or not a number is divisible by ten. A number is
divisible by ten if the remainder of the number divided by 10 is 0. Using this, we can complete
this function in a few steps:

1. Define the function header to accept one input num


2. Calculate the remainder of the input divided by 10 (use modulus)
3. Use an if statement to check if the remainder was 0. If the remainder was 0, return True,
otherwise, return False

Coding question

Create a function called divisible_by_ten() that has one parameter named num.

The function should return True if num is divisible by 10, and False otherwise. Consider using
modulo operator % to check for divisibility.

SOLUTION

You said:

Coding Challenges for basic control flows and functions 1. Large Power Create a method that
tests whether the result of taking the power of one number to another number provides an answer
which is greater than 5000. We will use a conditional statement to return True if the result is
greater than 5000 or return False if it is not. In order to accomplish this, we will need the
following steps: 1. Define the function to accept two input parameters called base and exponent
2. Calculate the result of base to the power of exponent 3. Use an if statement to test if the result
is greater than 5000. If it is then return True. Otherwise, return False Coding Question Create a
function named large_power() that takes two parameters named base and exponent. If base raised
to the exponent is greater than 5000, return True, otherwise return False 2.Divisible By Ten
Create a function that determines whether or not a number is divisible by ten. A number is
divisible by ten if the remainder of the number divided by 10 is 0. Using this, we can complete
this function in a few steps: 1. Define the function header to accept one input num 2. Calculate
the remainder of the input divided by 10 (use modulus) 3. Use an if statement to check if the
remainder was 0. If the remainder was 0, return True, otherwise, return False Coding question
Create a function called divisible_by_ten() that has one parameter named num. The function
should return True if num is divisible by 10, and False otherwise. Consider using modulo
operator % to check for divisibility.

ChatGPT said:

Got it 👍 Let’s solve both coding challenges step by step with clear and professional Python
solutions.

1. Large Power

We need a function large_power(base, exponent) that checks whether base ** exponent is greater
than 5000.

def large_power(base, exponent):


"""
Returns True if base raised to the power of exponent is greater than 5000,
otherwise returns False.
"""
result = base ** exponent # Step 2: Calculate power

if result > 5000: # Step 3: Check condition


return True
else:
return False

# --- Example Tests ---


print(large_power(10, 3)) # 1000 → False
print(large_power(20, 3)) # 8000 → True

2. Divisible by Ten

We need a function divisible_by_ten(num) that checks if a number is divisible by 10.


def divisible_by_ten(num):
"""
Returns True if num is divisible by 10,
otherwise returns False.
"""
if num % 10 == 0: # Step 2 & 3: Check remainder
return True
else:
return False

# --- Example Tests ---


print(divisible_by_ten(50)) # True
print(divisible_by_ten(37)) # False

✅ Both functions are written clearly, follow the control flow logic, and include example test
cases so you can see how they work.

Would you like me to also combine both into a single file with multiple test cases (like a small
coding challenge script), so you can run them together?

You said:

Coding Challenges for basic control flows and functions 1. Large Power Create a method that
tests whether the result of taking the power of one number to another number provides an answer
which is greater than 5000. We will use a conditional statement to return True if the result is
greater than 5000 or return False if it is not. In order to accomplish this, we will need the
following steps: 1. Define the function to accept two input parameters called base and exponent
2. Calculate the result of base to the power of exponent 3. Use an if statement to test if the result
is greater than 5000. If it is then return True. Otherwise, return False Coding Question Create a
function named large_power() that takes two parameters named base and exponent. If base raised
to the exponent is greater than 5000, return True, otherwise return False 2.Divisible By Ten
Create a function that determines whether or not a number is divisible by ten. A number is
divisible by ten if the remainder of the number divided by 10 is 0. Using this, we can complete
this function in a few steps: 1. Define the function header to accept one input num 2. Calculate
the remainder of the input divided by 10 (use modulus) 3. Use an if statement to check if the
remainder was 0. If the remainder was 0, return True, otherwise, return False Coding question
Create a function called divisible_by_ten() that has one parameter named num. The function
should return True if num is divisible by 10, and False otherwise. Consider using modulo
operator % to check for divisibility.

ChatGPT said:

Perfect 👍 Let’s write the solutions for both coding challenges step by step, exactly as the
instructions describe.
1. Large Power

We need a function large_power(base, exponent) that checks if base ** exponent is greater than
5000.

def large_power(base, exponent):


"""
Returns True if base raised to the power of exponent is greater than 5000,
otherwise returns False.
"""
# Step 2: Calculate base to the power of exponent
result = base ** exponent

# Step 3: Conditional check


if result > 5000:
return True
else:
return False

# --- Example Tests ---


print(large_power(10, 3)) # 1000 -> False
print(large_power(20, 3)) # 8000 -> True
print(large_power(5, 5)) # 3125 -> False
print(large_power(8, 5)) # 32768 -> True

2. Divisible by Ten

We need a function divisible_by_ten(num) that checks if num % 10 == 0.

def divisible_by_ten(num):
"""
Returns True if num is divisible by 10,
otherwise returns False.
"""
# Step 2: Calculate remainder
remainder = num % 10

# Step 3: Conditional check


if remainder == 0:
return True
else:
return False
# --- Example Tests ---
print(divisible_by_ten(50)) # True
print(divisible_by_ten(37)) # False
print(divisible_by_ten(100)) # True
print(divisible_by_ten(123)) # False

✅ Both functions follow basic control flow with if statements, and I’ve added test cases to show
how they work.

Do you want me to also combine both functions into one Python file with a menu-driven
program (so you can test them interactively), or just keep them as separate standalone functions?

You said:

YES PLEASE

ChatGPT said:

Great! 🚀 Let’s put both challenges together into one Python file.
I’ll also add a menu-driven program so you can test either function interactively.

✅ Complete Python Script

def large_power(base, exponent):


"""
Returns True if base raised to the power of exponent is greater than 5000,
otherwise returns False.
"""
result = base ** exponent
if result > 5000:
return True
else:
return False

def divisible_by_ten(num):
"""
Returns True if num is divisible by 10,
otherwise returns False.
"""
remainder = num % 10
if remainder == 0:
return True
else:
return False

# ---------------- MAIN PROGRAM ----------------


def main():
while True:
print("\n=== Coding Challenges Menu ===")
print("1. Check Large Power (>5000)")
print("2. Check Divisible by Ten")
print("3. Exit")

choice = input("Enter your choice (1/2/3): ")

if choice == "1":
base = int(input("Enter the base number: "))
exponent = int(input("Enter the exponent: "))
result = large_power(base, exponent)
print(f"Result: {result}")

elif choice == "2":


num = int(input("Enter a number: "))
result = divisible_by_ten(num)
print(f"Result: {result}")

elif choice == "3":


print("Exiting program. Goodbye!")
break
else:
print("Invalid choice. Please select 1, 2, or 3.")

# Run the program


if __name__ == "__main__":
main()

🔹 How It Works

1. Program starts and shows a menu:


o Option 1 → Test large_power(base, exponent)
o Option 2 → Test divisible_by_ten(num)
o Option 3 → Exit
2. Takes user input and prints whether the condition is True or False.
3. Loops until you choose Exit.

👉 Do you want me to also make this program print the actual calculated result (e.g., show
base ** exponent value when checking large power), or just keep it returning True/False?

You said:

YES PLEASE

ChatGPT said:

Perfect 🙌 I'll update the program so that when you test Large Power, it will show the actual
calculated result along with whether it’s greater than 5000 or not.

Here’s the improved version:

✅ Complete Python Script (Enhanced with Results)

def large_power(base, exponent):


"""
Returns True if base raised to the power of exponent is greater than 5000,
otherwise returns False.
"""
result = base ** exponent
if result > 5000:
return True
else:
return False

def divisible_by_ten(num):
"""
Returns True if num is divisible by 10,
otherwise returns False.
"""
remainder = num % 10
if remainder == 0:
return True
else:
return False
# ---------------- MAIN PROGRAM ----------------
def main():
while True:
print("\n=== Coding Challenges Menu ===")
print("1. Check Large Power (>5000)")
print("2. Check Divisible by Ten")
print("3. Exit")

choice = input("Enter your choice (1/2/3): ")

if choice == "1":
base = int(input("Enter the base number: "))
exponent = int(input("Enter the exponent: "))
power_result = base ** exponent
check = large_power(base, exponent)
print(f"{base} ^ {exponent} = {power_result}")
print(f"Is {power_result} > 5000? {check}")

elif choice == "2":


num = int(input("Enter a number: "))
check = divisible_by_ten(num)
print(f"{num} % 10 = {num % 10}")
print(f"Is {num} divisible by 10? {check}")

elif choice == "3":


print("Exiting program. Goodbye!")
break
else:
print("Invalid choice. Please select 1, 2, or 3.")

# Run the program


if __name__ == "__main__":
main()

🔹 Sample Run

=== Coding Challenges Menu ===


1. Check Large Power (>5000)
2. Check Divisible by Ten
3. Exit
Enter your choice (1/2/3): 1
Enter the base number: 8
Enter the exponent: 5
8 ^ 5 = 32768
Is 32768 > 5000? True
=== Coding Challenges Menu ===
1. Check Large Power (>5000)
2. Check Divisible by Ten
3. Exit
Enter your choice (1/2/3): 2
Enter a number: 45
45 % 10 = 5
Is 45 divisible by 10? False

👉 Do you also want me to add multiple test cases automatically (so it runs a batch of examples
without user input), or should we keep it interactive only

WEEK3 QUIZ

Skip to content

Chat history
You said:
1. Which keyword is used to define a function in Python? create 🎨 function 🔧 def 🛠
make ⚒

The correct keyword is:

def 🛠 ✅
In Python, functions are defined using the def keyword.
2. How do you call a function named greet() in Python? call greet() 📞 greet() 🎉 run
greet start greet()

The correct way is:

greet() 🎉 ✅

In Python, you call (execute) a function by writing its name followed by parentheses.

3. What will happen if the condition in an if statement is False? The code inside the
if block will still run 🚀 The code will break ❌ The code inside the if block will be
skipped 🚪 The program will crash 💥

The correct answer is:


The code inside the if block will be skipped 🚪 ✅
If the condition is False, Python simply skips the if block and continues executing the rest of the
program.
4. What does the return keyword do inside a function? Prints the function’s name
Ends the program Restarts the function 🌀 Stops the function and sends back a
value 🚚

The correct answer is:

Stops the function and sends back a value 🚚 ✅


In Python, the return keyword ends a function’s execution and optionally provides a value back
to the caller.
5. What does an elif statement do? It checks another condition if the first if is
False 🔍 It breaks the loop It repeats the loop It stops the program immediately 💥

The correct answer is:

It checks another condition if the first if is False 🔍 ✅


In Python, elif (short for else if) lets you test another condition when the initial if condition
is False.
Week 3 Assignment Question

1. Create a function named calculate_discount(price, discount_percent) that calculates the final


price after applying a discount. The function should take the original price (price) and the
discount percentage (discount_percent) as parameters. If the discount is 20% or higher, apply the
discount; otherwise, return the original price.

2. Using the calculate_discount function, prompt the user to enter the original price of an item
and the discount percentage. Print the final price after applying the discount, or if no discount
was applied, print the original price.

Answers

# Week 3 Assignment
# Question 1 & 2

# Function to calculate final price after discount


def calculate_discount(price, discount_percent):
"""
Calculates the final price after applying a discount.

Parameters:
price (float): Original price of the item.
discount_percent (float): Discount percentage to apply.

Returns:
float: Final price after discount if discount is >= 20%,
otherwise returns the original price.
"""
if discount_percent >= 20:
discount_amount = (discount_percent / 100) * price
final_price = price - discount_amount
return final_price
else:
# No discount applied if discount < 20%
return price

# Main program to get user input


try:
# Prompt user for inputs
original_price = float(input("Enter the original price of the item:
"))
discount = float(input("Enter the discount percentage: "))

# Call the function


final_price = calculate_discount(original_price, discount)

# Print results
if discount >= 20:
print(f"Discount applied! The final price is: {final_price:.2f}")
else:
print(f"No discount applied. The price remains:
{final_price:.2f}")

except ValueError:
print("Invalid input. Please enter numeric values for price and
discount.")
# End of the code snippet
# End of calculate_discount.py

Perfect! Here's an enhanced version that also shows the discount amount when applied:

# Function to calculate final price after discount


def calculate_discount(price, discount_percent):
"""
Returns a tuple: (final_price, discount_amount)
If discount < 20%, discount_amount will be 0
"""
if discount_percent >= 20:
discount_amount = price * (discount_percent / 100)
final_price = price - discount_amount
return final_price, discount_amount
else:
return price, 0

# Main program
try:
price = float(input("Enter the original price: "))
discount = float(input("Enter the discount percentage: "))

final_price, discount_amount = calculate_discount(price, discount)

if discount_amount > 0:
print(f"Discount applied! You saved: {discount_amount:.2f}")
print(f"Final price: {final_price:.2f}")
else:
print(f"No discount applied. Price remains: {final_price:.2f}")

except ValueError:
print("Please enter valid numeric values for price and discount.")
# calculate_discounts.py
# This script calculates the final price after applying a discount

Sample Run:

Enter the original price: 200


Enter the discount percentage: 25
Discount applied! You saved: 50.00
Final price: 150.00
Enter the original price: 150
Enter the discount percentage: 10
No discount applied. Price remains: 150.00

This version is interactive and professional, clearly showing:

 The discount applied


 The amount saved
 The final price

WEEK3 ASSIGNMENT BEST ANSWER

# calculate_discount.py
def calculate_discount(price, discount_percent):
"""
Calculates the final price after applying a discount if the discount
is 20% or higher.

Parameters:
price (float): Original price of the item
discount_percent (float): Discount percentage to apply (0-100)

Returns:
float: Final price after discount (or original price if discount <
20%)
"""
if discount_percent >= 20:
discount_amount = price * (discount_percent / 100)
final_price = price - discount_amount
return final_price
else:
return price

# Get user input


original_price = float(input("Enter the original price of the item: "))
discount_percentage = float(input("Enter the discount percentage: "))

# Calculate final price


final_price = calculate_discount(original_price, discount_percentage)

# Display the result


if discount_percentage >= 20:
print(f"After applying a {discount_percentage}% discount, the final
price is: ${final_price:.2f}")
else:
print(f"No discount applied (needs to be 20% or higher). The price
remains: ${original_price:.2f}")
# This script calculates the final price after applying a discount
# based on the given conditions.

You might also like