TutorialsTonight Logo

10 Number Pattern In Python

In this tutorial, we are going to discuss different number pattern in python. You can use the programs below in your python programs as well.

Number Pattern

Number pattern is a pattern created by numbers of any geometrical shape using controlled loops like squares, triangles, rectangles, etc.

Let us see some examples of number patterns in python.

alphabet pattern example

The above image shows some of the number patterns that you can create in python. Apart from these, there are many more number patterns that you can think of and create.

Print numbers from 0 to 9

Before we start creating number patterns, let us first see how to print numbers from 0 to 9.

To do this you can simply use for loop to loop through the numbers from 0 to 9 and print them.

Let's now create different number patterns.

1. Square Patterns

The square pattern is very simple to create using python. You need to use 2 nested loops to create a square pattern.

The internal loop will print the number of times you want to print the number. The outer loop will execute the internal loop for the number of times you want.

2. Left Triangle Alphabet Pattern

The left triangle pattern is a pattern in the shape of a triangle created using numbers.

The program for this will be 2 nested loops where the inner loop will print the number of times the outer loop is executed and print the number in every iteration.

You can create variations in this pattern by creating 1 pattern that changes every next number in a row or another pattern that changes every next number in a column.

3. Right triangle Pattern

You can see above how the right triangle number pattern looks like.

The pattern starts with a bunch of spaces and then the number increases in every iteration.

To create this pattern, you can use 2 internal loops where the first loop will print spaces and the second loop will print the number. The outer loop will execute the inner loop for the number of times you want.

4. Hollow triangle alphabet Pattern

You can see above how the hollow triangle pattern looks. It is a bit complex to create because of the spaces within the pattern.

To create this keep a few things in mind, print only numbers in the first and last row, and in other rows print numbers only at the first and last position of the row and rest print spaces.

5. Number Pyramid Pattern

The pyramid pattern is a very famous pattern you can create it using numbers too.

Every line has an odd number of numbers, the first line has 1 number, the second line has 2 numbers, the third line has 3 numbers, and so on.

The program will have 2 internal loops where the first loop will print spaces and the second loop will print the 2n + 1 increasing numbers.

6. Hollow Number Pyramid Pattern

The hollow number pyramid pattern is a little bit tricky just as the hollow triangle pattern.

This is the same as the hollow triangle pattern except it also has spaces at starting of the row.

7. Reverse Number Pyramid Pattern

You can see above reverse number pyramid pattern is equivalent to a number pyramid pattern but upside down.

This is may look not easy but it is very simple to create. Here is the program for this pattern.

8. Number Diamond Pattern

This is a number diamond pattern . Try observing it closely you will find 2 figures in the pattern, one is the number pyramid and the other is the reverse number pyramid.

So you have to create a program that prints a number pyramid and reverses the number pyramid pattern back to back.

Let's see the complete program for this pattern.

9. Number Hourglass pattern

The number hourglass pattern is again a famous pattern you can create it using numbers. It is the same as a diamond pattern but you should have a vision for this as how it is that.

When observed you will find 2 figures in the pattern, one is the number pyramid and the other is the reverse number pyramid.

So using the concepts of the above program here is a complete program for this pattern.

10. Right pascal triangle pattern

The right pascal triangle pattern is shown above. Again it contains 2 figures within it, one is a left triangle and the other is a reverse left triangle.

You have seen above how to create both of them. Let's see the complete code for this pattern.

11. Heart pattern in python

The number heart pattern can be created using numbers and spaces. It is really pattern complex to create.

You can see the complete code of heart pattern below.

Note - Do not increase the size of the heart by more than 4 because numbers become 2 digits after 9 which will distort the shape of the heart.

You have learned to create many different types of number pattern in python in this section. Now you have enough experience to create many other patterns.

For further exploration, you can see pattern programs in python .

Python Program to Print 8 Star Pattern

Python program to print 8 star pattern using a while loop.

2 Easy Ways to Extract Digits from a Python String

Ways To Extract Digits From A String

Hello, readers! In this article, we will be focusing on the ways to extract digits from a Python String . So, let us get started.

1. Making use of isdigit() function to extract digits from a Python string

Python provides us with string.isdigit() to check for the presence of digits in a string.

Python isdigit() function returns True if the input string contains digit characters in it.

We need not pass any parameter to it. As an output, it returns True or False depending upon the presence of digit characters in a string.

In this example, we have iterated the input string character by character using a for loop. As soon as the isdigit() function encounters a digit, it will store it into a string variable named ‘num’.

Thus, we see the output as shown below–

Now, we can even use Python list comprehension to club the iteration and idigit() function into a single line.

By this, the digit characters get stored into a list ‘num’ as shown below:

2. Using regex library to extract digits

Python regular expressions library called ‘ regex library ‘ enables us to detect the presence of particular characters such as digits, some special characters, etc. from a string.

We need to import the regex library into the python environment before executing any further steps.

Further, we we re.findall(r'\d+', string) to extract digit characters from the string. The portion ‘\d+’ would help the findall() function to detect the presence of any digit.

So, as seen below, we would get a list of all the digit characters from the string.

By this, we have come to the end of this topic. Feel free to comment below, in case you come across any question.

I recommend you all to try implementing the above examples using data structures such as lists , dict , etc.

For more such posts related to Python, Stay tuned and till then, Happy Learning!! 🙂

  • Python Course
  • Python Basics
  • Interview Questions
  • Python Quiz
  • Popular Packages
  • Python Projects
  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Dictionaries

Python | Extract digits from given string

While programming, sometimes, we just require a certain type of data and need to discard other. This type of problem is quite common in Data Science domain, and since Data Science uses Python worldwide, its important to know how to extract specific elements. This article discusses certain ways in which only digit can be extracted. Let’s discuss the same.

Method #1 : Using join() + isdigit() + filter()

This task can be performed using the combination of above functions. The filter function filters the digits detected by the isdigit function and join function performs the task of reconstruction of join function.  

 

  Method #2 : Using re  

The regular expressions can also be used to perform this particular task. We can define the digit type requirement, using “\D”, and only digits are extracted from the string. 

 

Method 3: Using loops:

This task is done by using for loop.

Time Complexity: O(n) Auxiliary Space: O(1)

