Python Classroom Series – 06/Dec/2019

Functions

Function with varied number of arguments

  • *args:
    • Variable number of arguments.
    • Can be used in function arguments
import sys

def addition(*args):
    result = 0
    for arg in args:
        result = result + arg
    return result



if __name__ == '__main__':
    print("Inside main")
    print(addition(1))
    print(addition())
    print(addition(1,2))
    print(addition(1,2,3,4,5,6,7,8,9))

* Exercise: Write a python function which takes variable number of arguments and finds out the largest number of it.
# Sample Outputs
max(1,2,10,1,100) = 100

max(100) => 100

max() => -1

def max(*args):
    if len(args) == 0:
        result = -1
    else:
        result = args[0]

    for arg in args:
        if arg > result:
            result = arg
    return result
* Exercise: Write a min function with variable arguments
# Sample Outputs
min() => -1
min(10,5) => 5
min(10) => 10
  • **kwargs: This is also a variable set of arguments, they are called as keyworded arguments
def printargs(**kwargs):
    for key, value in kwargs.items():
        print(key+"==>"+value)
    pass


if __name__ == '__main__':
    print("Inside main")
    printargs(first = '1', sec= '2')
    printargs(a = '1', b= '2')

Python Lists, Tuples and Dictionaries.

Lists:

  • Mutable collection of objects.
# open terminal or powershell and enter python to enter python shell
x = [1,2,4,8,16]
type(x)
# print 1st element index will be 0
x[0]
# finding length of list
len(x)
# to insert element
x.append(32)
# to remove element
x.remove(1)
# to update element
x[0]=1
# slicing can be done
x[::-1]

Tuples:

  • Immuatable collection of objects
  • Syntax is <variable> = (1,2,3)
y = (1,2,3)
type(y)
y[0] # 1
y[0] = 5 # error => exception
y.append # error
y.remove # error

Dictionary

  • Is collection of key value pairs
z = {'course': 'python', 'applicable': ['AWS', 'AZURE', 'DEVOPS']}
type(z)
# insert a new key pair
z['inst'] = 'QualityThought'
# To find if key exists
#key in <varibale>
'course' in z

Iterating files and directories

  • walk method of os

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About continuous learner

devops & cloud enthusiastic learner