May 20, 2024

Wiki

Python

Aide

edit SideBar

Search

Some predefined methods


Number manipulation

The methods

Division, modulo (of integers)

Let $x$ and $y$ be two integers.

$x/y$
An entire division of $x$ by $y$, i.e. the quotient of this division.
  >>> 7/3
  2
Indeed, the quotient of the division of 7 by 3 is 2: to obtain a real division, one of the terms must be a float; to do so, one can add a point to one of the integers, or use the float method:
  >>> 7./3
  2.3333333333333335
  >>> float(7)/3
  2.3333333333333335
$x%y$
"$x$ modulo $y$", which is the rest of the entire division of $x$ by $y$ :
  >>> 7%3
1
since the rest of the division of 7 by 3 is equal to 1 ($7 = 3 \times 2 + 1$). In mathematics, we would be more likely to note this: $7 \equiv 1[3]$.
divmod(number1,number2)
Returns the entire division pair followed by modulo.
  >>> divmod(7,3)
(2, 1)
  >>> x=divmod(7,3)
  >>> x[0]
  2
  >>> x[1] 
  1

Power ratings

x**y
Returns $x^y$.
pow(x,y)
Calculates efficiently $x^y$.
pow(x,y,z)
Calculates efficiently $x^y%z$.

The interest of this last method is found in the encryption RSA, for example.

Comparisons

cmp(number1,number2)
Refers to -1, 0 or 1, depending on whether the first number is strictly inferior, equal or strictly superior to the second.
max(sequence)
Returns the maximum of the sequence passed as an argument.
  >>> max([1,3,5,5,2])
5
min(sequence)
Returns the minimum of the sequence passed as an argument.

Change of base

int(number,base)
For example,
  >>> int('110',2)
  6
since 110 in base 2 gives 6 in base 10.
bin(number)
Binary value of a decimal point.
  >>> bin(14)
  '0b1110'

The return is a string beginning with 0b. To obtain only the bits, we can take a slice of the string:

  >>> bin(14)[2:]
  '1110'

It can also be completed on the left with zeros, for example to code 14 on 8 bits, using the zfill method.

  >>> bin(14)[2:].zfill(8)
  '00001110'
hex(number)
Returns the hexadecimal form (as a string) of the number passed as an argument.
Oct(number)
Returns the octal shape (as a string) of the number passed as an argument.

Type conversion

