Перейти к содержимому

Что значит процент в питоне

  • автор:

The Python Modulo Operator — What Does the % Symbol Mean in Python? (Solved)

The Python Modulo Operator - What Does the % Symbol Mean in Python? (Solved)

When you see the % symbol, you may think «percent». But in Python, as well as most other programming languages, it means something different.

The % symbol in Python is called the Modulo Operator. It returns the remainder of dividing the left hand operand by right hand operand. It’s used to get the remainder of a division problem.

The modulo operator is considered an arithmetic operation, along with + , — , / , * , ** , // .

The basic syntax is:

In the previous example a is divided by b , and the remainder is returned. Let’s see an example with numbers.

The result of the previous example is one. Two goes into seven three times and there is one left over.

The diagram below shows a visual representation of 7 / 2 and 7 % 2 (The «R» stands for «remainder»). The single logo on the right side (with the green arrow pointing at it) is the remainder from the division problem. It is also the answer to 7 % 2 .

image-196

Here is another example:

This will result in three. Four does not go into three any times so the original three is still left over. The diagram below shows what is happening. Remember, the modulo operator returns the remainder after performing division. The remainder is three.

image-197

Example using the Modulo Operator

One common use for the Modulo Operator is to find even or odd numbers. The code below uses the modulo operator to print all odd numbers between 0 and 10.

What is the result of % in Python?

What does the % in a calculation? I can’t seem to work out what it does.

Does it work out a percent of the calculation for example: 4 % 2 is apparently equal to 0. How?

orange's user avatar

20 Answers 20

The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the ZeroDivisionError exception. The arguments may be floating point numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4*0.7 + 0.34.) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand [2].

Example 1: 6%2 evaluates to 0 because there’s no remainder if 6 is divided by 2 ( 3 times ).

Example 2: 7%2 evaluates to 1 because there’s a remainder of 1 when 7 is divided by 2 ( 3 times ).

So to summarise that, it returns the remainder of a division operation, or 0 if there is no remainder. So 6%2 means find the remainder of 6 divided by 2.

meder omuraliev's user avatar

Somewhat off topic, the % is also used in string formatting operations like %= to substitute values into a string:

Again, off topic, but it seems to be a little documented feature which took me awhile to track down, and I thought it was related to Pythons modulo calculation for which this SO page ranks highly.

An expression like x % y evaluates to the remainder of x ÷ y — well, technically it is "modulus" instead of "reminder" so results may be different if you are comparing with other languages where % is the remainder operator. There are some subtle differences (if you are interested in the practical consequences see also "Why Python’s Integer Division Floors" bellow).

Precedence is the same as operators / (division) and * (multiplication).

  • 9 divided by 2 is equal to 4.
  • 4 times 2 is 8
  • 9 minus 8 is 1 — the remainder.

Python gotcha: depending on the Python version you are using, % is also the (deprecated) string interpolation operator, so watch out if you are coming from a language with automatic type casting (like PHP or JS) where an expression like ’12’ % 2 + 3 is legal: in Python it will result in TypeError: not all arguments converted during string formatting which probably will be pretty confusing for you.

[update for Python 3]

User n00p comments:

9/2 is 4.5 in python. You have to do integer division like so: 9//2 if you want python to tell you how many whole objects is left after division(4).

To be precise, integer division used to be the default in Python 2 (mind you, this answer is older than my boy who is already in school and at the time 2.x were mainstream):

In modern Python 9 / 2 results 4.5 indeed:

[update]

User dahiya_boy asked in the comment session:

Q. Can you please explain why -11 % 5 = 4 — dahiya_boy

This is weird, right? If you try this in JavaScript:

This is because in JavaScript % is the "remainder" operator while in Python it is the "modulus" (clock math) operator.

In Java and iOS -11 % 5 = -1 whereas in python and ruby -11 % 5 = 4 .

Well half of the reason is explained by the Paulo Scardine, and rest of the explanation is below here

In Java and iOS, % gives the remainder that means if you divide 11 % 5 gives Quotient = 2 and remainder = 1 and -11 % 5 gives Quotient = -2 and remainder = -1 .

Sample code in swift iOS.

enter image description here

But when we talk about in python its gives clock modulus. And its work with below formula

mod(-11,5) = -11 — 5 * Floor(-11/5) => -11 —

Sample code in python 3.0.

enter image description here

Why Python’s Integer Division Floors

I was asked (again) today to explain why integer division in Python returns the floor of the result instead of truncating towards zero like C.

For positive numbers, there’s no surprise:

But if one of the operands is negative, the result is floored, i.e., rounded away from zero (towards negative infinity):

