Python Programming U2
Python Programming U2
Python Functions
A function is a block of code which only runs when it is called.
Example:
def my_function():
Calling a Function
To call a function, use the function name followed by parenthesis:
def my_function():
print("Hello from a function")
my_function()
Hello from a function
User-Defined Function
We will define a function that returns the argument number's square when
called.
Function variables refer to the variables that are defined inside a function. These are local
variables and exist only during the execution of the function.
Example:
name and message are function variables. They are only accessible within the greet function.
g = "global"
def display():
print("Global variable inside the Function :", g)
display()
Python Function with Parameters
If you have experience in C/C++ or Java then you must be thinking about the
return type of the function and data type of arguments. That is possible in
Python as well (specifically for Python 3.5 and above).
return num3
# Driver code
num1, num2 = 5, 15
ans = add(num1, num2)
print(f"The addition of {num1} and {num2} results {ans}.")
Output:
The addition of 5 and 15 results 20.
# Driver code
num1, num2 = 5, 15
ans = add(num1, num2)
print(f"The addition of {num1} and {num2} results {ans}.")
# Prime functions
def is_prime(n):
if n in [2, 3]:
return True
if (n == 1) or (n % 2 == 0):
return False
r=3
while r * r <= n:
if n % r == 0:
return False
r += 2
return True
print(is_prime(78), is_prime(79))
Output:
False True
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(city):
print(city + " is a great place!")
my_function("New York")
my_function("Tokyo")
my_function("Paris")
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.
Error:
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil")
Traceback (most recent call last):
File "demo_function_args_error.py", line 4, in <module>
my_function("Emil")
TypeError: my_function() missing 1 required positional argument:
'lname'
Python supports various types of arguments that can be passed at the time
of the function call. In Python, we have the following function argument
types in Python:
● Default argument
● Positional arguments
**kwargs)
Default Arguments
# default arguments
print("x: ", x)
print("y: ", y)
# Driver code (We call myFun() with only
# argument)
myFun(10)
Code
number 1 is: 30
number 2 is: 20
number 1 is: 50
number 2 is: 30
Keyword Arguments
The idea is to allow the caller to specify the argument name with values so
that the caller does not need to remember the order of parameters.
You can also send arguments with the key = value syntax.
# Keyword arguments
student(firstname='Geeks', lastname='Practice')
student(lastname='Practice', firstname='Geeks')
Output:
Geeks Practice
Geeks Practice
Positional Arguments
We used the Position argument during the function call so that the first
argument (or value) is assigned to name and the second argument (or value)
is assigned to age. By changing the position, or if you forget the order of the
positions, the values can be used in the wrong places, as shown in the
Case-2 example below, where 27 is assigned to the name and Suraj is
assigned to the age.
Output:
Case-1:
Hi, I am Suraj
My age is 27
Case-2:
Hi, I am 27
My age is Suraj
Example:
● **kwargs captures name, age, and city as a dictionary.
You can use both in a function to accept both positional and keyword
arguments.
Output:
Docstring
The first string after the function is called the Document string or
Docstring in short. This is used to describe the functionality of the
function. The use of docstring in functions is optional but it is considered a
good practice.
The below syntax can be used to print out the docstring of a function.
Syntax: print(function_name.__doc__)
8
if (x % 2 == 0):
9
print("even")
10
else:
11
print("odd")
12
13
14
# Driver code to call the function
15
print(evenOdd.__doc__)
Output:
Function to check if the number is even or odd
8
def f2():
9
print(s)
10
11
f2()
12
13
# Driver's code
14
f1()
Output:
I love GeeksforGeeks
Anonymous Functions in Python
In Python, an anonymous function means that a function is without a name.
As we already know the def keyword is used to define the normal functions
and the lambda keyword is used to create anonymous functions.
1
# Python code to illustrate the cube of a number
2
# using lambda function
3
def cube(x): return x*x*x
4
5
cube_v2 = lambda x : x*x*x
6
7
print(cube(7))
8
print(cube_v2(7))
Output:
343
343
Python functions can accept a variable number of arguments using *args for non-keyword
arguments and **kwargs for keyword arguments.
You can combine both *args and **kwargs in a function, but *args should appear before
**kwargs:
Arbitrary Arguments, *args
If you do not know how many arguments that will be passed into your function,
add a * before the parameter name in the function definition.
This way the function will receive a tuple of arguments, and can access the
items accordingly:
Example
Example
def my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname = "Tobias", lname = "Refsnes")
His last name is Refsnes
E.g. if you send a List as an argument, it will still be a List when it reaches the
function:
def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
apple
banana
cherry
Return Values
To let a function return a value, use the return statement:
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
15
25
45
Recursion
Python also accepts function recursion, which means a defined function can call
itself.
In Python, scope refers to the region of the program where a variable is accessible.
● Local Scope: Variables defined within a function are only accessible inside that function
(local scope).
● Global Scope: Variables defined outside of all functions are accessible throughout the
code (global scope).
● Enclosing Scope: This refers to variables in the scope of an enclosing function (when
you have nested functions).
● Built-in Scope: The scope that contains all the built-in functions and exceptions (e.g.,
print, len, etc.).
Example:
x is global, y is in the enclosing scope, and z is local to inner_function.
Function documentation is typically provided using docstrings, which are string literals enclosed
in triple quotes (""" """) right after the function definition. This documentation describes what
the function does, its parameters, and its return value.
Example:
To access the documentation of a function, you can use the help() function:
Python Lambda
A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have
one expression.
It can take any number of arguments but can only have one expression. It is
generally used for short-lived, simple operations.
Syntax
lambda arguments : expression
Example
x = lambda a, b: a * b
print(x(5, 6))
30
Example
Summarize argument a, b, and c and return the result:
x = lambda a, b, c: a + b + c
print(x(5, 6, 2))
13
Why Use Lambda Functions?
The power of lambda is better shown when you use them as an anonymous
function inside another function.
Say you have a function definition that takes one argument, and that argument
will be multiplied with an unknown number:
def myfunc(n):
return lambda a : a * n
Use that function definition to make a function that always doubles the number
you send in:
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
22
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
22
33
Map Function
Syntax:
map(function, iterable)
1. Syntax Errors: These occur when the Python interpreter can't parse your code
because it doesn't follow proper syntax.
2. Runtime Errors: These occur during the execution of the program when
something goes wrong.
3. Semantic Errors: These occur when your code runs without crashing, but the
logic or behavior doesn't match what you intended.
4. Experimental Debugging: This involves using tools or methods (like print()
statements, debuggers, or logging) to investigate what's happening during
execution.
Let's go through each type of error with example code and how to debug them.
1. Syntax Errors
A syntax error occurs when the code doesn't follow Python's syntax rules. These errors
prevent the program from running.
Example:
Debugging:
The error message will indicate a syntax error, and in this case, it will tell you that the
closing parenthesis is missing. Fixing it is simple:
2. Runtime Errors
A runtime error occurs when the program starts but encounters an issue during
execution, such as dividing by zero or trying to access a variable that doesn't exist.
Example:
Debugging:
The runtime error occurs because division by zero is not allowed. The error message
would look like ZeroDivisionError: division by zero. To fix it, you can add a
check to avoid division by zero:
3. Semantic Errors
A semantic error occurs when the code runs without crashing, but it doesn't do what
you expect. The logic is wrong, even though the syntax is correct.
Example:
Debugging:
In the example above, the function calculates the circumference of a circle instead of
the area. The logic is incorrect. To fix it, you should return the area formula (π *
radius^2):
Strings:
A string is a sequence of characters that can be a combination of letters,
numbers, and special characters.
It can be declared in python by using single quotes, double quotes, or even
triple quotes.
These quotes are not a part of a string, they define only starting and
ending of the string.
Strings are immutable, i.e., they cannot be changed. Each element of the
string can be accessed using indexing or slicing operations.
Example
print("Hi")
print('Hi')
Example
a = "Hello"
print(a)
Multiline Strings
You can assign a multiline string to a variable by using three quotes:
Example
print(a)
Example
a = '''Lorem ipsum dolor sit amet,
print(a)
String Length
To get the length of a string, use the len() function.
Example
a = "Hello, World!"
print(len(a))
Check String
To check if a certain phrase or character is present in a string, we can
use the keyword in.
Example
Check if "free" is present in the following text:
print("free" in txt)
Use it in an if statement:
Example
if "free" in txt:
Check if NOT
To check if a certain phrase or character is NOT present in a string, we
can use the keyword not in.
Example
Use it in an if statement:
Example
A String Is a Sequence,
Indexing:
Creating a Tuple
You can create a tuple using parentheses () or
without them (comma-separated values).
Accessing Elements
1. Concatenation:
Repetition: