1 Syntax of a function

The Python syntax for defining a function is as follows:

def function_name (parameter list):
      instruction block

You can choose any name for the function you are creating, except the reserved keywords of the language, and provided you do not use any special or accented characters (the underlined character "_" is allowed) . As is the case for variable names, we use lowercase letters, especially at the beginning of the name (names that start with a capital letter will be reserved for classes).

2 Body of the function

Like the if, for, and while statements, the def statement is a compound statement. The line containing this instruction ends obligatorily with a colon:, which introduces a block of instructions which is specified thanks to the indentation. This instruction block is the body of the function.

Example

>>> def message ():
return "Hello!"

>>> message ()
'Hello !'

Function with parameters

Example

>>> def mult (x):
return 2 * x

>>> mult (5)
10

3 - Function with several parameters

With Python you can also define functions with several parameters

Example

>>> def sum (x, y):
return x + y

>>> sum (5,7)
12

Younes Derfoufi CRMEF OUJDA

Leave a Reply