Python Coding Day 5 | Floor division, Modulo, and F-strings

Floor division, Modulo, and F-strings

Watch the lesson tutorial  🔻


1. Floor Division (//) 🏠

Floor division, denoted by the // operator, performs division and then rounds the result down to the nearest whole number (integer).

This is different from regular division (/), which always returns a floating-point number (decimal). Floor division ensures the result is an integer, representing the maximum number of whole times the divisor fits into the dividend.

Practical Example Code

Floor division is useful when you need to distribute items evenly or determine how many full groups can be formed.

Python
## Example 1: Calculating full teams

total_students = 17
team_size = 5

# Use floor division to find the maximum number of full teams
number_of_full_teams = total_students // team_size

print(f"Total students: {total_students}")
print(f"Team size: {team_size}")
print(f"Number of FULL teams that can be formed: {number_of_full_teams}")

# --- Output ---
# Total students: 17
# Team size: 5
# Number of FULL teams that can be formed: 3

Note on Negative Numbers: When dealing with negative numbers, floor division still rounds the result down (towards negative infinity), which can sometimes be counter-intuitive.

Python
print(f"5 // 2  is: {5 // 2}")     # Output: 2 (2.5 rounded down)
print(f"-5 // 2 is: {-5 // 2}")    # Output: -3 (-2.5 rounded down to -3)

2. Modulo (%) 🕰️

The modulo operator, denoted by the % symbol, returns the remainder of a division operation.

If you divide a number A by a number B ($A/B$), the modulo operator gives you the value left over after B has been subtracted from A as many times as possible.

Practical Example Code

Modulo is essential for tasks like checking for odd/even numbers, cycling through lists, or time conversions.

Python
## Example 2: Checking for even/odd numbers

number_to_check = 25

# If a number is perfectly divisible by 2, the remainder is 0 (it's even)
is_even = number_to_check % 2 == 0

print(f"The number is: {number_to_check}")
print(f"Remainder when divided by 2: {number_to_check % 2}")
print(f"Is the number even? {is_even}")

print("-" * 20)

## Example 3: Time conversion (finding the leftover minutes)

total_minutes = 150

# Use floor division to find the full hours
hours = total_minutes // 60

# Use modulo to find the remaining minutes
minutes = total_minutes % 60

print(f"Total minutes: {total_minutes}")
print(f"Hours: {hours}") # 150 // 60 = 2
print(f"Remaining minutes: {minutes}") # 150 % 60 = 30
print(f"Conversion: {hours} hours and {minutes} minutes")

# --- Example 3 Output ---
# Total minutes: 150
# Hours: 2
# Remaining minutes: 30
# Conversion: 2 hours and 30 minutes

3. f-String (Formatted String Literals) 💬

An f-string is a way to embed expressions directly inside string literals. They provide a concise and highly readable method for formatting strings in Python 3.6 and later.

You create an f-string by prefixing a string with the letter f (or F). Any Python expression (variables, function calls, arithmetic) placed inside curly braces {} within the string will be evaluated and converted to a string in its place.

Practical Example Codes

F-strings are the modern standard for string formatting due to their simplicity and power.

Python
## Example 4: Basic variable substitution

name = "Alice"
age = 30
city = "London"

# Using an f-string to combine variables and text
greeting = f"Hello, my name is {name}, I am {age} years old, and I live in {city}."

print(greeting)

# --- Output ---
# Hello, my name is Alice, I am 30 years old, and I live in London.
Python
## Example 5: Embedding expressions and calculations

price = 19.99
tax_rate = 0.05
quantity = 3

# Embed a calculation directly in the string
total_cost = f"Item price: ${price}. Total for {quantity} items including 5% tax is ${price * quantity * (1 + tax_rate):.2f}"

print(total_cost)

# --- Output ---
# Item price: $19.99. Total for 3 items including 5% tax is $62.97

# The :.2f inside the braces is a format specifier that rounds the result to 2 decimal places.
Python
## Example 6: Function calls and dictionary lookups

def get_status(is_active):
    return "Active" if is_active else "Inactive"

user_data = {"username": "coder_x", "active": True}

report = f"User: {user_data['username']} is {get_status(user_data['active'])}."

print(report)

# --- Output ---
# User: coder_x is Active.

- by Chirana Nimnaka




Comments

Popular posts from this blog

Python Coding Day 1 | The print() Function and Comments

What is Python?

Set Up an Environment to Code in Python