UNIT-2
UNIT-2
Creating a Function
In Python a function is defined using the def keyword:
Example
def my_function():
print("Hello from a function")
Calling a Function
To call a function, use the function name followed by parenthesis:
Example
def my_function():
print("Hello from a function")
my_function()
Try it Yourself »
Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a comma.
The following example has a function with one argument (fname). When the
function is called, we pass along a first name, which is used inside the
function to print the full name:
Example
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Try it Yourself »
Arguments are often shortened to args in Python documentations.
Parameters or Arguments?
The terms parameter and argument can be used for the same thing:
information that are passed into a function.
Number of Arguments
By default, a function must be called with the correct number of arguments.
Meaning that if your function expects 2 arguments, you have to call the
function with 2 arguments, not more, and not less.
Example
This function expects 2 arguments, and gets 2 arguments:
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil", "Refsnes")
Try it Yourself »
If you try to call the function with 1 or 3 arguments, you will get an error:
Example
This function expects 2 arguments, but gets only 1:
my_function("Emil")
Try it Yourself »
This way the function will receive a tuple of arguments, and can access the
items accordingly:
Example
If the number of arguments is unknown, add a * before the parameter name:
def my_function(*kids):
print("The youngest child is " + kids[2])
Keyword Arguments
You can also send arguments with the key = value syntax.
This way the function will receive a dictionary of arguments, and can access
the items accordingly:
Example
If the number of keyword arguments is unknown, add a double ** before the
parameter name:
def my_function(**kid):
print("His last name is " + kid["lname"])
Example
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Try it Yourself »
E.g. if you send a List as an argument, it will still be a List when it reaches
the function:
Example
def my_function(food):
for x in food:
print(x)
my_function(fruits)
Try it Yourself »
Return Values
To let a function return a value, use the return statement:
Example
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
Try it Yourself »
Example
def myfunction():
pass
Try it Yourself »
Recursion
Python also accepts function recursion, which means a defined function can
call itself.
The developer should be very careful with recursion as it can be quite easy to
slip into writing a function which never terminates, or one that uses excess
amounts of memory or processor power. However, when written correctly
recursion can be a very efficient and mathematically-elegant approach to
programming.
To a new developer it can take some time to work out how exactly this
works, best way to find out is by testing and modifying it.
Example
Recursion Example
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result
Try it Yourself »
EXCEPTIONS
The try block lets you test a block of code for errors.
The finally block lets you execute code, regardless of the result of the
try- and except blocks.
Exception Handling
When an error occurs, or exception as we call it, Python will normally stop
and generate an error message.
These exceptions can be handled using the try statement:
Example
The try block will generate an exception, because x is not defined:
try:
print(x)
except:
print("An exception occurred")
Try it Yourself »
Since the try block raises an error, the except block will be executed.
Without the try block, the program will crash and raise an error:
Example
This statement will raise an error, because x is not defined:
print(x)
Try it Yourself »
Many Exceptions
You can define as many exception blocks as you want, e.g. if you want to
execute a special block of code for a special kind of error:
Example
Print one message if the try block raises a NameError and another for other
errors:
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
Try it Yourself »
ADVERTISEMENT
Else
You can use the else keyword to define a block of code to be executed if no
errors were raised:
Example
In this example, the try block does not generate any error:
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
Try it Yourself »
Finally
The finally block, if specified, will be executed regardless if the try block
raises an error or not.
Example
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
Try it Yourself »
Example
Try to open and write to a file that is not writable:
try:
f = open("demofile.txt")
try:
f.write("Lorum Ipsum")
except:
print("Something went wrong when writing to the file")
finally:
f.close()
except:
print("Something went wrong when opening the file")
Try it Yourself »
The program can continue, without leaving the file object open.
Raise an exception
As a Python developer you can choose to throw an exception if a condition
occurs.
Example
Raise an error and stop the program if x is lower than 0:
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
Try it Yourself »
You can define what kind of error to raise, and the text to print to the user.
Example
Raise a TypeError if x is not an integer:
x = "hello"
KeyboardInterrupt Raised when the user hits the interrupt key ( Ctrl+C or Delete ).
OverflowError Raised when the result of an arithmetic operation is too large to be represented.
Raised when a weak reference proxy is used to access a garbage collected
ReferenceError
referent.
RuntimeError Raised when an error does not fall under any other category.
ValueError Raised when a function gets an argument of correct type but improper value.
ZeroDivisionError Raised when the second operand of division or modulo operation is zero.
If required, we can also define our own exceptions in Python. To learn
more about them, visit Python User-defined Exceptions.
We can handle these built-in and user-defined exceptions in Python
using try , except and finally statements. To learn more about them,
visit Python try, except and finally statements.
The try block lets you test a block of code for errors.
The finally block lets you execute code, regardless of the result of the
try- and except blocks.
Syntax
assert condition [, Error Message]
Example: assert
Copy
x = 10
assert x > 0
print('x is a positive number.')
Output
x is a positive number.
Copy
x = 0
assert x > 0, 'Only positive numbers are allowed'
print('x is a positive number.')
Output
Above, x=0, so the assert condition x > 0 becomes False, and so it will
raise the AssertionError with the specified message 'Only positive
numbers are allowed'. It does not execute print('x is a positive
number.') statement.
Example: assert
Copy
def square(x):
assert x>=0, 'Only positive numbers are allowed'
return x*x
n = square(2) # returns 4
n = square(-2) # raise an AssertionError
Output
Example: AssertionError
Copy
def square(x):
assert x>=0, 'Only positive numbers are allowed'
return x*x
try:
square(-2)
except AssertionError as msg:
print(msg)
Output
Example
Live Demo
Output
A New Exception occured: User defined error
Example
Live Demo
Output
Enter a number: Input value is zero, try again!
Runtime error is a built-in class which is raised whenever a generated error does not
fall into mentioned categories. The program below explains how to use runtime error
as base class and user-defined error as derived class.
Example
Live Demo
Output
('u', 's', 'e', 'r', 'E', 'r', 'r', 'o', 'r')
😊ROCK ’N’
ROLL
GUYS😊