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:

leftovers = 10 % 3
print(leftovers)

Output:

1

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:

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

Example usage:

print(is_leap(2000))  # --> True
print(is_leap(1900))  # --> False
print(is_leap(2016))  # --> True

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:

>>> name = "Alice"
>>> "Hello %s" % name
'Hello Alice'

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:

>>> age = 20
>>> "I am %d years old." % age
'I am 20 years old.'

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

>>> age = 1000
>>> "I am 0x%x years old." % age
'I am 0x3e8 years old.'

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+:

>>> age = 30
>>> "I am {} years old".format(age)
I am 30 years old

A formatted string example in Python 3.6+:

>>> age = 30
>>> f"I am {age} years old"
I am 30 years old

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:

In [1]: %pwd
Out[1]: 'C:\\User\\Artturi'

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.

For example:

In [1]: %lsmagic
Out[1]: 
Available line magics:
%alias  %alias_magic  %autoawait  %autocall  %autoindent  %automagic  %bookmark
  %cat  %cd  %clear  %colors  %conda  %config  %cp  %cpaste  %debug  %dhist  %d
irs  %doctest_mode  %ed  %edit  %env  %gui  %hist  %history  %killbgscripts  %l
dir  %less  %lf  %lk  %ll  %load  %load_ext  %loadpy  %logoff  %logon  %logstar
t  %logstate  %logstop  %ls  %lsmagic  %lx  %macro  %magic  %man  %matplotlib  
%mkdir  %more  %mv  %notebook  %page  %paste  %pastebin  %pdb  %pdef  %pdoc  %p
file  %pinfo  %pinfo2  %pip  %popd  %pprint  %precision  %prun  %psearch  %psou
rce  %pushd  %pwd  %pycat  %pylab  %quickref  %recall  %rehashx  %reload_ext  %
rep  %rerun  %reset  %reset_selective  %rm  %rmdir  %run  %save  %sc  %set_env 
 %store  %sx  %system  %tb  %time  %timeit  %unalias  %unload_ext  %who  %who_l
s  %whos  %xdel  %xmode

Available cell magics:
%%!  %%HTML  %%SVG  %%bash  %%capture  %%debug  %%file  %%html  %%javascript  %
%js  %%latex  %%markdown  %%perl  %%prun  %%pypy  %%python  %%python2  %%python
3  %%ruby  %%script  %%sh  %%svg  %%sx  %%system  %%time  %%timeit  %%writefile
Automagic is ON, % prefix IS NOT needed for line magics.

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:

In [11]: %autocall?
Docstring:
Make functions callable without having to type parentheses.
Usage:
   %autocall [mode]
The mode can be one of: 0->Off, 1->Smart, 2->Full.  If not given, the
value is toggled on and off (remembering the previous state).
In more detail, these values mean:
0 -> fully disabled
1 -> active, but do not apply if there are no arguments on the line.
In this mode, you get::
  In [1]: callable
  Out[1]: <built-in function callable>
  In [2]: callable 'hello'
  ------> callable('hello')
  Out[2]: False
2 -> Active always.  Even if no arguments are present, the callable
object is called::
  In [2]: float
  ------> float()
  Out[2]: 0.0
Note that even with autocall off, you can still use '/' at the start of
a line to treat the first argument on the command line as a function
and add parentheses to it::
  In [8]: /str 43
  ------> str(43)
  Out[8]: '43'
# all-random (note for auto-testing)
File:      /usr/local/lib/python3.9/site-packages/IPython/core/magics/auto.py

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

In [1]: %%ruby?
    ...: 
    ...: 
Docstring:
%%ruby script magic
Run cells with ruby in a subprocess.
This is a shortcut for `%%script ruby`
File:      /usr/local/lib/python3.9/site-packages/IPython/core/magics/script.py

Conclusion

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

  1. Calculating modulos.
  2. Old-school string formatting.
  3. Magic commands in IPython shell.

Thanks for reading.

Happy coding!

Further Reading

10 Jupyter Notebook Tricks

50 Python Interview Questions

Resources

https://docs.python.org/3/

Leave a Comment

Your email address will not be published. Required fields are marked *