Function Arguments

A function can have more than one argument.

Keyword Arguments

Passing values by their names.

Code

def greet(arg_1, arg_2):
print(arg_1 + " " + arg_2)
greeting = input()
name = input()
greet(arg_1=greeting,arg_2=name)
PYTHON

Input

Good Morning
Ram

Output

Good Morning Ram

Possible Mistakes - Keyword Arguments

Code

def greet(arg_1, arg_2):
print(arg_1 + " " + arg_2)
greeting = input()
name = input()
greet(arg_2=name)
PYTHON

Input

Good Morning
Ram

Output

TypeError: greet() missing 1 required positional argument: 'arg_1'

Positional Arguments

Values can be passed without using argument names.

  • These values get assigned according to their position.
  • Order of the arguments matters here.

Code

def greet(arg_1, arg_2):
print(arg_1 + " " + arg_2)
greeting = input()
name = input()
greet(greeting,name)
PYTHON

Input

Good Morning
Ram

Output

Good Morning Ram

Possible Mistakes - Positional Arguments

Mistake - 1

Code

def greet(arg_1, arg_2):
print(arg_1 + " " + arg_2)
greeting = input()
name = input()
greet(greeting)
PYTHON

Input

Good Morning
Ram

Output

TypeError: greet() missing 1 required positional argument: 'arg_2'

Mistake - 2

Code

def greet(arg_1, arg_2):
print(arg_1 + " " + arg_2)
greeting = input()
name = input()
greet()
PYTHON

Input

Good Morning
Ram

Output

TypeError: greet() missing 2 required positional arguments

Default Values

Example - 1

Code

def greet(arg_1="Hi", arg_2="Ram"):
print(arg_1 + " " + arg_2)
greeting = input()
name = input()
greet()
PYTHON

Input

Hello
Teja

Output

Hi Ram

Example - 2

Code

def greet(arg_1="Hi", arg_2="Ram"):
print(arg_1 + " " + arg_2)
greeting = input()
name = input()
greet(greeting)
PYTHON

Input

Hello
Teja

Output

Hello Ram

Example - 3

Code

def greet(arg_1="Hi", arg_2="Ram"):
print(arg_1 + " " + arg_2)
greeting = input()
name = input()
greet(name)
PYTHON

Input

Hello
Teja

Output

Teja Ram

Example - 4

Code

def greet(arg_1="Hi", arg_2="Ram"):
print(arg_1 + " " + arg_2)
greeting = input()
name = input()
greet(arg_2=name)
PYTHON

Input

Hello
Teja

Output

Hi Teja

Example - 5

Code

def greet(arg_1="Hi", arg_2):
print(arg_1 + " " + arg_2)
greeting = input()
name = input()
greet(arg_2=name)
PYTHON

Input

Hello
Teja

Output

SyntaxError:non-default argument follows default argument

Non-default arguments cannot follow default arguments.

Example - 6

Code

def greet(arg_2, arg_1="Hi"):
print(arg_1 + " " + arg_2)
greeting = input()
name = input()
greet(arg_2=name)
PYTHON

Input

Hello
Teja

Output

Hi Teja

Passing Immutable Objects

Code

def increment(a):
a += 1
a = int(input())
increment(a)
print(a)
PYTHON

Input

5

Output

5

Even though variable names are same, they are referring to two different objects. Changing the value of the variable inside the function will not affect the variable outside.

Post a Comment

Please Select Embedded Mode To Show The Comment System.*

Previous Post Next Post

Contact Form