[go: up one dir, main page]

0% found this document useful (0 votes)
13 views36 pages

CST 445 - Module 2

Uploaded by

Hrudhya Haridas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views36 pages

CST 445 - Module 2

Uploaded by

Hrudhya Haridas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

CST 445 –MODULE 2

Functions and Python Data


Structures

Dr Manju K
Functions
• In Python, a function is a group of related statements that performs a
specific task.
• Built-in functions - Functions that are built into Python.
User-defined functions - Functions defined by the users themselves.
• Defining function in Python
In Python, functions are defined using def statements, with parameters
enclosed in parentheses () and return values are indicated by the return
statement. A function without an explicit return statement returns None.

Calling the function is performed by using the call operator () after the name of
the function
Functions

Like all other variables in Python, there is no explicit type


associated with the function arguments.
Functions
• Parameters are defined by separating them with commas inside the
parentheses of function_name(). When calling a function, specify the
values in the defined order.
• If the number of values specified when calling the function does not
match the number of parameters in the function definition,
a TypeError will occur.
• All mutable parameters (arguments) in the Python language are
passed by reference. It means if you change what a parameter refers
to within a function, the change also reflects back in the calling
function. Immutable object are passed by value.
Parameters and Arguments
• Parameter is the input defined for the function. If there is more than
one value required by the function to work on, then, all of them will
be listed in parameter list separated by comma.
• Arguments are the actual vales passed to the function. List of
arguments should be supplied in same way as parameters are listed.
• Return statement is used to exit a function and go back to the place
from where it was called. It is used to return values to the calling
program. This statement can contain an expression that gets
evaluated and the value is returned. If there is no expression in the
statement or the return statement itself is not present inside a
function, then the function will return the None object.
• You can call a function by using the following types of formal
arguments −
• Required arguments
• Default arguments
• Keyword arguments
• Variable-length arguments
Required arguments, Default/Optional arguments
• Required arguments are the arguments passed to a function in
correct positional order. Here, the number of arguments in the
function call should match exactly with the function definition.

the parameter name does not have a


default value and is required
(mandatory) during a call.

the parameter msg has a default value of "Good


morning". So, it is optional during a call. If a value is
provided, it will overwrite the default value.
Default/Optional arguments
• Any number of arguments in a function can have a default value. But
once we have a default argument, all the arguments to its right must
also have default values.
• def hello(msg = "Good morning!", name):
We would get an error as:
SyntaxError: non-default argument follows default argument
Keyword arguments