This disturbs some people, but there is a good mathematical reason. The integer division operation (//) and its sibling, the modulo operation (%), go together and satisfy a nice mathematical relationship (all variables are integers):

(assuming a and b are >= 0).

If you want the relationship to extend for negative a (keeping b positive), you have two choices: if you truncate q towards zero, r will become negative, so that the invariant changes to 0 <= abs(r) < otherwise, you can floor q towards negative infinity, and the invariant remains 0 <= r < b. [update: fixed this para]

In mathematical number theory, mathematicians always prefer the latter choice (see e.g. Wikipedia). For Python, I made the same choice because there are some interesting applications of the modulo operation where the sign of a is uninteresting. Consider taking a POSIX timestamp (seconds since the start of 1970) and turning it into the time of day. Since there are 24*3600 = 86400 seconds in a day, this calculation is simply t % 86400. But if we were to express times before 1970 using negative numbers, the "truncate towards zero" rule would give a meaningless result! Using the floor rule it all works out fine.

Other applications I’ve thought of are computations of pixel positions in computer graphics. I’m sure there are more.

For negative b, by the way, everything just flips, and the invariant becomes:

So why doesn’t C do it this way? Probably the hardware didn’t do this at the time C was designed. And the hardware probably didn’t do it this way because in the oldest hardware, negative numbers were represented as "sign + magnitude" rather than the two’s complement representation used these days (at least for integers). My first computer was a Control Data mainframe and it used one’s complement for integers as well as floats. A pattern of 60 ones meant negative zero!

Tim Peters, who knows where all Python’s floating point skeletons are buried, has expressed some worry about my desire to extend these rules to floating point modulo. He’s probably right; the truncate-towards-negative-infinity rule can cause precision loss for x%1.0 when x is a very small negative number. But that’s not enough for me to break integer modulo, and // is tightly coupled to that.

PS. Note that I am using // instead of / — this is Python 3 syntax, and also allowed in Python 2 to emphasize that you know you are invoking integer division. The / operator in Python 2 is ambiguous, since it returns a different result for two integer operands than for an int and a float or two floats. But that’s a totally separate story; see PEP 238.

Posted by Guido van Rossum at 9:49 AM

Percentage Sign in Python

In Python, the % sign is commonly used in three cases:

  1. Modulo calculation. For example, 5 % 3 returns 2 .
  2. Old-school string formatting. For example, «I am %d years old» % 25 returns «I am 25 years old» .
  3. “Magic” commands in IPython shell. For example, In [2]: %recall executes the previous command.

1. Modulo in Python

The most commonly known use case for % in Python is the modulo operator.

The modulo operator calculates the remainder of a division between two integers.

For example, dividing 10 to 3 evenly is impossible. There will be one leftover. To verify this using Python, write:

This can represent for example how many slices of pizza are left over when 10 slices are shared with 3 eaters.

Practical Modulo Example: Leap Years

Definition. A leap year is a year that is evenly divisible by 4 or 400. The exception is that years divisible by 100 are not leap years (unless they are divisible by 400). For example, 2016, 2000, 1600 are leap years but 2011 and 1900 are not.

Task. Write a program that checks if a given year is a leap year.

Answer. To solve this problem, you need to figure out if a given year is divisible by 4 but not by 100 unless it’s divisible by 400.

To turn this into code, you get this kind of result:

If this answer rings no bells, here is a complete guide on how to figure out leap years in Python.

2. Old-school String Formatting with % Operator

In earlier days, Python string formatting was possible using the % operator followed by a type identifier.

For instance, let’s add a string into another string using %s:

This is positional formatting. It works such that you specify a place for a variable in a string using the % operator. Immediately after that, you specify the type of variable you want to insert.

In the above example, you embed a string into another string with the format specifier %s.

  • The percentage sign means a variable will be inserted in that position.
  • The character ‘s’ shows the type of the inserted variable is string.

In addition to embedding strings into strings, you can embed other types too. To do this, you need to use different format specifiers.

For example, to embed a number into a string, use the %d format specifier:

Or if you want to convert an integer to a string that represents a hexadecimal number, you can use the %x format specifier:

However, this formatting style is yesterday’s news.

  • In Python 2.6 and later, you can use .format() method to format strings.
  • As of Python 3.6, you can use formatted strings (F-strings) to format strings in a more elegant way.

An example of the string.format() method in Python 2.6+:

A formatted string example in Python 3.6+:

3. Magic Commands in IPython Shell

Magic commands are command-line-like commands that are available in the IPython shell.

But What Is an IPython Shell?

If you are using Jupyter Notebook you definitely know what an IPython shell is.

If you do not know what an IPython shell is, it is an interactive Python shell. It has rich features such as syntax highlighting or code completion. IPython Notebooks (these days Jupyter Notebook) is a popular web-based interactive computational environment. In this environment, you can create, run, visualize and document the code all in the same interactive shell.

Magic Commands in IPython Shell

If you are using Jupyter Notebook, you have to know about magic commands.

For example, you can get the present working directory in the IPython shell using %pwd magic command:

This works the same way as the pwd command works in a command-line window.

In IPython, there are two types of magic commands:

  1. Line magics.
  2. Cell magics.

1. Line Magics in IPython

Line magic commands are similar to command-line commands. They start with a singular % character followed by the command without arguments or parenthesis.

These line magics can be used as expressions. Their result can be stored into a Python variable.

2. Cell Magics in IPython

Cell magics operate on multiple lines below the call as opposed to line magics. To call a cell magic command, use a two % operators, %%, followed by the command name.

A cell magic command can make modifications to the input. This input does not even have to be valid in Python. The whole block is received as a string by the cell magic command.

Available Magic Commands in IPython

To get a list of all the available line magics and cell magics, use the %lsmagic command.

How to Use Magic Commands

Listing out all the possible magic commands is useful. But even more useful is knowing how to actually use them. Luckily, you do not need to start googling the magic commands up. Instead, you can use a built-in magic command to get help with any magic commands in IPython:

  • To get help on any line magic command, run %commandname?
  • To get help with a cell magic command, run %%commandname?

For example, let’s see what the line magic %autocall does:

Or let’s take a look at what the cell magic command %%ruby does:

Conclusion

The percentage operator % is used in three ways in Python:

What does %s mean in a Python format string?

The % symbol is used in Python with a large variety of data types and configurations. %s specifically is used to perform concatenation of strings together. It allows us to format a value inside a string. It is used to incorporate another string within a string. It automatically provides type conversion from value to string.

The %s operator is put where the string is to be specified. The number of values you want to append to a string should be equivalent to the number specified in parentheses after the % operator at the end of the string value.

The following Python code illustrates the way of performing string formatting.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *