Movatterモバイル変換


[0]ホーム

URL:


Loading video player…

Python Modulo: Using the % Operator (Overview)

Python supports a wide range ofarithmetic operators that you can use when working withnumbers in your code. One of these operators is themodulo operator (%), which returns the remainder of dividing two numbers. Modular operations are useful to check if a number is even or odd, simplifying cycling through data, and doing non-decimal based units conversion.

In this course, you’ll learn:

  • Howmodulo works in mathematics
  • How to use the Python modulo operator with differentnumeric types
  • How Python calculates the results of amodulo operation
  • How to override.__mod__() in your classes to use them with the modulo operator
  • How to use the Python modulo operator to solvereal-world problems

The code in this course was tested with Python 3.9.0,% has not change much and older versions should be compatible.

Download

Sample Code (.zip)

2.4 KB
Download

Course Slides (.pdf)

696.4 KB

00:00Welcome to Python Modulo in Practice, or How to Use the% Operator.My name is Chris and I will be your guide. In this course,you’ll learn about modular arithmetic,how to use the percent operator (%) withint andfloat types,common coding uses of the% operator, and how to use% with customclasses.

00:22Python’s% operator’s been around for a long time.The code I’m going to show you has all been tested using Python 3.9,but you should be able to use it in pretty much any version of Python.

00:34So, what’s it for? Well, the% operator does modular arithmetic.That means getting the remainder portion of doing some division.For example, 14 divided by 4 is 3 remainder 2.

00:483 times 12 is 12,and there’s 2 leftover. 14 mod 4 returns 2, the remainder from the division.Python’s operator for that mod operation is percent (%). Modulus pops up in a bunchof places inside of your code.

01:03Some common uses are detecting even versus odd numbers,looping on cycles of data, doing unit conversion—for example,if you want to take a large number of inches and turn it into feet and inchesif you’re using the American Imperial system.

01:19Or, if you want to take a large number of minutes and turn it into hours andminutes, you’ll need the modulus operation.

01:26Everything in Python is an object,so you can take advantage of this and write your own objects that support the% operator. You do this by overriding.__mod__().

01:36I’ll show you how to do this later on in the course.

01:39Next up, an introduction to modular arithmetic.

Become a Member to join the conversation.

Course Contents

Overview
16%

[8]ページ先頭

©2009-2026 Movatter.jp