• When we call a function with some values, these values get assigned
to the parameters according to their position.
• Python allows functions to be called using keyword arguments. When
we call functions in this way, the order (position) of the arguments
can be changed.
• hello(name='Manu', msg='Hai’)
Hello Manu,Hai
• hello(msg='How do you do ?', name='Manu')
Hello Manu,How do you do ?
Keyword arguments
Arbitrary arguments
• Sometimes, we do not know in advance the number of arguments that will be
passed into a function. Python allows us to handle this kind of situation through
function calls with an arbitrary number of arguments.
• In the function definition, we use an asterisk (*) before the parameter name to
denote this kind of argument.
Arbitrary arguments
Here, we have called the function with multiple arguments. These arguments get wrapped up
into a tuple before being passed into the function. Inside the function, we use a for loop to
retrieve all the arguments back.
Return Multiple values from a Function
• Python, can return multiple values from a function.
• Using Tuple:
• A tuple is a comma-separated sequence of items enclosed in
parentheses.
• To return multiple values, simply separate them with a comma and
return them as a tuple.

q, r = divide(22, 7)
print("Quotient:", q)
print("Remainder:", r)
Return Multiple values from a Function

• Using List:
• A list is an array-like collection of items enclosed in square brackets.
Unlike tuples, lists are mutable (can be modified).
Return Multiple values from a Function
• Using Dictionary: A dictionary is similar to a hash or map in other languages. It
associates keys with values.
Python Main Function
• Main function is like the entry point of a program. However, Python
interpreter runs the code right from the first line. The execution of
the code starts from the starting line and goes line by line. It does not
matter where the main function is present or it is present or not.
• Since there is no main() function in Python, when the command to
run a Python program is given to the interpreter, the code that is at
level 0 indentation is to be executed.
• There are two primary ways that you can instruct the Python
interpreter to execute or use code:
• You can execute the Python file as a script using the command line.
• You can import the code from one Python file into another file or into the
interactive interpreter.
• No matter which way of running your code you’re using, Python
defines a special variable called _name_ that contains a string whose
value depends on how the code is being used.
• If the source file is executed as the main program, the interpreter sets
the __name__ variable to have a value __main__.
• If this file is being imported from another module, __name__ will be
set to the module’s name.__name__ is a built-in variable which
evaluates to the name of the current module.
Defining a main Function
• In scripts that include the definitions of several cooperating functions,
it is often useful to define a special function named main that serves
as the entry point for the script.
• This function usually expects no arguments and returns no value. Its
purpose might be to take inputs, process them by calling other
functions, and print the results.
• The definition of the main function and the other function definitions
need appear in no particular order in the script, as long as main is
called at the very end of the script.
• The main function prompts the user for a
number, calls the square function to compute
its square, and prints the result.
• You can define the main and the square
functions in any order.
• When Python loads this module, the code for
both function definitions is loaded and
compiled, but not executed.
• Note that main is then called within an if
statement as the last step in the script.
• when the File1.py is imported into File2.py, the value of __name__
changes.

When File1.py is run directly, the interpreter sets the __name__ variable as __main__
and when it is run through File2.py by importing, the __name__ variable is set as the
name of the python script, i.e. File1.
Thus, it can be said that if __name__ == “__main__” is the part of the program that runs
when the script is run from the command line using a command like python File1.py.
Local and Global variables
• Python Global variables are those which are not defined inside any
function and have a global scope whereas Python local variables are
those which are defined inside a function and their scope is limited to
that function only.
Lambda functions
• Python Lambda Functions are anonymous functions means that the
function is without a name. We use lambda functions when we
require a nameless function for a short period of time.
• Syntax: lambda arguments : expression
• Lambda functions can have any number of arguments but only one
expression. The expression is evaluated and returned. Lambda
functions can be used wherever function objects are required.
# Program to show the use of lambda functions
Programs
Recursion
• Recursion involves a function calling itself.
• Recursive functions typically follow this pattern:
• There are one or more base cases that are directly solvable without the need for
further recursion.
• Each recursive call moves the solution progressively closer to a base case.
• Advantages of recursion
Recursive functions make the code look clean and elegant.
A complex task can be broken down into simpler sub-problems using
recursion.
Sequence generation is easier with recursion than using some nested
iteration.
• Disadvantages of recursion
Sometimes the logic behind recursion is hard to follow through.
Recursive calls are expensive (inefficient) as they take up a lot of memory
and time.
Recursive functions are hard to debug.
countdown(5)
5
4
3
2
1
0
Strings in Python
• Strings are compound data type made of sequence of characters.
• Strings are created by using single quotes or double quotes or triple
quotes.
• Python len() function can be used to find the number of characters in
the string- len('python’)
• The string is an immutable data structure.This means that its internal
characters can be accessed, but cannot be replaced, inserted or
removed.
• a simple for loop can access any of the characters in a string, some
times you just want to inspect one character at a given position
without visiting them all.The subscript operator [ ] makes this
possible.
• The integer expression in brackets indicates the position of a
particular character in that string. The integer expression is also
called index.
• string[ <an int expression>]
Example:
s="Python“
for i in range(len(s)):
print(i,s[i])
• s[2]=’c’ will leads to an error because strings are immutable.
Slicing for substrings
• We can extract a portion of string called substring using a process
called slicing.To extract substring, a colon(: ) is placed in the subscript.
• Generally when two integer positions are included in the slice, the
range of characters in the substring extends from the first position up
to but not including the second position.
• s="Python“
• s[1:3] ‘yt’
• If the first index is not mentioned, the slicing will start from 0.
• If the last index is not mentioned, the slicing will go till the end of the
string.
• >>>s[3:]
‘hon’
• We can also specify the step size in slicing. The example below slice
0,2 and 4th character.
>>>s[0:5:2]
'Pto’
• We can also use –ve index in slicing
• s[-6:-2:2]
'Pt’
Negative step size makes string to be printed in reverse
• >>> s[5:0:-1]
'nohty'
• >>>s[-1:-7:-1]
'nohtyP’
• Print the full string
>>> s[:] or >>>s[::]
'Python’
• Print the string in reverse
>>> s[::-1]
'nohtyP'
#Write the output of following python code : ( University Question)
S ="Computer"
print(S[::2])
print(S[::-1])
print(S[:])
• output:
Cmue
retupmoC
Computer

You might also like