Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
33 views

Python Lec 7 Functions

The document discusses Python functions and modules. It explains that functions allow reusable blocks of code to perform tasks, while modules allow importing and reuse of Python code across files. Functions can take arguments, return values, and have default values. Lambda functions provide anonymous one-time functions. Modules allow organization of code into libraries that can be imported and used in other Python files through the import statement.

Uploaded by

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

Python Lec 7 Functions

The document discusses Python functions and modules. It explains that functions allow reusable blocks of code to perform tasks, while modules allow importing and reuse of Python code across files. Functions can take arguments, return values, and have default values. Lambda functions provide anonymous one-time functions. Modules allow organization of code into libraries that can be imported and used in other Python files through the import statement.

Uploaded by

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

Python Functions & Modules

ICS 2241
Python functions
• A function is a reusable block of programming statements designed to perform a certain task
• The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of
writing the same code again and again for different inputs, we can do the function calls to reuse code
contained in it over and over again.
• Functions can be both built-in or user-defined. It helps the program to be concise, non-repetitive, and
organized.
• Python includes many built-in functions. These functions perform a predefined task and can be called upon in
any program, as per requirement.
• However, if you don't find a suitable built-in function to serve your purpose, you can define one.
Creating a Function
• In Python a function is defined using the def keyword
def my_function():
print("Hello from a 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()
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 (name). When the function is
called, we pass along a name, which is used inside the function to print the name:
def greet(name):
print ('Hello ', name)
greet('Steve') # calling function with argument

def greet(name1, name2, name3):


print ('Hello ', name1, ' , ', name2 , ', and ', name3)
greet('Steve', 'Bill', 'Yash')
• Arguments are often shortened to args in Python documentations.
• The terms parameter and argument can be used for the same thing: information that
are passed into a function.
• A parameter is the variable listed inside the parentheses in the function definition.
• An argument is the value that is sent to the function when it is called.
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.
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil", "Nyamboke")
• If you try to call the function with 1 or 3 arguments, you will get an error:
my_function("Emil")
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:
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")
Arbitrary Arguments are often shortened to *args in Python documentations.
Keyword Arguments
• You can also send arguments with the key = value syntax.
• This way the order of the arguments does not matter.
Keyword Arguments
• You can also send arguments with the key = value syntax.
• This way the order of the arguments does not matter.
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")
• The phrase Keyword Arguments are often shortened to kwargs in Python documentations.
Arbitrary Keyword Arguments, **kwargs
• If you do not know how many keyword arguments that will be passed into your function, add
two asterisk: ** before the parameter name in the function definition.
• This way the function will receive a dictionary of arguments, and can access the items
accordingly:
def my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname = "Tobias", lname = "Refsnes")
Default Parameter Value
• The following example shows how to use a default parameter value.
• If we call the function without argument, it uses the default value:
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
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))
Python Lambda
• The def keyword is used to define a function in Python, as we have seen in the previous
chapter
• The lambda keyword is used to define anonymous functions in Python. Usually, such a
function is meant for one-time use
Syntax
lambda [arguments] : expression
• The lambda function can have zero or more arguments after the : symbol. When this
function is called, the expression after : is executed
square = lambda x : x * x
square(5)
print(square(5))
• Lambda functions can take any number of arguments:
x = lambda a, b : a * b
print(x(5, 6))
Python Module
• A module is the same as a code library.
• Any text file with the .py extension containing Python code is basically a module
• Different Python objects defined in one module can be made available to another Python script by
using the import statement
• Creating a Module
• To create a module just save the code you want in a file with the file extension .py
def sum(x, y):
return x + y
• Importing a Module
• Note: When using a function from a module, use the syntax: module_name.function_name
import calc
calc.sum(5, 5)
• def greeting(name):
print("Hello, " + name)
• import mymodule
mymodule.greeting("Jonathan")
Built-in Modules
• There are several built-in modules in Python, which you can import whenever you like.
• To display a list of all available modules, use the following command in the Python console:
>>>help('modules')
Python OS Module
• It is possible to automatically perform many operating system tasks. The OS module in
Python provides functions for creating and removing a directory (folder), fetching its
contents, changing and identifying the current directory, etc.
• You first need to import the os module to interact with the underlying operating system.
So, import it using the import os statement before using its functions
• Getting Current Working Directory
• The getcwd() function confirms returns the current working directory
>>> import os
>>> os.getcwd()
>>> os.mkdir("MyPythonProject") #making directory
>>> os.chdir("C:\MyPythonProject") # changing current workign directory
>>> os.getcwd()
>>> os.rmdir("C:\\MyPythonProject")
>>>os.listdir() # listing directory content

You might also like