Types of Arguments,Scope of Variables-Notes
Types of Arguments,Scope of Variables-Notes
SCOPE OF VARIABLES
PRE-TEST
• Write a user defined function countVowels() that accept a
string as a parameter. The function should count and display
the total number of vowels present in the given string.
Learning Objective
• To explore the concepts of different types of arguments and
scope of variables in a user defined functions.
Learning Outcome
• After the completion of the topic, students will be able to
execute python programs with user defined functions that
accepts various types of arguments.
• Also, students will be able to identify the differences between
local variable & global variables in python programs.
Types of Arguments- Introduction
Example,
def f1(x,y):
statements
f1(10,20)
• In the above example, 10,20 are actual arguments whereas, x & y are formal arguments.
• In Python, there are only 4 types of actual arguments:
*Positional Arguments
*Default Arguments
*Keyword Arguments
*Variable length Arguments
Positional Arguments
• These are arguments passed to the actual arguments of a function in correct positional order i.e.,
in the same order as in the function header.
• The number and position of arguments must be matched.
• If we change their order, the result will change.
• If we change the number of arguments ,it will result in an error.
• Example:
def subtract(a,b):
print(a-b)
subtract(100,200) gives result is -100
subtract(200,100) gives result 100
subtract(200,100,300) gives an error
Default Arguments
• It is an argument that can assign a default value if a value is not provided in the function call for that
argument.
• The value is assigned at the time of function definition by using ‘=‘ operator.
• Positional arguments must appear before the default arguments, otherwise it results in Syntax error.
• Example
def interest(principal, rate, time=15):
def interest(principal, rate=8.5, time=15): Valid Function Header
def fn1(name=“Anu”):
print(“Hello”,name,”Good Morning”)
fn1(“Reshma”) Hello Reshma Good Morning
fn1() Hello Anu Good Morning
Keyword(Name) Arguments
• In a function call, we can specify values for some parameters using their name instead of the
position/order. These are called Keyword Arguments or Named Arguments .
• This allows calling function with arguments in any order using name of arguments.
• Example:
def fn1(name,msg):
print(“Hello”,name,msg)
fn1(name=“Anu”, msg=“Good Morning”) Hello Anu Good Morning
fn1(msg=“Good Morning”, name=“Reshma”) Hello Reshma Good Morning
• We can use both positional & keyword arguments simultaneously.
• But first we have to specify the positional argument and then keyword argument, otherwise,
it will generate Syntax Error “Positional Argument follows Keyword
Argument.
Example:
def fn1(name,msg):
print(“Hello”,name,msg)
fn1(name=“Anu”, msg=“Good Morning”)
fn1(msg=“Good Morning”, name=“Reshma”) # Valid