## Data Science and Machine Learning Internship ...

- 22k Enrolled Learners
- Weekend/Weekday
- Live Class

The modulo operation is performed in Python using the % operator, also called the “modulo” operator. When two numbers are split by one another, the modulo operation determines the residual. It is a basic mathematical operation, and the% operator in Python is a flexible tool with a number of uses. In this blog, we’ll discuss the specifics of using Python’s the% operator and some of its many applications.

*🐍 Ready to Unleash the Power of Python? Sign Up for Edureka’s Comprehensive Python Training For Certification with access to hundreds of Python learning Modules and 24/7 technical support.*

Let’s get a hang of what we’re going to cover in this blog:

**Basic Usage:**

It is easy to use the % operator. Both the dividend and the divisor, or the number by which the dividend is divided, are required operands. As a result of the division, the operator returns the remainder. Here’s an easy illustration:

**dividend = 17**

**divisor = 5**

**remainder = dividend % divisor**

**print(remainder) # Output: 2**

In this case, 17 (the value of dividend) is divided by 5 (the value of divisor). The result of this division is 3, with a remainder of 2. Therefore, the remainder variable will be assigned the value 2.

print(remainder) # Output: 2:

Finally, the code prints the value of the remainder variable using the print() function. The output will be 2, which is the remainder of dividing 17 by 5.

To summarize, the code calculates the remainder when 17 is divided by 5 using the % operator and assigns the result (2) to the remainder variable. Then, it prints the value of the remainder variable, which outputs 2.

**Modulo for Determining Even/Odd Numbers**

To detect if an integer is even or odd, the % operator is frequently employed. The remainder of a positive integer divided by two is either 0 for even integers or 1 for odd numbers. Here’s an illustration:

**def is_even(number):**

** return number % 2 == 0**

**number1 = 10**

**number2 = 15**

**print(is_even(number1)) # Output: True**

**print(is_even(number2)) # Output: False**

def is_even(number):

This line defines a function called is_even, which takes one argument called number. The purpose of this function is to determine whether the given number is even or not.

return number % 2 == 0:

The return statement in the function is the core of the logic. It uses the % operator, also known as the “modulo” operator, to calculate the remainder when number is divided by 2. If the remainder is 0, it means the number is divisible by 2, and thus, it is an even number. The function returns True in this case. Otherwise, if the remainder is not 0, the number is not divisible by 2, making it an odd number. The function returns False in this case.

number1 = 10:

In this line, the variable number1 is assigned the value 10, which is an even number.

number2 = 15:

The variable number2 is assigned the value 15, which is an odd number.

print(is_even(number1)) # Output: True:

The code calls the is_even function with number1 (which is 10) as an argument. The function returns True since 10 is an even number, and the output will be True.

print(is_even(number2)) # Output: False:

The code calls the is_even function with number2 (which is 15) as an argument. The function returns False since 15 is not an even number (it’s an odd number), and the output will be False.

In summary, the code defines a function called is_even that determines whether a given number is even or not by using the modulo operator %. It then demonstrates the function’s usage by checking if number1 and number2 are even or odd and prints the respective results: True for number1 (even) and False for number2 (odd).

Except for years that are both divisible by 100 and not divisible by 400, a leap year in the Gregorian calendar is one that is divisible by 4. If a year is a leap year or not, it can be determined using the % operator:

**def is_leap_year(year):**

** return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)**

**year1 = 2000**

**year2 = 2021**

**print(is_leap_year(year1)) # Output: True**

**print(is_leap_year(year2)) # Output: False**

def is_leap_year(year):

This line defines a function called is_leap_year, which takes one argument called year. The purpose of this function is to determine whether the given year is a leap year or not.

return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)

The return statement in the function contains the logic to determine if the year is a leap year or not.

The logic follows the rules for identifying leap years in the Gregorian calendar:

A year is a leap year if it is divisible by 4.

However, if a year is divisible by 100, it is not a leap year, unless it is also divisible by 400.

The expression year % 4 == 0 checks if the year is divisible by 4. If this condition is True, the first part of the expression is satisfied.

The expression (year % 100 != 0 or year % 400 == 0) is an “or” condition, which means it will evaluate to True if either of its sub-conditions is True. The sub-conditions are as follows:

year % 100 != 0: This checks if the year is not divisible by 100. If this condition is True, it means the year is either not divisible by 100 or is not a multiple of 100, which satisfies the “leap year” condition.

year % 400 == 0: This checks if the year is divisible by 400. If this condition is True, it means the year is a multiple of 400, which also satisfies the “leap year” condition.

Therefore, the entire expression year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) will be True if the year is a leap year, and False if it is not.

print(is_leap_year(year1)) # Output: True

The code calls the is_leap_year function with year1 (which is 2000) as an argument. The function returns True since 2000 is a leap year, and the output will be True.

print(is_leap_year(year2)) # Output: False

The code calls the is_leap_year function with year2 (which is 2021) as an argument. The function returns False since 2021 is not a leap year, and the output will be False.

The code defines a function called is_leap_year that determines whether a given year is a leap year or not based on the rules of the Gregorian calendar. It then demonstrates the function’s usage by checking if year1 and year2 are leap years or not and prints the respective results: True for year1 (leap year) and False for year2 (not a leap year).