Method 4: Using recursion:

Method 5: Using ord() method 

Method 6 : Using isnumeric() method

  • Initiate a for loop to traverse the string
  • Check whether the character is numeric by using isnumeric()
  • Display the character if numeric

Time Complexity : O(N) N – length of string

Auxiliary Space :O(1)

author

Please Login to comment...

Similar reads.

  • Python Programs
  • Python string-programs
  • OpenAI o1 AI Model Launched: Explore o1-Preview, o1-Mini, Pricing & Comparison
  • How to Merge Cells in Google Sheets: Step by Step Guide
  • How to Lock Cells in Google Sheets : Step by Step Guide
  • PS5 Pro Launched: Controller, Price, Specs & Features, How to Pre-Order, and More
  • #geekstreak2024 – 21 Days POTD Challenge Powered By Deutsche Bank

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

How to compare two two digit integers as is, reversed, and one character at a time

I am new to programming and am trying to learn it by taking an intro class using python.

One of my assignments requires us to do the following:

compare a randomly generated two digit integer with a user generated two digit integer.

  • if both the random and user generated integers match print blah1
  • if the user generated integer has the same two digits as the random generated integer in reverse, print blah2
  • if the user generated integer has one digit that is the same as the randomly generated integer, print blah3.

Now, so far, we have only learned the basic stuff, (operators, if / else / elif , while loops, printing, strings, integers)

I came up with something that randomly assigns two digits, converts them into strings, and then concatenates them into a two digit string. From here, I used elif statements to match each possible condition.

Unfortunately, that's not what's required. I must use two digit integers when I do my comparisons. Unfortunately, I have absolutely no clue how to compare portions of an integer, or reverse the integer with what I've been taught.

Now, I am not looking for someone to solve this for me. I want some help, either a hint or a suggestion on how I should think about this with the basic knowledge I have.

Any and all help is greatly appreciated.

I've included the code that I wrote.

Martijn Pieters's user avatar

3 Answers 3

There are three tricks that'll help you here:

Lists can be compared just like strings and numbers. A list of integers can be compared to another and if the contained numbers are the same, the comparison returns True :

You can reverse a list easily. You can use the reversed() built-in function, or you can use the [start:stop:stride] slice notation to give a negative stride. The latter gives you a reversed list too:

The reversed() function returns an iterator, by passing that to the list() constructor we get a list again.

You can use the in operator to test list membership. Use this to test if an individual integer is part of a list of integers:

These 3 tricks together should give you all the tools you need to re-program your script to work with integers. Store both your random numbers and the user input (turned to integers with the int() function) in lists and work your way from there.

If you must accept one integer input between 10 and 99 things get a little trickier. You can separate out the 10s and the 1s by using th modulo % and division \ operators:

You can combine the two operations using the divmod() function :

Now you have two separate integers again to do your comparisons with.

  • Sameer might also find it helpful to know that the obvious [1,2]==reversed([2,1]) gives False , you have to use [1,2]==list(reversed([2,1])) or the slicing notation to get a list for comparison. BTW, I don't believe your output for the example you gave using reversed() . –  Duncan Commented Sep 27, 2012 at 9:01
  • Right, in Python 3, reversed is an iterator, I am using Python 2 too often still. I'll correct. –  Martijn Pieters Commented Sep 27, 2012 at 9:43
  • Doesn't reversed return a listreverseiterator object in Python 2 as well? –  DSM Commented Sep 27, 2012 at 12:43
  • @MartijnPieters: i don't know why i didn't notice the integer division and modulus operators before. thanks, that pretty much did it. –  Sameer Sheikh Commented Sep 28, 2012 at 4:14

I think the challenge you're facing is how to get the separate digits from a two digit integer. It is possible to do using mathematical operators.

Just think about what each digit in a number like 42 represents. The 4 is the "tens" digit and the 2 is the "ones" digit. It might help to think about it in reverse. If you have the integers 4 and a 2 in separate variables, how would you assemble them into the single integer 42 ?

Hopefully my hints will help you out! If I've been too oblique, I can try to elaborate a bit more, but I do want you to be able to solve it on your own, and I suspect you'll get it quickly once you've thought of the right operators to use.

Blckknght's user avatar

alright, thanks to everyone's help. because of your suggestions and hints, i managed to complete the assignment according to specs.

while, i am not too proud of how it was done - just seems sloppy to me - it works.

here it is:

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged python string python-3.x integer logic or ask your own question .

  • The Overflow Blog
  • The world’s largest open-source business has plans for enhancing LLMs
  • Looking under the hood at the tech stack that powers multimodal AI
  • Featured on Meta
  • Join Stack Overflow’s CEO and me for the first Stack IRL Community Event in...
  • User activation: Learnings and opportunities
  • What does a new user need in a homepage experience on Stack Overflow?
  • Announcing the new Staging Ground Reviewer Stats Widget

Hot Network Questions

  • How to react to a rejection based on a single one-line negative review?
  • How can I use an op-amp in differential configuration to measure voltage across a MOSFET?
  • Grothendieck topoi as a constructive property
  • A certain solution for Sine-Gordon Equation
  • HTA w/ VBScript to open and copy links
  • How to translate the letter Q to Japanese?
  • What do I NEED?
  • Cartoon Network (Pakistan or India) show around 2007 or 2009 featuring a brother and sister who fight but later become allies
  • How to rectify a mistake in DS 160
  • How can I assign a heredoc to a variable in a way that's portable across Unix and Mac?
  • Counting the number of meetings
  • Is the forced detention of adult students by private universities legal?
  • Why does fdisk create a 512B partition when I enter +256K?
  • Can All Truths Be Scientifically Verified?
  • 〈ü〉 vs 〈ue〉 in German, particularly names
  • What does "either" refer to in "We don't have to run to phone booths anymore, either"?
  • Bach's figured bass notation?
  • Hungarian Immigration wrote a code on my passport
  • On Concordant Readings in Titrations
  • Does the different strength of gravity at varying heights affect the forces within a suspended or standing object
  • Can turbo trainers be easily damaged when instaling a cassette?
  • Grid-based pathfinding for a lot of agents: how to implement "Tight-Following"?
  • Determining Entropy in PHP
  • Ellipsoid name from semi-major axis and flattening

