Python Collections
Python Collections
if-else
if-elif-else
Make a list of five or more usernames, including the name 'admin’.
Imagine you are writing code that will print a greeting to each user after they
log in to a website. Loop through the list, and print a greeting to each user:
LIST WITH IF • If the username is 'admin', print a special greeting, such as Hello admin,
would you like to see a status report?
• Otherwise, print a generic greeting, such as Hello Eric, thank you for logging
in again.
Add an if test to hello_admin.py to make sure the list of users is not empty.
Two dimensions
my2DList = [[1,2,3,’a’],[5,6,7],[9,10,’e’,12,’cat’],[’beta’,14,15,16]]
https://www.purdue.edu/hla/sites/varalalab/wp-content/uploads/sites/20/2018/03/Lecture_10.pdf
EXAMPLES
mat = ((1, 2, 3, 5), (4.5, "a",
"b", "c"))
for j in mat:
for k in j:
print(k,end = " ")
print()
person[name]=[phone_no,email_id]
COMMON METHODS OF DICTIONARY
❑A function is a block of organized, reusable code that is used to perform a single, related
action. Functions provides better modularity for your application and a high degree of code
reusing.
❑As you already know, Python gives you many built-in functions like print() etc. but you can
also create your own functions. These functions are called user-defined functions.
❑Any indented lines that follow def identity(): make up the body of the function.
❑A function call tells Python to execute the code in the function
FUNCTIONS
❑The first statement of a function can be an optional statement - the documentation
string of the function or docstring.
❑The code block within every function starts with a colon (:) and is indented.
❑The statement return [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as return
None.
❑Syntax:
❑def function_name( parameters ):
‘’’function_docstring’’’
function_suite By default, parameters have a positional behavior, and
you need to inform them in the same order that they were
return [expression] defined
RESOLVING PARAMETER TYPES
❑We don’t declare the types of the parameters, relying instead on duck typing; that is, as long
as the parameter argument has the attributes our function expects to operate upon, we don’t
care about its real type
❑Wikipedia has a nice, concise explanation of duck typing: “A style of typing in which an
object’s methods and properties determine the valid semantics, rather than its inheritance
from a particular class or implementation of an explicit interface.”
❑The name of the concept refers to the duck test, attributed to James Whitcomb Riley, which
is phrased as follows: “When I see a bird that walks like a duck, and swims like a duck, and
quacks like a duck, I call that bird a duck.”
❑ In a duck-typed language, the function would take an object of any type, and
simply call its walk and quack methods, producing a runtime error if they are not
defined
PASS BY REFERENCE VS VALUE
❑All parameters (arguments) in the Python language are passed by reference. It means if you change
what a parameter refers to within a function, the change also reflects back in the calling function.
def changeme( mylist ):
'''This changes a passed list’‘’
myList.append(56)
print("Values inside the function: " + str(mylist))
return
mylist = [10,20,30];
changeme( mylist );
print("Values outside the function: “ + str(mylist))
❑There is one more example where argument is being passed by reference but inside the function, but
the reference is being over-written.
def changeme( mylist ):
'''This changes a passed list'''
mylist = [1,2,3,4]
print("Values inside the function: " + str(mylist))
return
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist
❑The parameter mylist is local to the function changeme. Changing mylist within the function does not
affect mylist. The function accomplishes nothing and finally this would produce following result:
❑ Function Arguments:
A function by using the following types of formal arguments::
Required arguments
Keyword arguments
Default arguments
Variable-length arguments
❑ Required arguments:
Required arguments are the arguments passed to a function in correct positional order.
printme();
ORDER MATTERS IN POSITIONAL ARGUMENTS
❑If a list is passed as an argument and we don’t want to change its values through the
function, then pass a copy of the list instead
function_name(list_name[:])
def build_person(fname, lname, age):
person={'fname':fname,
'lname':lname, ‘age’:age}
KEYWORD ARGUMENTS print(“Hello “ + fname + “ “ +
lname)
return person
❑Keyword arguments are related to the function calls. When you use keyword arguments in a
function call, the caller identifies the arguments by the parameter name.
❑This allows you to skip arguments or place them out of order because the Python interpreter
is able to use the keywords provided to match the values with parameters.
❑ p=build_person(fname=‘Alan’,lname=‘Turing’, age=42)
❑ p=build_person(age=42, fname=‘Alan’,lname=‘Turing’)
DEFAULT ARGUMENTS
❑ A default argument is an argument that assumes a default value if a value is not provided in
the function call for that argument.
❑ Following example gives idea on default arguments, it would print default age if it is not
passed:
def printinfo( name, age = 35 ):
print("Name: “ + name)
print("Age “ + age)
return
❑You may need to process a function for more arguments than you specified while defining the
function.
❑These arguments are called variable-length arguments and are not named in the function
definition, unlike required and default arguments.
❑The general syntax for a function with non-keyword variable arguments is this:
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
VARIABLE LENGTH ARGUMENTS
make_pizza(16)
❑If you want a function to accept several different kinds of arguments, the parameter
that accepts an arbitrary number of arguments must be placed last in the function
definition.
❑Python matches positional and keyword arguments first and then collects any
remaining arguments in the final parameter.
def build_person(fname, lname, age='',
**otherDetails):
person={'fname':fname,
VARIABLE KEYWORD ARGUMENT 'lname':lname}
if age:
person['age']=age
if otherDetails:
for key, value in
otherDetails.items():
person[key]=value
return person
❑Sometimes you’ll want to accept an arbitrary number of arguments, but you won’t know
ahead of time what kind of information will be passed to the function.
❑ In this case, you can write functions that accept as many key-value pairs as the calling
statement provides
RETURN VALUES
❑ The return statement takes a value from inside a function and sends it back to the line that called the
function
❑ A function can return any kind of value you need it to, including more complicated data structures
like lists and dictionaries
❑ A function may return multiple values
❑ When a function returns multiple comma-separated values, Python automatically wraps them up into
a tuple data structure and returns that tuple to the caller.
❑ This is a feature called automatic tuple packing.
❑ You may make this packing more explicit by wrapping up your return values in a tuple yourself but
this is neither required, nor encouraged
UNPACKING A TUPLE
a, b, c = multi_return()
ANONYMOUS FUNCTIONS
import pizza
pizza.make_pizza(16, ‘extra cheese’)
❑ from module_name import *
❑This approach to importing, in which you simply write import followed by the name of the module,
makes every function from the module available in your program
❑Importing specific functions-from module_name import function_name
❑ from module_name import function_0, function_1, function_2
❑Putting an alias for the module name
❑from module_name import function_name as fn