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

Python Functions

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

Python Functions

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

Python Functions:

 A function is a group of related statements that performs a specific task.


 Functions help break our program into smaller and modular chunks.
 As our program grows larger and larger, functions make it more organized and manageable.
 it avoids repetition and makes the code reusable.

Syntax of a function

def function_name(parameters):

statement(s)

A function definition that consists of the following components.

 Keyword def that marks the start of the function header.


 A function name to uniquely identify the function. Function naming follows the same rules
of writing identifiers in Python.
 Parameters (arguments) through which we pass values to a function. They are optional.
 A colon (:) to mark the end of the function header.
 One or more valid python statements that make up the function body. Statements must
have the same indentation level.
 An optional return statement to return a value from the function.

Once we have defined a function, we can call it from another function, program or even the Python
prompt. To call a function we simply type the function name with appropriate parameters.

def my_function(): #definition

print("Hello from a function")

my_function() #call

Arguments

 Information can be passed into functions as arguments.


 Arguments are specified after the function name, inside the parentheses.
 One can add as many arguments as needed, by separating them with a comma.

Example: Function with one argument

def my_function(fname):

print(fname + " Refsnes")

my_function("Emil")

my_function("Tobias")

my_function("Linus")

Number of Arguments

 By default, a function must be called with the correct number of arguments. That means if a
function expects 2 arguments, it has to be called with 2 arguments, not more, and not less.
Example : Function with two arguments:

def my_function(fname, lname):

print(fname + " " + lname)

my_function("Emil", "Refsnes")

If the number of arguments vary, it will display an error.

def my_function(fname, lname):

print(fname + " " + lname)

my_function("Emil")

The above program when run gives an error indicating mismatch in the number of arguments
passed.

Arbitrary arguments, *args

If the number of arguments passed into a function is unknown, a * is added 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")

my_function("Emil", "Tobias", "Linus", “Lin”)

The function my_function in the above example is called with 3 arguments and 4 arguments
(Arguments of variable length) .

Keyword arguments

Arguments with the key = value syntax is also allowed in python. 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")

my_function(child2 = "Ram", child3 = "Shyam", child1 = "Laxman") #order doesn’t matter

Arbitrary Keyword Arguments, **kwargs

If the number of keyword arguments that will be passed into the function is not known, add two
asterisk: ** before the parameter name in the function definition.

def my_function(**kid):

print("His last name is " + kid["lname"])


my_function(fname = "Tobias", lname = "Refsnes")

Default Parameter Value

If we call the function without argument, it uses the default value. The default value has to be
specified in the function definition.

def my_function(country = "Norway"):

print("I am from " + country)

my_function("Sweden")

my_function("India")

my_function() # Default value “Norway” is considered.

my_function("Brazil")

Passing a List as an Argument

Any data type can be sent as an argument to a function (string, number, list, dictionary etc.), and it
will be treated as the same data type inside the function.

def my_function(food):

for x in food:

print(x)

fruits = ["apple", "banana", "cherry"]

my_function(fruits)

Return values

To let a function return a value, the return statement is used.

def my_function(x):

return 5 * x

print(my_function(3)) #15

print(my_function(5)) #25

print(my_function(9)) #45

Programs on functions

1. Write a python function that accepts a string and checks of it is a palindrome or not.

def palindrome(str):
if str == str[::-1]:

print (str,"is a palindrome")

else:

print (str, "is not a palindrome")

palindrome('racecar')

palindrome('palindrome')

2. Write a python function that accepts a list and returns a new list of unique elements only.

def unique (l):

unique_list = set(l)

unique_list = list(unique_list)

print (unique_list)

unique ([1,1,1,2,3,2])

3. Using a function calculate the number of upper case and lower case letters in string.

def upperlowercount(string):

u=0

l=0

for i in string:

if i.isupper():

u+=1

if i.islower():

l+=1

print ("Upper =", u)

print ("Lower = ", l)

upperlowercount("STring")

4. Using a function check the number of occurrences of letter 'A' in a string.


def occur_A(string2):

a=0

for i in string2:

if i == 'A':

a+=1

print ("Number of 'A' =",a)

occur_A("AbcAd")

5. Calculate the average marks of 3 students. Student 1 has taken 2 subjects, Student 2 has taken 5
subjects and Student 3 has taken 3 subjects.

def avgMarks(*marks):

s=0

for i in marks:

s += i

print (s/len(marks))

avgMarks(30,40) # Student 1

avgMarks(30,40,40,30,40) # Student 2

avgMarks(30,40,40) # Student 3

6. Accept user input to take in the values for name, company and location. If the user does not enter
a location default it with the value "Bangalore"

def info(name,company,location="Bangalore"):

print (name,company,location)

n = input("name ")

c = input("company ")

q = int(input("1 for bangalore, 2 for other locs "))

if q == 1:

info (n,c)
if q== 2:

loc = input("enter location ")

info (n,c,loc)

7. Write a python program to accept user's first name middle name and last name. The user may or
may not enter all the names. Print them from within the function.

def names(**kwargs):

print (' '.join( kwargs.values()) )

names(first_name=input("First name: "),

middle_name=input("Middle name: "),

last_name=input("Last name: "))

8. Using functions Calculate area of circle if 1 parameter is passed. Calculate area of rectangle if 2
parameter are passed.

def area(*args):

if len(args) == 1:

print (3.14 * float (args[0] **2))

if len (args) == 2:

print (args[0] * args[1])

area(2,3)

area(3)

You might also like