digit 9 in python assignment expert

CopyAssignment

We are Python language experts, a community to solve Python problems, we are a 1.2 Million community on Instagram, now here to help with our blogs.

  • Single Digit Number in Python

Problem Statement:

In this Single Digit Number in Python problem, we are given a number, we need to add its digits, and we need to repeat this until the addition results in a single digit. At last, we need to print the result. For example, 78=> 7+8=>15=>1+5=>6.

Code for Single Digit Number in Python:

Single Digit Number in Python | Assignment Expert

Explanation:

We imported the math module, declared n, and assigned 78 to it. Then inside it, we first check if n is between 1 and 9, we will print it else we will add it’s both digits. Our output results in 6 because 78=> 7+8=>15=>1+5=>6.

  • Hyphenate Letters in Python
  • Earthquake in Python | Easy Calculation
  • Striped Rectangle in Python
  • Perpendicular Words in Python
  • Free shipping in Python
  • Raj has ordered two electronic items Python | Assignment Expert
  • Team Points in Python
  • Ticket selling in Cricket Stadium using Python | Assignment Expert
  • Split the sentence in Python
  • String Slicing in JavaScript
  • First and Last Digits in Python | Assignment Expert
  • List Indexing in Python
  • Date Format in Python | Assignment Expert
  • New Year Countdown in Python
  • Add Two Polynomials in Python
  • Sum of even numbers in Python | Assignment Expert
  • Evens and Odds in Python
  • A Game of Letters in Python
  • Sum of non-primes in Python
  • Smallest Missing Number in Python
  • String Rotation in Python
  • Secret Message in Python
  • Word Mix in Python
  • Shift Numbers in Python | Assignment Expert
  • Weekend in Python
  • Temperature Conversion in Python
  • Special Characters in Python
  • Sum of Prime Numbers in the Input in Python

' src=

Author: Harry

digit 9 in python assignment expert

Search….

digit 9 in python assignment expert

Machine Learning

Data Structures and Algorithms(Python)

Python Turtle

Games with Python

All Blogs On-Site

Python Compiler(Interpreter)

Online Java Editor

Online C++ Editor

Online C Editor

All Editors

Services(Freelancing)

Recent Posts

  • Most Underrated Database Trick | Life-Saving SQL Command
  • Python List Methods
  • Top 5 Free HTML Resume Templates in 2024 | With Source Code
  • How to See Connected Wi-Fi Passwords in Windows?
  • 2023 Merry Christmas using Python Turtle

Š Copyright 2019-2024 www.copyassignment.com. All rights reserved. Developed by copyassignment

Python Modulo in Practice: How to Use the % Operator

Python Modulo in Practice: How to Use the % Operator

Table of Contents

Modulo in Mathematics

Modulo operator with int, modulo operator with float, modulo operator with a negative operand, modulo operator and divmod(), modulo operator precedence, how to check if a number is even or odd, how to run code at specific intervals in a loop, how to create cyclic iteration, how to convert units, how to determine if a number is a prime number, how to implement ciphers, using the python modulo operator with decimal.decimal, using the python modulo operator with custom classes.

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Python Modulo: Using the % Operator

Python supports a wide range of arithmetic operators that you can use when working with numbers in your code. One of these operators is the modulo operator ( % ), which returns the remainder of dividing two numbers.

In this tutorial, you’ll learn:

  • How modulo works in mathematics
  • How to use the Python modulo operator with different numeric types
  • How Python calculates the results of a modulo operation
  • How to override .__mod__() in your classes to use them with the modulo operator
  • How to use the Python modulo operator to solve real-world problems

The Python modulo operator can sometimes be overlooked. But having a good understanding of this operator will give you an invaluable tool in your Python tool belt.

Free Bonus: Click here to get a Python Cheat Sheet and learn the basics of Python 3, like working with data types, dictionaries, lists, and Python functions.

The term modulo comes from a branch of mathematics called modular arithmetic . Modular arithmetic deals with integer arithmetic on a circular number line that has a fixed set of numbers. All arithmetic operations performed on this number line will wrap around when they reach a certain number called the modulus .

A classic example of modulo in modular arithmetic is the twelve-hour clock. A twelve-hour clock has a fixed set of values, from 1 to 12. When counting on a twelve-hour clock, you count up to the modulus 12 and then wrap back to 1. A twelve-hour clock can be classified as “modulo 12,” sometimes shortened to “mod 12.”

The modulo operator is used when you want to compare a number with the modulus and get the equivalent number constrained to the range of the modulus.

For example, say you want to determine what time it would be nine hours after 8:00 a.m. On a twelve-hour clock, you can’t simply add 9 to 8 because you would get 17. You need to take the result, 17, and use mod to get its equivalent value in a twelve-hour context:

17 mod 12 returns 5 . This means that nine hours past 8:00 a.m. is 5:00 p.m. You determined this by taking the number 17 and applying it to a mod 12 context.

Now, if you think about it, 17 and 5 are equivalent in a mod 12 context. If you were to look at the hour hand at 5:00 and 17:00, it would be in the same position. Modular arithmetic has an equation to describe this relationship:

This equation reads “ a and b are congruent modulo n .” This means that a and b are equivalent in mod n as they have the same remainder when divided by n . In the above equation, n is the modulus for both a and b . Using the values 17 and 5 from before, the equation would look like this:

This reads “ 17 and 5 are congruent modulo 12 .” 17 and 5 have the same remainder, 5 , when divided by 12 . So in mod 12 , the numbers 17 and 5 are equivalent.

You can confirm this using division:

Both of the operations have the same remainder, 5 , so they’re equivalent modulo 12 .

Now, this may seem like a lot of math for a Python operator, but having this knowledge will prepare you to use the modulo operator in the examples later in this tutorial. In the next section, you’ll look at the basics of using the Python modulo operator with the numeric types int and float .

Python Modulo Operator Basics

The modulo operator, like the other arithmetic operators, can be used with the numeric types int and float . As you’ll see later on, it can also be used with other types like math.fmod() , decimal.Decimal , and your own classes.

