0% found this document useful (0 votes)
21 views

Python Programming - 4

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Python Programming - 4

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

CE4950

Applied Machine Learning & Artificial


Intelligence in Civil Engineering
Sachini S. Madushani
Python Programming
Functions

2/28/2024 Python Programming 3


The need of a Function
• What if we need to perform a specific task, several times in different parts of a program?

Task Are you going to write the similar block of code


again and again??

Similar Use a function – Define it and call


task

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

2/28/2024 Python Programming 5


Introduction
• In previous lessons of this course, you have been introduced to some
of the built-in functions provided by Python.
Built in • In these built-in functions, the code that accomplishes the task is
Functions abstracted out from you and you only need to know the function
arguments and the values it's returning, whenever you are going to
call it.

• 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.

2/28/2024 Python Programming 7


Calling a function
• <arguments> are the values that are passed into the function when it is called.
• They correspond to the <parameters> in the particular function definition.

2/28/2024 Python Programming 8


Empty Functions
• Sometimes you may need to define a function with an empty body, one that does nothing.
• This is usually to act as a placeholder until the function is implemented at a later level.
• Anyhow, when you define empty functions, you must use the pass statement.

2/28/2024 Python Programming 9


Passing Arguments
• Most of the functions you will be defining needs data being passed into it, in the form of
parameters. In Python there are varied ways of function invocation.
• Positional Arguments
• Keyword Arguments
• Default Parameters
• Arbitrary Arguments

2/28/2024 Python Programming 10


Passing Arguments – Positional Arguments
• Positional Arguments are the most common and straightforward method of passing
arguments to function. During the definition of the function you also specify the list of
parameters that the function accepts, within parenthesis.
• What you should keep in mind is that with positional arguments, the arguments you pass in
the function call and the parameters defined in the function should match in order and
number.
• Although positional arguments are the most straightforward way to pass data to a function,
you are not allowed to leave any out, or specify extra ones when calling the function.

2/28/2024 Python Programming 11


Passing Arguments – Positional Arguments

2/28/2024 Python Programming 12


Passing Arguments – Keyword Arguments
• Here, you can specify the passed arguments with the keyword which is provided as the
parameter and the value is the actual parameter value you want to pass to the function.
• The specialty with Keyword arguments use is that you don’t need to worry about the
argument order like you did previously.
• As each argument you pass is specified with the parameter/Keyword name Python can
identify the values even though the order is messed up.
• However, here too, the number of arguments should be equal to what is defined in the
function.

2/28/2024 Python Programming 13


Passing Arguments – Keyword Arguments

2/28/2024 Python Programming 14


Passing Arguments – Default Parameters
• In Functions defined with default parameters, if no argument is passed during the function
call, a predefined default parameter is passed as the value for the function.

Default Parameter

2/28/2024 Python Programming 15


Passing Arguments – Arbitrary Arguments
• In some function definitions, you will not know the exact number of arguments that need to
be passed to the function during its call.
• In such situations you can use the *args syntax with the function definition.

2/28/2024 Python Programming 16


The ‘return’ Statement
• A return statement in a Python function can serve either terminate the function
immediately and pass the control of execution back to the caller or pass any required data
back to the function caller.
• In the first situation we just include the return statement but whenever we are returning a
specific value/s from the function, we need to mention that together with the return
statement and these returned values can be captured by another function or a variable as the
program prefers.
• A Python function can return any type of object.
• Python allows returning multiple values, separated by commas and they are actually
returned as a tuple.

2/28/2024 Python Programming 17


The ‘return’ Statement – Example

2/28/2024 Python Programming 18


Docstrings
• The Docstrings are supposed to provide detailed documentation for a function.
• It can be composed of the function’s purpose, its list of arguments, its return values and any
other information that the programmer thinks important to mention.
• A docstring is added as the first statement in the body of a Python function.
• These need to be within quotation marks and the recommended convention to use the
triple-quotes.
• These can be on a single line or be multi lined as well.
• We can also view the docstrings of built-in and user defined functions using the __doc___
attribute.
• Docstrings seem to be similar to the commenting. But the difference is that comments are
not accessible for viewing during the program execution. And the purpose docstrings serve is
different, they are in fact a more useful way of commenting.
2/28/2024 Python Programming 19
Docstrings – Example

2/28/2024 Python Programming 20


Exercise 1
• Define a function to calculate the second moment of inertia of rectangular beams.

2/28/2024 Python Programming 21


Exercise 2
• Define a function to calculate circumference and area of a circle.

2/28/2024 Python Programming 22


Errors

2/28/2024 Python Programming 23


Introduction

Syntax Errors Runtime errors Logical errors

• 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.

2/28/2024 Python Programming 24


Syntax Error
• Occurs due to the mistakes done in using the programming language.

2/28/2024 Python Programming 25


Runtime Error
• Runtime errors occur whenever syntactically correct Python code results in errors at the
run-time. An error message will be shown in order to indicate what is wrong with the code.
• It is important to know that whenever a runtime error occurs and if it is not handled
properly, the Python program will be terminated after that point of error.
• There are many types of runtime errors in Python.
a) Name Error
b) Index Error
c) Type Error
d) Value Error
e) Import Error

2/28/2024 Python Programming 26


Runtime Error – Name Error
• A ‘Name Error’ occurs when you try to refer a variable that has not been defined in the
code.

2/28/2024 Python Programming 27


Runtime Error – Index Error
• An ‘Index Error’ occurs when you try to access a value from a sequence, but the referenced
index is out of range.

2/28/2024 Python Programming 28


Runtime Error – Type Error
• A ‘Type Error’ occurs when you try to perform an operation on objects of inappropriate
type.

2/28/2024 Python Programming 29


Runtime Error – Value Error
• A ‘Value Error’ occurs when a built-in operation or function receives an argument that has
the right type but an invalid value.

2/28/2024 Python Programming 30


Runtime Error – Import/Module Not Found Error
• An ‘Import Error’ could occur if you try to import something that does not exist from an
existing module or if something is wrong with the import statement.

2/28/2024 Python Programming 31


Handling Runtime Errors
• When a runtime error occurs, the program will stop immediately if the error was not
handled properly.
• Therefore, it is necessary to plan carefully to catch any possible errors during runtime and
handle runtime errors to ensure an uninterrupted execution of the program.

2/28/2024 Python Programming 32


The try/except Structure
• The try/except structure helps to handle possible runtime errors. This structure will not
prevent the errors, instead it creates a safe passage for the program in the case of runtime
error.
• Basically, two blocks (try and except) can be identified in this structure. We can put the so
called ‘dangerous code’ into the try block. That means you are anticipating an error in that
section of the code. In the case where the error actually occurs, the program jumps to the
except block and executes what’s inside that block and moves on with the program.
• Notice that, if this error handling structure is not used, the program will terminate as soon
as the error occurs.

2/28/2024 Python Programming 33


The try/except Structure – Example

2/28/2024 Python Programming 34


Logical Error
• Logical errors would not generate any error messages, but they would result in unexpected
or erroneous output.
• Examples –
• Misuse of parentheses
• Use of infinite loops
• Use of incorrect logical conditions (using ‘or’ instead of ‘and’)

2/28/2024 Python Programming 35

You might also like