int(number)
Truncate the decimal part of the number (it's not exactly our integer part).
  >>> int(3.14)
  3
long(object)
Transforms an integer into a "long integer". Note that the conversion is automatic if necessary:
  >>> for k in range(15):
... print 13**k, type (13**k)
  ... 
  1 <type'int'>
  13 <type'int'>
  169 <type'int'>
  2197 <type'int'>
  28561 <type'int'>
  371293 <type'int'>
  4826809 <type'int'>
  62748517 <type'int'>
  815730721 <type'int'>
  10604499373 <type'long'>
  137858491849 <type'long'>
  1792160394037 <type'long'>
  23298085122481 <type'long'>
  302875106592253 <type'long' >
  3937376385699289 <type'long'>
Integers can be as large as you want, and will not be approached: however, you are limited by the size of the memory. In most other languages, there is a maximum integer beyond which calculation is approximated (a library of large numbers should be installed, if necessary): we will appreciate this advantage for instance in arithmetic, cryptography, etc.
In the third version of python, these two types of integers have been merged.
float(object)
Transforms the object (a character or an integer) into a float.
complex ($nb_a$,$nb_b$)
Returns a complex type object, equal to $nb_a+nb_b*1j$ where $1j$ is the pure imaginary.
  >>> complex(2,3)
(2+3j)
  >>> complex(2,3)+complex(4,-1)
  (6+2j)
  >>> complex(0.1)**2
  (-1+0j)
abs(number)
Returns the absolute value (or the module, if we are dealing with a complex) of the number.

Character string evaluation

eval(string)
Evaluate the mathematical expression (string). For example,
  >>> eval('2+3*(4-1)')
  11

Practical work

  1. Test all these methods in an interactive python.
  2. Let's say "q" the quotient of the division of 1234 by 56, and "r" its remainder. Check that 1234 = 56*q+r (using the entire division, and the modulo).
  3. Calculate the sum of the multiples from 7 to 7777, using the modulo, the if, and a loop (We can proceed differently, but the goal is to practice using the modulo.)
  4. Ask the user to enter an algebraic expression, such as 7*3+4, or 2**3+4**2+1, and return the result.

Other primitive Python

We end this short presentation of Python by listing some useful primitives.

Constants

Some python constants:

pi
The constant $\pi$.
True
The true Boolean.
False
The false Boolean.
e
exp(1).

Operators

Python operators:

x == y
Tests the (Boolean) equality between x and y.
x != y
Test if x is different from y.
x >= y
Tests whether x is greater than or equal to y.
x or y
The Boolean or.
x and y
The Boolean and.

Character manipulation

chr(number)
Returns the character that admits number for ascii code.
cmp(character1,character2)
Returns -1, 0 or 1, depending on whether the first character is strictly before, equal to or strictly after the second (in the ascii table).
len(object)
Returns the length of the string, or more generally of the object passed as an argument.
ord(object)
Returns the rank of a character (in the ascii table).
str(object)
Converts the object into a string of characters.

Lists, sequences

map(function,sequence)
Applies the function to all elements of the sequence.
  >>> map(abs,[-2,1.5,7,-3.7])
[2, 1.5, 7, 3.7000000000000002]
range(n)
Returns the list of integers from $0$ to $n-1$.
range(a,b)
Returns the list of integers from $a$ to $b-1$.
range(a,b,c)
Returns the list of integers from $a$ to $b-1$, with a $c$ step.
sum(list)
Returns the sum of the numbers in the list.

Miscellaneous

help(name)
As its name suggests. For example, to get help on the abs method:
  >>> help(abs)
abs(...)
    abs(number) -> number

    Return the absolute value of the argument.
isinstance(object,type)
For example,
  >>> isinstance('test', int)
returns False, since the string test is not an instance of the class int (it is not an integer).
type(object)
Returns the type of the object.

Practical work

  • Perform offset encryption: if the user enters azerty, encrypt it in bafsuz (you shift a letter in the alphabet). We'll be careful that after z, it's a.
  • We can already assume that only lower-case letters can be entered, then lower-case and upper-case letters can be entered, and all characters can be admitted.
  • In addition, ask the user to specify by how many letters he wants his offset.

Some additions

Multiple assignments

In Python, we can make assignments to several variables:

  • in "series"
  >>> x = y = 7
  • in "parallel" mode
  >>> x, y = 7, 8

The python math module

Python modules

Python has modules that can do just about anything.

  • The official modules are documented on the official website, here
  • The modules made by the average person are centralized on the Python package index (Pypi)
  • On this wiki, we detail some of these modules here.

Example of use of the math module

The math module has most of the basic functionalities expected for a mathematics library: trigonometric functions, square root, mathematical constants, etc.

There are at least 3 ways to import these functions. In the first one, we import the whole math module:

  >>> import math
  >>> print math.pi
  >>> print math.sin(2*math.pi)

The advantage of this approach is that we always know which method or constant is called: here, the sin method of the math module. The disadvantage is that you always have to type the name of the module.

The second way is to immediately import all the content of the module, as follows:

  >>> from math import *
  >>> print pi
  >>> print sin(2*pi)

The advantage is the brevity of this approach. The disadvantages are multiple:

  • When you see an exotic function appear in the middle of a big program, you don't see where it comes from. If it has to be debugged, that is a problem.
  • If you have created a toto function, and a module you import contains a toto function, which toto function is ultimately used?
  • The modules scipy, sympy, numpy and math all have a sin function. You cannot know which one you are using by making such an import.

The last way to import is perhaps the best compromise:

  >>> from math import pi, sin
  >>> print pi
  >>> print sin(2*pi)

We can get the details of the math module:

  • either by consulting the link math of the official modules
  • or on the command line:
  >>> import math
>>> help(math)

or for a specific function:

  >>> from math import sin
  >>> help(sin)

Practical work

  1. Make a program that asks the user to enter a radius, and returns the perimeter and area of the associated disk
  2. Browse the documentation of the official modules, and the pypi
  3. Discover the modules documented on this wiki, test them.

Page Actions

Recent Changes

Group & Page

Back Links