Most of the time you’ll use the modulo operator with integers. The modulo operator, when used with two positive integers, will return the remainder of standard Euclidean division :

Be careful! Just like with the division operator ( / ), Python will return a ZeroDivisionError if you try to use the modulo operator with a divisor of 0 :

Next, you’ll take a look at using the modulo operator with a float .

Similar to int , the modulo operator used with a float will return the remainder of division, but as a float value:

An alternative to using a float with the modulo operator is to use math.fmod() to perform modulo operations on float values:

The official Python docs suggest using math.fmod() over the Python modulo operator when working with float values because of the way math.fmod() calculates the result of the modulo operation. If you’re using a negative operand, then you may see different results between math.fmod(x, y) and x % y . You’ll explore using the modulo operator with negative operands in more detail in the next section.

Just like other arithmetic operators, the modulo operator and math.fmod() may encounter rounding and precision issues when dealing with floating-point arithmetic :

If maintaining floating-point precision is important to your application, then you can use the modulo operator with decimal.Decimal . You’ll look at this later in this tutorial .

All modulo operations you’ve seen up to this point have used two positive operands and returned predictable results. When a negative operand is introduced, things get more complicated.

As it turns out, the way that computers determine the result of a modulo operation with a negative operand leaves ambiguity as to whether the remainder should take the sign of the dividend (the number being divided) or the sign of the divisor (the number by which the dividend is divided). Different programming languages handle this differently.

For example, in JavaScript , the remainder will take the sign of the dividend:

The remainder in this example, 2 , is positive since it takes the sign of the dividend, 8 . In Python and other languages, the remainder will take the sign of the divisor instead:

Here you can see that the remainder, -1 , takes the sign of the divisor, -3 .

You may be wondering why the remainder in JavaScript is 2 and the remainder in Python is -1 . This has to do with how different languages determine the outcome of a modulo operation. Languages in which the remainder takes the sign of the dividend use the following equation to determine the remainder:

There are three variables this equation:

  • r is the remainder.
  • a is the dividend.
  • n is the divisor.

trunc() in this equation means that it uses truncated division , which will always round a negative number toward zero. For more clarification, see the steps of the modulo operation below using 8 as the dividend and -3 as the divisor:

Here you can see how a language like JavaScript gets the remainder 2 . Python and other languages in which the remainder takes the sign of the divisor use the following equation:

floor() in this equation means that it uses floor division . With positive numbers, floor division will return the same result as truncated division. But with a negative number, floor division will round the result down, away from zero:

Here you can see that the result is -1 .

Now that you understand where the difference in the remainder comes from, you may be wondering why this matters if you only use Python. Well, as it turns out, not all modulo operations in Python are the same. While the modulo used with the int and float types will take the sign of the divisor, other types will not.

You can see an example of this when you compare the results of 8.0 % -3.0 and math.fmod(8.0, -3.0) :

math.fmod() takes the sign of the dividend using truncated division, whereas float uses the sign of the divisor. Later in this tutorial, you’ll see another Python type that uses the sign of the dividend, decimal.Decimal .

Python has the built-in function divmod() , which internally uses the modulo operator. divmod() takes two parameters and returns a tuple containing the results of floor division and modulo using the supplied parameters.

Below is an example of using divmod() with 37 and 5 :

You can see that divmod(37, 5) returns the tuple (7, 2) . The 7 is the result of the floor division of 37 and 5 . The 2 is the result of 37 modulo 5 .

Below is an example in which the second parameter is a negative number. As discussed in the previous section, when the modulo operator is used with an int , the remainder will take the sign of the divisor:

Now that you’ve had a chance to see the modulo operator used in several scenarios, it’s important to take a look at how Python determines the precedence of the modulo operator when used with other arithmetic operators.

