0% found this document useful (0 votes)
9 views

Notes Functions

Python

Uploaded by

Mangesh Deshmukh
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)
9 views

Notes Functions

Python

Uploaded by

Mangesh Deshmukh
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/ 9

In [10]: kingdom = {}

animals = ["Mammals", "Birds", "Reptiles", "Amphibians", "Fish"]


kingdom["animal"] = animals

#kingdom["animal"]
print(kingdom)

{'animal': ['Mammals', 'Birds', 'Reptiles', 'Amphibians', 'Fish']}

In [8]: a={ 'a': 1, 'b': 2, 'c': 3 }


#print(a.items()) #dict_items([('a', 1), ('b', 2), ('c', 3)])

print([(j,i) for i,j in a.items()]) #[(1, 'a'), (2, 'b'), (3, 'c')]

[(1, 'a'), (2, 'b'), (3, 'c')]

In [9]: keys = ['a', 'b', 'c']


values = [1, 2, 3]
dictionary = dict(zip(keys, values))
print(dictionary) #{'a': 1, 'b': 2, 'c': 3}

{'a': 1, 'b': 2, 'c': 3}


In [19]: x = int(input('Enter the value of x: '))
if x==0:
print("Factorial of 0! is=",1)
else:
r=factorial(x)
print("factorial = ",r)



#Factorial Functions.....
def factorial(n):
f=1
for i in range(1,n+1):
f=f*i
return f


Enter the value of x: 4


factorial = 24

Default Arguments
In [20]: # function with 2 keyword arguments grade and school
def student(name, age, grade="Five", school="ABC School"):
print('Student Details:', name, age, grade, school)

# without passing grade and school
# Passing only the mandatory arguments
student('Jon', 12)

Student Details: Jon 12 Five ABC School

Keyword Arguments
In [21]: # function with 2 keyword arguments grade and school
def student(name, age, grade="Five", school="ABC School"):
print('Student Details:', name, age, grade, school)

# not passing a school value (default value is used)
# six is assigned to grade
student('Kelly', 12, 'Six')

# passign all arguments
student('Jessa', 12, 'Seven', 'XYZ School')
Student Details: Kelly 12 Six ABC School
Student Details: Jessa 12 Seven XYZ School

In [23]: # function with 2 keyword arguments


def student(name, age):
print('Student Details:', name, age)

# default function call
student('Jessa', 14)

# both keyword arguments
student(name='Jon', age=12)

# 1 positional and 1 keyword
student('Donald', age=13)


# both keyword arguments by changing their order
student(age=13, name='Kelly')

Student Details: Jessa 14
Student Details: Jon 12
Student Details: Donald 13
Student Details: Kelly 13

Positional Arguments
In [24]: def add(a, b):
print(a - b)

add(50, 10)
# Output 40

add(10, 50)
#output -40

40
-40

In [25]: def add(a, b):


print(a - b)

add(105, 561, 4)

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [25], in <cell line: 4>()
1 def add(a, b):
2 print(a - b)
----> 4 add(105, 561, 4)

TypeError: add() takes 2 positional arguments but 3 were given

In [26]: #Point 1: Default arguments should follow non-default arguments


def get_student(name, grade='Five', age):
print(name, age, grade)
Input In [26]
def get_student(name, grade='Five', age):
^
SyntaxError: non-default argument follows default argument
In [27]: #Point: Default arguments must follow the default argument in a function definition
def student(name, grade="Five", age):
print('Student Details:', name, grade, age)

student('Jon', 'Six', 12)

Input In [27]
def student(name, grade="Five", age):
^
SyntaxError: non-default argument follows default argument

In [34]: #Point 2: keyword arguments should follow positional arguments only.


def get_student(name, age, grade):
print(name, age, grade)

get_student(name='Jessa', 12, 'Six')
Input In [34]
get_student(name='Jessa', 12, 'Six')
^
SyntaxError: positional argument follows keyword argument
In [37]: #Point 3: The order of keyword arguments is not important,
#but All the keyword arguments passed must match one of the arguments accepted by the function.

def get_student(name, age, grade):
print(name, age, grade)

get_student(grade='Six', name='Jessa', age=12)
# Output: Jessa 12 Six

get_student(name='Jessa', age=12, standard='Six')
Jessa 12 Six

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [37], in <cell line: 10>()
7 get_student(grade='Six', name='Jessa', age=12)
8 # Output: Jessa 12 Six
---> 10 get_student(name='Jessa', age=12, standard='Six')

TypeError: get_student() got an unexpected keyword argument 'standard'

In [38]: #Point 4: No argument should receive a value more than once


def student(name, age, grade):
print('Student Details:', name, grade, age)

student(name='Jon', age=12, grade='Six', age=12)
# Output: SyntaxError: keyword argument repeated
Input In [38]
student(name='Jon', age=12, grade='Six', age=12)
^
SyntaxError: keyword argument repeated: age

Variable-length arguments
In Python, sometimes, there is a situation where we need to pass multiple arguments to the function.
Such types of arguments are called arbitrary arguments or variable-length arguments.

We use variable-length arguments if we don’t know the number of arguments needed for the function
in advance.
in advance.

Types of Arbitrary Arguments:

arbitrary positional arguments (*args)
arbitrary keyword arguments (**kwargs)

The *args and **kwargs allow you to pass multiple positional arguments or keyword arguments to a function.

Arbitrary positional arguments (*args)


Arbitrary positional arguments (*args)

We can declare a variable-length argument with the * (asterisk) symbol.
Place an asterisk (*) before a parameter in the function definition to define an
arbitrary positional argument.

we can pass multiple arguments to the function. Internally all these values are represented
in the form of a tuple. Let’s understand the use of variable-length arguments with an example.

In [39]: def percentage(sub1, sub2, sub3):


avg = (sub1 + sub2 + sub3) / 3
print('Average', avg)

percentage(56, 61, 73)

Average 63.333333333333336
In [40]: # function with variable-length arguments
#Note: args is just a name. You can choose any name that you prefer, such as *subjects.
def percentage(*args):
sum = 0
for i in args:
# get total
sum = sum + i
# calculate average
avg = sum / len(args)
print('Average =', avg)

percentage(56, 61, 73)

Average = 63.333333333333336

Arbitrary keyword arguments (**kwargs)


The **kwargs allow you to pass multiple keyword arguments to a function. Use the **kwargs if you want to handle
named arguments in a function.

Use the unpacking operator(**) to define variable-length keyword arguments. Keyword arguments passed to a
kwargs are accessed using key-value pair
(same as accessing a dictionary in Python).

In [41]: # function with variable-length keyword arguments


def percentage(**kwargs):
sum = 0
for sub in kwargs:
# get argument name
sub_name = sub
# get argument value
sub_marks = kwargs[sub]
print(sub_name, "=", sub_marks)

# pass multiple keyword arguments
percentage(math=56, english=61, science=73)
math = 56
english = 61
science = 73

You might also like