The % operator can also be used for string formatting. It is an older method of string formatting in Python, often referred to as “old-style string formatting.” It involves using the % operator together with a formatting specifier to insert values into a string. The syntax is as follows:

**format_string = “Hello, %s! You are %d years old.”**

**name = “John”**

**age = 30**

**formatted_string = format_string % (name, age)**

**print(formatted_string) # Output: “Hello, John! You are 30 years old.”**

format_string = “Hello, %s! You are %d years old.”

In this line, a string is assigned to the variable format_string. The string contains placeholders denoted by %s and %d. These placeholders serve as slots to be filled with actual values later in the code.

%s is a placeholder for a string value.

%d is a placeholder for an integer value.

name = “John”

Here, the variable name is assigned the value “John”. It is a string variable that will be used to replace the %s placeholder in the format_string.

age = 30

The variable age is assigned the value 30, which is an integer. It will be used to replace the %d placeholder in the format_string.

formatted_string = format_string % (name, age)

This line combines the values of name and age with the format_string using the % operator. The % operator, in this context, is used for string formatting, specifically the “old-style string formatting” method.

The % operator expects a tuple containing the values to be inserted into the placeholders. In this case, the tuple contains name and age, so the % operator replaces %s with “John” and %d with 30, resulting in the formatted string “Hello, John! You are 30 years old.”.

print(formatted_string) # Output: “Hello, John! You are 30 years old.”

Finally, the formatted string is printed to the console using the print() function, and the output will be “Hello, John! You are 30 years old.”.

Utilising indices and cyclic iterations are both possible with the % operator. Consider a list of things, for instance, that you want to iterate through in a circular fashion. To accomplish this, use the % operator:

**items = [“apple”, “banana”, “orange”, “grape”]**

**for i in range(10):**

** item = items[i % len(items)]**

** print(item)**

In this code, we have a list items containing fruits: “apple”, “banana”, “orange”, and “grape.” The code then uses a for loop to iterate 10 times. During each iteration, it calculates the index using i % len(items), which ensures that the index stays within the range of the items list. The value at that index is then printed to the console.

Since the for loop iterates 10 times, it will output the elements of the items list in a cyclic manner. The output will be:

**apple**

**banana**

**orange**

**grape**

**apple**

**banana**

**orange**

**grape**

**apple**

**banana**

Floating-point numbers with a defined precision can be formatted using the% operator. The following is the syntax for formatting floating-point numbers:

**pi = 3.14159265359**

**formatted_pi = “Value of pi: %.2f” % pi**

**print(formatted_pi) # Output: “Value of pi: 3.14”**

In this code, we have a variable pi storing the value of pi (approximately 3.14159265359). The code then uses string formatting with the % operator to create a new string formatted_pi.

The %f format specifier in the string “Value of pi: %.2f” indicates that the variable pi should be inserted into the string as a floating-point number with two decimal places.

When we use % pi at the end of the string, it replaces %f with the value of pi, formatted to two decimal places. The resulting string, “Value of pi: 3.14”, is then printed to the console. This allows us to display the value of pi with a specific level of precision in the output.

Modulo for Integer Wrapping

When you wish to retain a value within a specific range, the% operator can be used to accomplish integer wrapping. For instance, you could want to guarantee that an index stays inside a list’s boundaries:

def get_wrapped_index(index, list_length):

return index % list_length

index1 = 8

index2 = 15

list_length = 5

print(get_wrapped_index(index1, list_length)) # Output: 3

print(get_wrapped_index(index2, list_length)) # Output: 0

n this code, we have a function called get_wrapped_index that takes two arguments: index and list_length. The function calculates and returns the wrapped index, which ensures that the index stays within the range of the list.

The line return index % list_length uses the % operator (modulo operator) to calculate the remainder when index is divided by list_length. This remainder represents the wrapped index within the range of the list.

For example, let’s consider index1 = 8 and list_length = 5:

The remainder of 8 % 5 is 3, so the function returns 3, ensuring that the index 8 wraps around and stays within the range of the list [0, 1, 2, 3, 4].

Similarly, for index2 = 15 and list_length = 5:

The remainder of 15 % 5 is 0, so the function returns 0, indicating that the index 15 wraps around and corresponds to the index 0 in the list.

When the code prints the output for both cases, the results will be:

3

0

**Considerations for Performance **

Even though the % operator is practical and flexible, it’s important to keep in mind that in some circumstances, alternative methods, such as bitwise operations or the usage of the divmod() function, might provide better performance for particular instances. However, the% operator performs well for the majority of ordinary use cases and continues to be a popular and dependable tool for numerous operations in Python.

Upcoming Batches For Python Programming Certification Course

Course Name | Date | Details |
---|---|---|

Python Programming Certification Course | Class Starts on 30th November,2024 30th November SAT&SUN (Weekend Batch) | View Details |

Python Programming Certification Course | Class Starts on 28th December,2024 28th December SAT&SUN (Weekend Batch) | View Details |

Comments 0 Comments

REGISTER FOR FREE WEBINAR

Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

edureka.co