Python Programming - 4
Python Programming - 4
Similar
task
2/28/2024 Python Programming 4
Introduction
• In programming, a function is a self-contained block of code that executes a specific task or
related group of tasks.
• They run only when specifically called within the program.
• The prime advantage of functions is the code re-usability and manageability.
• There are two kinds of functions in Python.
➢ Built-in functions – that are provided as part of Python - print(), input(), type(), float(),
int() ...
➢ User-defined functions – that we define ourselves and then use
• You can define your own functions to manage and reuse the lines of
User Defined code you may need within the program.
Functions • We treat function names as “new” reserved words (we avoid them
as variable names)
2/28/2024 Python Programming 6
Defining a function
• def is the keyword that can be used to inform Python of the new function.
• Function name is the identifier, and this should also follow the naming conventions based
on variables.
• The component named <parameter/s> is optional. It is there we provide the parameters to
be passed to the function, if any are needed.
• The indented <statement/s> compose the function body defining the functionality (We
include the statements we need executed when the function is called).
• The body of every function starts with a colon and is indented.
Default Parameter
• Syntax errors are the • Runtime errors occur • Logical errors would not
mistakes in using the when a script or a generate any error
programming language. function is executing. messages, but they
• Each programming • These are sometimes would result in
language has its own referred to as Execution unexpected or
syntax and the code time errors. erroneous output
should be written
correctly using the
correct syntax in
particular language.