Like other Python operators, there are specific rules for the modulo operator that determine its precedence when evaluating expressions . The modulo operator ( % ) shares the same level of precedence as the multiplication ( * ), division ( / ), and floor division ( // ) operators.

Take a look at an example of the modulo operator’s precedence below:

Both the multiplication and modulo operators have the same level of precedence, so Python will evaluate them from left to right. Here are the steps for the above operation:

  • 4 * 10 is evaluated, resulting in 40 % 12 - 9 .
  • 40 % 12 is evaluated, resulting in 4 - 9 .
  • 4 - 9 is evaluated, resulting in -5 .

If you want to override the precedence of other operators, then you can use parentheses to surround the operation you want to be evaluated first:

In this example, (12 - 9) is evaluated first, followed by 4 * 10 and finally 40 % 3 , which equals 1 .

Python Modulo Operator in Practice

Now that you’ve gone through the basics of the Python modulo operator, you’ll look at some examples of using it to solve real-world programming problems. At times, it can be hard to determine when to use the modulo operator in your code. The examples below will give you an idea of the many ways it can be used.

In this section, you’ll see how you can use the modulo operator to determine if a number is even or odd. Using the modulo operator with a modulus of 2 , you can check any number to see if it’s evenly divisible by 2 . If it is evenly divisible, then it’s an even number.

Take a look at is_even() which checks to see if the num parameter is even:

Here num % 2 will equal 0 if num is even and 1 if num is odd. Checking against 0 will return a Boolean of True or False based on whether or not num is even.

Checking for odd numbers is quite similar. To check for an odd number, you invert the equality check:

This function will return True if num % 2 does not equal 0 , meaning that there’s a remainder proving num is an odd number. Now, you may be wondering if you could use the following function to determine if num is an odd number:

The answer to this question is yes and no. Technically, this function will work with the way Python calculates modulo with integers. That said, you should avoid comparing the result of a modulo operation with 1 as not all modulo operations in Python will return the same remainder.

You can see why in the following examples:

In the second example, the remainder takes the sign of the negative divisor and returns -1 . In this case, the Boolean check 3 % -2 == 1 would return False .

However, if you compare the modulo operation with 0 , then it doesn’t matter which operand is negative. The result will always be True when it’s an even number:

If you stick to comparing a Python modulo operation with 0 , then you shouldn’t have any problems checking for even and odd numbers or any other multiples of a number in your code.

In the next section, you’ll take a look at how you can use the modulo operator with loops to control the flow of your program.

With the Python modulo operator, you can run code at specific intervals inside a loop. This is done by performing a modulo operation with the current index of the loop and a modulus. The modulus number determines how often the interval-specific code will run in the loop.

Here’s an example:

This code defines split_names_into_rows() , which takes two parameters. name_list is a list of names that should be split into rows. modulus sets a modulus for the operation, effectively determining how many names should be in each row. split_names_into_rows() will loop over name_list and start a new row after it hits the modulus value.

Before breaking down the function in more detail, take a look at it in action:

As you can see, the list of names has been split into three rows, with a maximum of three names in each row. modulus defaults to 3 , but you can specify any number:

Now that you’ve seen the code in action, you can break down what it’s doing. First, it uses enumerate() to iterate over name_list , assigning the current item in the list to name and a count value to index . You can see that the optional start argument for enumerate() is set to 1 . This means that the index count will start at 1 instead of 0 :

Next, inside the loop, the function calls print() to output name to the current row. The end parameter for print() is an empty string ( "" ) so it won’t output a newline at the end of the string. An f-string is passed to print() , which uses the string output formatting syntax that Python provides:

Without getting into too much detail, the :-^15 syntax tells print() to do the following:

  • Output at least 15 characters, even if the string is shorter than 15 characters.
  • Center align the string.
  • Fill any space on the right or left of the string with the hyphen character ( - ).

Now that the name has been printed to the row, take a look at the main part of split_names_into_rows() :

This code takes the current iteration index and, using the modulo operator, compares it with modulus . If the result equals 0 , then it can run interval-specific code. In this case, the function calls print() to add a newline, which starts a new row.

The above code is only one example. Using the pattern index % modulus == 0 allows you to run different code at specific intervals in your loops. In the next section, you’ll take this concept a bit further and look at cyclic iteration.

Cyclic iteration describes a type of iteration that will reset once it gets to a certain point. Generally, this type of iteration is used to restrict the index of the iteration to a certain range.

You can use the modulo operator to create cyclic iteration. Take a look at an example using the turtle library to draw a shape:

The above code uses an infinite loop to draw a repeating star shape. After every six iterations, it changes the color of the pen. The pen size increases with each iteration until i is reset back to 0 . If you run the code, then you should get something similar to this:

Example of cyclic iteration using Python mod (%) Operator

The important parts of this code are highlighted below:

Each time through the loop, i is updated based on the results of (i + 1) % 6 . This new i value is used to increase the .pensize with each iteration. Once i reaches 5 , (i + 1) % 6 will equal 0 , and i will reset back to 0 .

You can see the steps of the iteration below for more clarification:

When i is reset back to 0 , the .pencolor changes to a new random color as seen below:

The code in this section uses 6 as the modulus, but you could set it to any number to adjust how many times the loop will iterate before resetting the value i .

In this section, you’ll look at how you can use the modulo operator to convert units. The following examples take smaller units and convert them into larger units without using decimals. The modulo operator is used to determine any remainder that may exist when the smaller unit isn’t evenly divisible by the larger unit.

In this first example, you’ll convert inches into feet. The modulo operator is used to get the remaining inches that don’t evenly divide into feet. The floor division operator ( // ) is used to get the total feet rounded down:

Here’s an example of the function in use:

As you can see from the output, 450 % 12 returns 6 , which is the remaining inches that weren’t evenly divided into feet. The result of 450 // 12 is 37 , which is the total number of feet by which the inches were evenly divided.

You can take this a bit further in this next example. convert_minutes_to_days() takes an integer, total_mins , representing a number of minutes and outputs the period of time in days, hours, and minutes:

Breaking this down, you can see that the function does the following:

  • Determines the total number of evenly divisible days with total_mins // 1440 , where 1440 is the number of minutes in a day
  • Calculates any extra_minutes left over with total_mins % 1440
  • Uses the extra_minutes to get the evenly divisible hours and any extra minutes

You can see how it works below:

While the above examples only deal with converting inches to feet and minutes to days, you could use any type of units with the modulo operator to convert a smaller unit into a larger unit.

Note : Both of the above examples could be modified to use divmod() to make the code more succinct. If you remember, divmod() returns a tuple containing the results of floor division and modulo using the supplied parameters.

Below, the floor division and modulo operators have been replaced with divmod() :

As you can see, divmod(total_inches, 12) returns a tuple, which is unpacked into feet and inches .

If you try this updated function, then you’ll receive the same results as before:

You receive the same outcome, but now the code is more concise. You could update convert_minutes_to_days() as well:

Using divmod() , the function is easier to read than the previous version and returns the same result:

Using divmod() isn’t necessary for all situations, but it makes sense here as the unit conversion calculations use both floor division and modulo.

Now that you’ve seen how to use the modulo operator to convert units, in the next section you’ll look at how you can use the modulo operator to check for prime numbers.

In this next example, you’ll take a look at how you can use the Python modulo operator to check whether a number is a prime number . A prime number is any number that contains only two factors, 1 and itself. Some examples of prime numbers are 2 , 3 , 5 , 7 , 23 , 29 , 59 , 83 , and 97 .

The code below is an implementation for determining the primality of a number using the modulo operator:

This code defines check_prime_number() , which takes the parameter num and checks to see if it’s a prime number. If it is, then a message is displayed stating that num is a prime number. If it’s not a prime number, then a message is displayed with all the factors of the number.

Note: The above code isn’t the most efficient way to check for prime numbers. If you’re interested in digging deeper, then check out the Sieve of Eratosthenes and Sieve of Atkin for examples of more performant algorithms for finding prime numbers.

Before you look more closely at the function, here are the results using some different numbers:

Digging into the code, you can see it starts by checking if num is less than 2 . Prime numbers can only be greater than or equal to 2 . If num is less than 2 , then the function doesn’t need to continue. It will print() a message and return :

If num is greater than 2 , then the function checks if num is a prime number. To check this, the function iterates over all the numbers between 2 and the square root of num to see if any divide evenly into num . If one of the numbers divides evenly, then a factor has been found, and num can’t be a prime number.

Here’s the main part of the function:

There’s a lot to unpack here, so let’s take it step by step.

First, a factors list is created with the initial factors, (1, num) . This list will be used to store any other factors that are found:

Next, starting with 2 , the code increments i until it reaches the square root of num . At each iteration, it compares num with i to see if it’s evenly divisible. The code only needs to check up to and including the square root of num because it wouldn’t contain any factors above this:

Instead of trying to determine the square root of num , the function uses a while loop to see if i * i <= num . As long as i * i <= num , the loop hasn’t reached the square root of num .

Inside the while loop, the modulo operator checks if num is evenly divisible by i :

If num is evenly divisible by i , then i is a factor of num , and a tuple of the factors is added to the factors list.

Once the while loop is complete, the code checks to see if any additional factors were found:

If more than one tuple exists in the factors list, then num can’t be a prime number. For nonprime numbers, the factors are printed out. For prime numbers, the function prints a message stating that num is a prime number.

The Python modulo operator can be used to create ciphers . A cipher is a type of algorithm for performing encryption and decryption on an input , usually text. In this section, you’ll look at two ciphers, the Caesar cipher and the Vigenère cipher .

Caesar Cipher

The first cipher that you’ll look at is the Caesar cipher , named after Julius Caesar, who used it to secretly communicate messages. It’s a substitution cipher that uses letter substitution to encrypt a string of text.

The Caesar cipher works by taking a letter to be encrypted and shifting it a certain number of positions to the left or right in the alphabet. Whichever letter is in that position is used as the encrypted character. This same shift value is applied to all characters in the string.

For example, if the shift were 5 , then A would shift up five letters to become F , B would become G , and so on. Below you can see the encryption process for the text REALPYTHON with a shift of 5 :

The resulting cipher is WJFQUDYMTS .

Decrypting the cipher is done by reversing the shift. Both the encryption and decryption processes can be described with the following expressions, where char_index is the index of the character in the alphabet:

This cipher uses the modulo operator to make sure that, when shifting a letter, the index will wrap around if the end of the alphabet is reached. Now that you know how this cipher works, take a look at an implementation:

This code defines a function called caesar_cipher() , which has two required parameters and one optional parameter:

  • text is the text to be encrypted or decrypted.
  • shift is the number of positions to shift each letter.
  • decrypt is a Boolean to set if text should be decrypted.

decrypt is included so that a single function can be used to handle both encryption and decryption. This implementation can handle only alphabetic characters, so the function first checks that text is an alphabetic character in the ASCII encoding:

The function then defines three variables to store the lowercase ASCII characters, the uppercase ASCII characters, and the results of the encryption or decryption:

Next, if the function is being used to decrypt text , then it multiplies shift by -1 to make it shift backward:

Finally, caesar_cipher() loops over the individual characters in text and performs the following actions for each char :

  • Check if char is lowercase or uppercase.
  • Get the index of the char in either the lowercase or uppercase ASCII lists.
  • Add a shift to this index to determine the index of the cipher character to use.
  • Use % 26 to make sure the shift will wrap back to the start of the alphabet.
  • Append the cipher character to the result string.

After the loop finishes iterating over the text value, the result is returned:

Here’s the full code again:

Now run the code in the Python REPL using the text meetMeAtOurHideOutAtTwo with a shift of 10 :

The encrypted result is woodWoKdYebRsnoYedKdDgy . Using this encrypted text, you can run the decryption to get the original text:

The Caesar cipher is fun to play around with for an introduction to cryptography. While the Caesar cipher is rarely used on its own, it’s the basis for more complex substitution ciphers. In the next section, you’ll look at one of the Caesar cipher’s descendants, the Vigenère cipher.

Vigenère Cipher

The Vigenère cipher is a polyalphabetic substitution cipher . To perform its encryption, it employs a different Caesar cipher for each letter of the input text. The Vigenère cipher uses a keyword to determine which Caesar cipher should be used to find the cipher letter.

You can see an example of the encryption process in the following image. In this example, the input text REALPYTHON is encrypted using the keyword MODULO :

For each letter of the input text, REALPYTHON , a letter from the keyword MODULO is used to determine which Caesar cipher column should be selected. If the keyword is shorter than the input text, as is the case with MODULO , then the letters of the keyword are repeated until all letters of the input text have been encrypted.

Below is an implementation of the Vigenère cipher. As you’ll see, the modulo operator is used twice in the function:

You may have noticed that the signature for vigenere_cipher() is quite similar to caesar_cipher() from the previous section:

The main difference is that, instead of a shift parameter, vigenere_cipher() takes a key parameter, which is the keyword to be used during encryption and decryption. Another difference is the addition of text.isupper() . Based on this implementation, vigenere_cipher() can only accept input text that is all uppercase.

Like caesar_cipher() , vigenere_cipher() iterates over each letter of the input text to encrypt or decrypt it:

In the above code, you can see the function’s first use of the modulo operator:

Here, the current_key value is determined based on an index returned from i % len(key) . This index is used to select a letter from the key string, such as M from MODULO .

The modulo operator allows you to use any length keyword regardless of the length of the text to be encrypted. Once the index i , the index of the character currently being encrypted, equals the length of the keyword, it will start over from the beginning of the keyword.

For each letter of the input text, several steps determine how to encrypt or decrypt it:

  • Determine the char_index based on the index of char inside uppercase .
  • Determine the key_index based on the index of current_key inside uppercase .
  • Use char_index and key_index to get the index for the encrypted or decrypted character.

Take a look at these steps in the code below:

You can see that the indices for decryption and encryption are calculated differently. That’s why decrypt is used in this function. This way, you can use the function for both encryption and decryption.

After the index is determined, you find the function’s second use of the modulo operator:

index % 26 ensures that the index of the character doesn’t exceed 25 , thus making sure it stays inside the alphabet. With this index, the encrypted or decrypted character is selected from uppercase and appended to results .

Here’s the full code the Vigenère cipher again:

Now go ahead and run it in the Python REPL:

Nice! You now have a working Vigenère cipher for encrypting text strings.

Python Modulo Operator Advanced Uses

In this final section, you’ll take your modulo operator knowledge to the next level by using it with decimal.Decimal . You’ll also look at how you can add .__mod__() to your custom classes so they can be used with the modulo operator.

Earlier in this tutorial, you saw how you can use the modulo operator with numeric types like int and float as well as with math.fmod() . You can also use the modulo operator with Decimal from the decimal module. You use decimal.Decimal when you want discrete control of the precision of floating-point arithmetic operations.

Here are some examples of using whole integers with decimal.Decimal and the modulo operator:

Here are some floating-point numbers used with decimal.Decimal and the modulo operator:

All modulo operations with decimal.Decimal return the same results as other numeric types, except when one of the operands is negative. Unlike int and float , but like math.fmod() , decimal.Decimal uses the sign of the dividend for the results.

Take a look at the examples below comparing the results of using the modulo operator with standard int and float values and with decimal.Decimal :

Compared with math.fmod() , decimal.Decimal will have the same sign, but the precision will be different:

As you can see from the above examples, working with decimal.Decimal and the modulo operator is similar to working with other numeric types. You just need to keep in mind how it determines the sign of the result when working with a negative operand.

In the next section, you’ll look at how you can override the modulo operator in your classes to customize its behavior.

The Python data model allows to you override the built-in methods in a Python object to customize its behavior. In this section, you’ll look at how to override .__mod__() so that you can use the modulo operator with your own classes.

For this example, you’ll be working with a Student class. This class will track the amount of time a student has studied. Here’s the initial Student class:

The Student class is initialized with a name parameter and starts with an empty list, study_sessions , which will hold a list of integers representing minutes studied per session. There’s also .add_study_sessions() , which takes a sessions parameter that should be a list of study sessions to add to study_sessions .

Now, if you remember from the converting units section above, convert_minutes_to_day() used the Python modulo operator to convert total_mins into days, hours, and minutes. You’ll now implement a modified version of that method to see how you can use your custom class with the modulo operator:

You can use this function with the Student class to display the total hours a Student has studied. Combined with the Student class above, the code will look like this:

If you load this module in the Python REPL, then you can use it like this:

The above code prints out the total hours jane studied. This version of the code works, but it requires the extra step of summing study_sessions to get total_mins before calling total_study_time_in_hours() .

Here’s how you can modify the Student class to simplify the code:

By overriding .__mod__() and .__floordiv__() , you can use a Student instance with the modulo operator. Calculating the sum() of study_sessions is included in the Student class as well.

With these modifications, you can use a Student instance directly in total_study_time_in_hours() . As total_mins is no longer needed, you can remove it:

Here’s the full code after modifications:

Now, calling the code in the Python REPL, you can see it’s much more succinct:

By overriding .__mod__() , you allow your custom classes to behave more like Python’s built-in numeric types.

At first glance, the Python modulo operator may not grab your attention. Yet, as you’ve seen, there’s so much to this humble operator. From checking for even numbers to encrypting text with ciphers, you’ve seen many different uses for the modulo operator.

In this tutorial, you’ve learned how to:

  • Use the modulo operator with int , float , math.fmod() , divmod() , and decimal.Decimal
  • Calculate the results of a modulo operation
  • Solve real-world problems using the modulo operator
  • Override .__mod__() in your own classes to use them with the modulo operator

With the knowledge you’ve gained in this tutorial, you can now start using the modulo operator in your own code with great success. Happy Pythoning!

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

About Jason Van Schooneveld

Jason Van Schooneveld

Jason is a software developer based in Taipei. When he's not tinkering with electronics or building Django web apps, you can find him hiking the mountains of Taiwan or brushing up on his Chinese.

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Aldren Santos

Master Real-World Python Skills With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

What Do You Think?

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal . Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session . Happy Pythoning!

Keep Learning

Related Topics: basics python

Recommended Video Course: Python Modulo: Using the % Operator

Related Tutorials:

  • How to Round Numbers in Python
  • Python's F-String for String Interpolation and Formatting
  • Python enumerate(): Simplify Loops That Need Counters
  • How to Iterate Through a Dictionary in Python
  • Dictionaries in Python

Keep reading Real Python by creating a free account or signing in:

Already have an account? Sign-In

Almost there! Complete this form and click the button below to gain instant access:

Python Logo

Get the Python Cheat Sheet (Free PDF)

🔒 No spam. We take your privacy seriously.

digit 9 in python assignment expert

  • How it works
  • Homework answers

Physics help

Answer to Question #224589 in Python for Hari nadh babu

Armstrong numbers between two intervals

This Program name is Armstrong numbers between two intervals. Write a Python program to Armstrong numbers between two intervals, it has two test cases

The below link contains Armstrong numbers between two intervals question, explanation and test cases

https://drive.google.com/file/d/1nMwnGgwxLey1JhQEaQ_x-goS5_1DyVdL/view?usp=sharing

We need exact output when the code was run

digit 9 in python assignment expert

Need a fast expert's response?

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS !

Leave a comment

Ask your question, related questions.

  • 1. PyramidThis Program name is Pyramid. Write a Python program to Pyramid, it has two test casesThe bel
  • 2. Digit 9This Program name is Digit 9. Write a Python program to Digit 9, it has two test casesThe bel
  • 3. X = int(input()) N = int(input()) M = 1 + 2*(N-1) list1 = [] i = 1 j = 0 k = 0 while i <= M:  li
  • 4. write a program to print the index of the last occurence of the given number N in the list
  • 5. given an array of n integers find and print all the unique triplets
  • 6. Consider the following function fpp.def foo(m): if m == 0: return(0) else: retu
  • 7. Add two polynomialsGiven two polynomials A and B, write a program that adds the given two polynomial
  • Programming
  • Engineering

10 years of AssignmentExpert

Who Can Help Me with My Assignment

There are three certainties in this world: Death, Taxes and Homework Assignments. No matter where you study, and no matter…

How to finish assignment

How to Finish Assignments When You Can’t

Crunch time is coming, deadlines need to be met, essays need to be submitted, and tests should be studied for.…

Math Exams Study

How to Effectively Study for a Math Test

Numbers and figures are an essential part of our world, necessary for almost everything we do every day. As important…

IMAGES

  1. Print Digit 9 In Python

    digit 9 in python assignment expert

  2. Digit 9 Pattern

    digit 9 in python assignment expert

  3. Digit 9

    digit 9 in python assignment expert

  4. First And Last Digits In Python

    digit 9 in python assignment expert

  5. Single Digit Number In Python

    digit 9 in python assignment expert

  6. Assignment Operators Python

    digit 9 in python assignment expert

VIDEO

  1. Data Analytics with Python Week 11 Assignment Answers

  2. Python Week 9 Graded Assignment Solution // IITM BS Online Degree Program || Foundation

  3. 2.5. Operators in Python

  4. Python Basics: Assignment Operators (Continuation)

  5. pattern of digit '3'

  6. "Mastering Assignment Operators in Python: A Comprehensive Guide"

COMMENTS

  1. Answer to Question #224587 in Python for Hari nadh babu

    Digit 9. This Program name is Digit 9. Write a Python program to Digit 9, it has two test cases. The below link contains Digit 9 question, explanation and test cases

  2. Answer to Question #223542 in Python for Anand

    Digit 9. You are given . N as input. Write a program to print the pattern of 2*N - 1 rows using an asterisk(*) as shown below.Note: There is a space after each asterisk * character.Input. The first line of input is an integer . N.Explanation. In the given example, N = 4.So, the output should be

  3. Answer to Question #233113 in Python for kaavya

    Python. Question #233113. Digit 9. You are given N as input. Write a program to print the pattern of 2*N - 1 rows using an asterisk (*) as shown below. Note: There is a space after each asterisk * character. Input. The first line of input is an integer N. Explanation.

  4. Digit 9 Pattern

    Digit 9 Pattern | Python Program to Print Digit 9 | CCBP Coding Assignment 15 Question | Patterns#ccbp #pythonpattern #codingpractice #assignment #coding #py...

  5. Print Digit 9 In Python

    Code to print digit 9 in Python is: CopyAssignment. We are Python language experts, a community to solve Python problems, we are a 1.2 Million community on Instagram, now here to help with our blogs.

  6. Digit 9

    Our Teligram group Link 🔗https://t.me/shivatechcareerhub Instagram id : https://instagram.com/mr_chiva?igshid=YmMyMTA2M2Y=Cal me on Calme4 app:id: shivapra...

  7. 10 Number Pattern in Python (with Code)

    Let us see some examples of number patterns in python. The above image shows some of the number patterns that you can create in python. Apart from these, there are many more number patterns that you can think of and create. Print numbers from 0 to 9. Before we start creating number patterns, let us first see how to print numbers from 0 to 9.

  8. python

    def contains_digit(s): isdigit = str.isdigit return any(map(isdigit,s)) in python 3 it's probably the fastest there (except maybe for regexes) is because it doesn't contain any loop (and aliasing the function avoids looking it up in str). Don't use that in python 2 as map returns a list, which breaks any short-circuiting

  9. Python Program to Print 8 Star Pattern

    Write a Python program to print 8 star pattern using the for loop, while loop, functions, and multiple if else statements with an example.

  10. 3 Savvy Ways To Digit 9 Pattern In Python Assignment Expert

    3 Savvy Ways To Digit 9 Pattern In Python Assignment Expert. travis 5 days ago 0 6 mins. 3 Savvy Ways To Digit 9 Pattern In Python Assignment Expert Mark N. Davies 1 7 I've seen the two techniques before in separate demos. But, I won't break them up in any further detail here. (Because I've changed the wording somewhat since the first I ...

  11. Regular Expressions: Regexes in Python (Part 1)

    In this tutorial, you'll explore regular expressions, also known as regexes, in Python. A regex is a special sequence of characters that defines a pattern for complex string-matching functionality. Earlier in this series, in the tutorial Strings and Character Data in Python, you learned how to define and manipulate string objects.

  12. 2 Easy Ways to Extract Digits from a Python String

    1. Making use of isdigit () function to extract digits from a Python string. Python provides us with string.isdigit() to check for the presence of digits in a string. Python isdigit () function returns True if the input string contains digit characters in it. Syntax: We need not pass any parameter to it.

  13. Answer to Question #224603 in Python for kaavya

    Write a Python program to W pattern with *, i; 3. Armstrong numbers between two intervalsThis Program name is Armstrong numbers between two intervals. 4. PyramidThis Program name is Pyramid. Write a Python program to Pyramid, it has two test casesThe bel; 5. Digit 9This Program name is Digit 9. Write a Python program to Digit 9, it has two test ...

  14. Python

    We can define the digit type requirement, using "\D", and only digits are extracted from the string. Method 3: Using loops: This task is done by using for loop. Method 4: Using recursion: Method 5: Using ord () method. Method 6 : Using isnumeric () method. Approach.

  15. Answer to Question #224590 in Python for Hari nadh babu

    W pattern with * This Program name is W pattern with *. Write a Python program to W pattern with *, it has two test cases. The below link contains W pattern with * question, explanation and test cases

  16. Variables in Python

    In Python, variables need not be declared or defined in advance, as is the case in many other programming languages. To create a variable, you just assign it a value and then start using it. Assignment is done with a single equals sign (=): Python. >>> n = 300. This is read or interpreted as " n is assigned the value 300.".

  17. First and Last Digits in Python

    In First and Last Digits in Python, we are given two positive numbers, we need to find the count of those numbers which have the same first and last digit. Also, if the number is below 10 it will also be counted.

  18. python

    I think the challenge you're facing is how to get the separate digits from a two digit integer. It is possible to do using mathematical operators. Just think about what each digit in a number like 42 represents. The 4 is the "tens" digit and the 2 is the "ones" digit. It might help to think about it in reverse.

  19. Single Digit Number in Python

    In this Single Digit Number in Python problem, we are given a number, we need to add its digits, and we need to repeat this until the addition results in a single digit. At last, we need to print the result. For example, 78=> 7+8=>15=>1+5=>6.

  20. Python Modulo in Practice: How to Use the % Operator

    The official Python docs suggest using math.fmod() over the Python modulo operator when working with float values because of the way math.fmod() calculates the result of the modulo operation. If you're using a negative operand, then you may see different results between math.fmod(x, y) and x % y.You'll explore using the modulo operator with negative operands in more detail in the next section.

  21. Answer to Question #224589 in Python for Hari nadh babu

    Armstrong numbers between two intervals. This Program name is Armstrong numbers between two intervals. Write a Python program to Armstrong numbers between two intervals, it has two test cases