CST 445 M2
CST 445 M2
CST 445 M2
Module II
Functions
A function is a block of code which only runs when it is called. You can
pass data, known as parameters, into a function. A function can return data
as a result.
In Python, a function is a group of related statements that performs a specific
task.
Functions help break our program into smaller and modular chunks. As our
program grows larger and larger, functions make it more organized and
manageable.
Furthermore, it avoids repetition and makes the code reusable.
Syntax of Function
def function_name(parameters):
statement(s)
5. One or more valid python statements that make up the function body. Statements
must have the same indentation level (usually 4 spaces).
Creating a Function
Example
def my_function():
print("Hello from a function")
Calling a Function
Example
def my_function():
print("Hello from a function")
my_function() # calling a function
The return statement is used to exit a function and go back to the place from where
it was called.
Syntax of return
return [expression_list]
This statement can contain an expression that gets evaluated and the value is
returned. If there is no expression in the statement or the return statement itself is
not present inside a function, then the function will return the None object
Example:
def LargestNumber(num1,num2):
return num1
else:
return num2
largest = LargestNumber(10,20)
Example
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
def my_func():
x = 10
print("Value inside function:",x)
x = 20
Output
Value inside function: 10
Value outside function: 20
When we call a function with some values, these values get assigned to the
arguments according to their position.
Python allows functions to be called using keyword arguments. When we
call functions in this way, the order (position) of the arguments can be
changed. Following calls to the above function are all valid and produce the
same result.
Main function
Main function is like the entry point of a program. However, Python interpreter
runs the code right from the first line. The execution of the code starts from the
starting line and goes line by line. It does not matter where the main function is
present or it is present or not.
print("hey there")
if __name__=="__main__": # Using the special variable __name__
main()
Output:
Hello
hey there
When above program is executed, the interpreter declares the initial value of name
as “main”. When the interpreter reaches the if statement it checks for the value of
name and when the value of if is true it runs the main function else the main
function is not executed.
if __name__ == "__main__":
print("File1 is being run directly")
else:
print("File1 is being imported")
Output:
File1 __name__ = __main__
File1 is being run directly
Now, when the File1.py is imported into File2.py, the value of __name__ changes.
# File2.py
import File1
print("File2 __name__ = %s" %__name__)
if __name__ == "__main__":
print("File2 is being run directly")
else:
print("File2 is being imported")
def displayRange(lower,upper):
while lower<=upper:
print(lower)
lower=lower+1
def displayRange(lower,upper):
if lower<=upper:
print(lower)
displayRange(lower+1,upper)
displayRange(4,10)
Lambda functions
All of the code must appear on one line and a lambda cannot include a
selection statement, because selection statements are not expressions.
Example:
x=lambda x,y:x+y
print(x(2,3))
output will be 5
A data structure combines several data values into a unit so they can be treated as one
thing.
The data elements within a data structure are usually organized in a special way that
allows the programmer to access and manipulate them.
A string is a data structure that organizes text as a sequence of characters.
Lists
A list is a sequence of data values called items or elements. An item can be of any type.
Each of the items in a list is ordered by position.
Each item in a list has a unique index that specifies its position.
The index of the first item is 0, and the index of the last item is the length of the list
minus 1.
In Python, a list is written as a sequence of data values separated by commas. The entire
sequence is enclosed in square brackets ([ and ]).
You can also use other lists as elements in a list, thereby creating a list of lists.
When the element is a variable or any other expression, its value is included in the list.
The function len and the subscript operator [] work just as they do for strings:
Concatenation (+) and equality (==) also work as expected for lists:
The print function strips the quotation marks from a string, but does not alter the look of a
list:
To print the contents of a list without the brackets and commas, you can use a for loop, as
follows:
Much of list processing involves replacing each element, with the result of applying some
operation to that element.
The next example replaces the first three elements of a list with new ones:
Sorting a List
Although a list’s elements are always ordered by position, it is possible to impose a
natural ordering on them as well.
List comprehension
List comprehensions are used for creating new lists from other iterables.
As list comprehensions return lists, they consist of brackets containing the expression,
which is executed for each element along with the for loop to iterate over each element.
This is the basic syntax:
new_list = [expression for_loop_one_or_more conditions]
For example, find the squares of a number using the for loop:
numbers=[1,2,3,4]
squares=[]
for n in numbers:
squares.append(n**2)
print(squares) # Output: [1, 4, 9, 16]
You can use most of the operators and functions used with lists in a similar fashion with
tuples.
Dictionaries
Lists organize their elements by position.
However, in some situations, the position of a datum in a structure is irrelevant; we’re
interested in its association with some other element in the structure.
A dictionary organizes information by association, not position.
For example, when you use a dictionary to look up the definition of “mammal,” you
don’t start at page 1; instead, you turn directly to the words beginning with “M.”
In Python, a dictionary associates a set of keys with data values.
A Python dictionary is written as a sequence of key/value pairs separated by commas.
These pairs are sometimes called entries. The entire sequence of entries is enclosed in
curly braces ({ and }). A colon (:) separates a key and its value.
Here are some example dictionaries:
A phone book: {'Savannah':'476-3321', 'Nathaniel':'351-7743'}
Personal information: {'Name':'Molly', 'Age':18}
The next code segment creates an empty dictionary and adds two new entries:
Accessing Values
You can also use the subscript to obtain the value associated with a key. However, if the
key is not present in the dictionary, Python raises an error. Here are some examples,
using the info dictionary, which was set up earlier:
Removing Keys
To delete an entry from a dictionary, one removes its key using the method pop.
This method expects a key and an optional default value as arguments. If the key is in the
dictionary, it is removed, and its associated value is returned. Otherwise, the default value
is returned.
If pop is used with just one argument, and this key is absent from the dictionary, Python
raises an error.
The next session attempts to remove two keys and prints the values returned:
Traversing a Dictionary
When a for loop is used with a dictionary, the loop’s variable is bound to each key in an
unspecified order.
The next code segment prints all of the keys and their values in our info dictionary:
Note that the entries are represented as tuples within the list.
A tuple of variables can then access the key and value of each entry in this list within a
for loop:
If a special ordering of the keys is needed, you can obtain a list of keys using the keys
method and process this list to rearrange the keys.
For example, you can sort the list and then traverse it to print the entries of the dictionary
in alphabetical order:
Set
A set is a collection which is unordered and unindexed. In Python, sets are written with
curly brackets.
Create a Set:
But you can loop through the set items using a for loop, or ask if a specified value is
present in a set, by using the in keyword.
Add Items: To add one item to a set use the add() method. To add more than one item to
a set use the update() method.
thisset.add("orange")
print(thisset)
#using the update() method
print(thisset)
Get the Length of a Set: To determine how many items a set has, use the len() method.
thisset = {"apple", "banana", "cherry"}
print(len(thisset))