***Welcome to ashrafedu.blogspot.com ***This website is maintained by ASHRAF***
***Use tabs for Content***

POSTS

    Introduction to Functions

    A function is a group of statements within a program that exists for the purpose of performing a specific task.

    A program that has been written with each task in its own function is called a modularized program.


    1. Benefits of Modularizing a Program with Functions

    Simpler Code: A program’s code tends to be simpler and easier to understand when it is broken down into functions. Several small functions are much easier to read than one long sequence of statements.

    Code Reuse: Functions also reduce the duplication of code within a program. If a specific operation is performed in several places in a program, a function can be written once to perform that operation and then be executed any time it is needed.

    Better Testing: When each task within a program is contained in its own function, testing and debugging becomes simpler. Programmers can test each function in a program individually, to determine whether it correctly performs its operation. This makes it easier to isolate and fix errors.

    Easier Facilitation of Teamwork: Functions also make it easier for programmers to work in teams. When a program is developed as a set of functions that each performs an individual task, then different programmers can be assigned the job of writing different functions. It leads to faster development.

    2. Void Functions and Value-Returning Functions

    There are two types of functions: void functions and value returning functions.

    When a void function is called, it simply executes the statements it contains and then terminates. When a value-returning function is called, it executes the statements that it contains, and then it returns a value back to the statement that called it.

    3. Defining and Calling a Function

    To create a function you write its definition. Here is the general format of a function definition in Python:

    def function_name():

    statement

    statement

    etc.

    The first line is known as the function header. It marks the beginning of the function definition.

    The function header begins with the key word def, followed by the name of the function, followed by a set of parentheses, followed by a colon.

    The next line is a set of statements known as a block. A block is simply a set of statements that belong together as a group.

    A function definition specifies what a function does, but it does not cause the function to execute. To execute a function, you must call it.

    When a function is called, the interpreter jumps to that function and executes the statements in its block. Then, when the end of the block is reached, the interpreter jumps back to the part of the program that called the function, and the program resumes execution at that point.

    Example:

    # This program demonstrates a function.

    # First, we define a function named message.

    def message():

    print('I am Ashraf,')

    print('computer science faculty.')

     # Call the message function.

    message()

    In fact, it is common for a program to have a main function that is called when the program starts. The main function then calls other functions in the program as they are needed. It is often said that the main function contains a program’s mainline logic, which is the overall logic of the program.

    Example:

    # This program has two functions.

    # define the main function.

    def main():

    print('I have a message for you.')

    message()

    print('Goodbye!')

    # Next we define the message function.

    def message():

    print('I am Ashraf,')

    print('computer science faculty.')

    # Call the main function.

    main()

    Designing a Program to Use Functions

    Programmers commonly use a technique known as top-down design to break down an algorithm into functions.

    This process is called top-down design because the programmer begins by looking at the topmost level of tasks that must be performed and then breaks down those tasks into lower levels of subtasks.

    The process of top-down design is performed in the following manner:

    ·         The overall task that the program is to perform is broken down into a series of subtasks.

    ·         Each of the subtasks is examined to determine whether it can be further broken down into more subtasks. This step is repeated until no more subtasks can be identified.

    ·         Once all of the subtasks have been identified, they are written in code.


    Set - Set operations

    A set is an object that stores a collection of data in the same way as mathematical sets. Here are some important things to know about sets:

    ·         All the elements in a set must be unique. No two elements can have the same value.

    ·         Sets are unordered, which means that the elements in a set are not stored in any particular order.

    ·         The elements that are stored in a set can be of different data types.

    To create a set, you have to call the built-in set function.

    myset = set()

    After this statement executes, the myset variable will reference an empty set.

    One argument can be passed to the set function. The argument that you pass must be an object that contains iterable elements, such as a list, a tuple, or a string.

    Here is an example:

    myset = set(['a', 'b', 'c'])

    In this example we are passing a list as an argument to the set function. After this statement executes, the myset variable references a set containing the elements 'a', 'b', and 'c'.

    If a string is passed as an argument to the set function, each individual character in the string becomes a member of the set.

    Here is an example:

    myset = set('abc')

    After this statement executes, the myset variable will reference a set containing the elements 'a', 'b', and 'c'.

    Sets cannot contain duplicate elements. If an argument containing duplicate elements is passed to the set function, only one of the duplicated elements will appear in the set.

    myset = set('aaabc')

    The character 'a' appears multiple times in the string, but it will appear only once in the set. After this statement executes, the myset variable will reference a set containing the elements 'a', 'b', and 'c'.

    Getting the Number of Elements in a Set

    As with lists, tuples, and dictionaries, the len function can be used to get the number of elements in a set.

    Example:

    >>> myset = set([1, 2, 3, 4, 5])

    >>> len(myset)

     5

    Adding and Removing Elements

    Sets are mutable objects, so items can be added to them and items can be removed from them. The add method to add an element to a set.

    Example:

    >>> myset = set( )

    >>> myset.add(1)

    >>> myset.add(2)

    >>> myset.add(3)

    >>> myset e

    {1, 2, 3}

    Above example creates an empty set and add elements to the set.

    A group of elements can be added to a set all at one time with the update method. When a call to the update method is made an argument is passed an object that contains iterable elements, such as a list, a tuple, string, or another set. The individual elements of the object that is passed as an argument become elements of the set.

    Example:

    >>> myset = set([1, 2, 3])

    >>> myset.update([4, 5, 6])

    >>> myset e

    {1, 2, 3, 4, 5, 6}

    Removing an item from set

    An item can be removed from a set with either the remove method or the discard method. The item to be removed is passes as an argument to either method, and that item is removed from the set. The only difference between the two methods is how they behave when the specified item is not found in the set. The remove method raises a KeyError exception, but the discard method does not raise an exception.

    Example:

    >>> myset = set([1, 2, 3, 4, 5])

    >>> myset.remove(1)

    >>> myset

    {2, 3, 4, 5}

    >>> myset.discard(5)

    >>> myset

    {2, 3, 4}

    >>> myset.discard(99)

    >>> myset.remove(99)

    Traceback (most recent call last):

    File "<pyshell#12>", line 1, in <module>

    myset.remove(99)

    KeyError: 99

    To clear all the elements from the set, clear method is used.

    Example:

    >>> myset = set([1, 2, 3, 4, 5])

    >>> myset.clear( )

    >>> myset

    set( )

    Using the for Loop to Iterate over a Set

    The for loop in the following general format can be used to iterate over all the elements in a set:

    for var in set:

    statement

    statement

    etc.

    This loop iterates once for each element in the set. Each time the loop iterates, var is assigned an element.

    >>> myset = set(['a', 'b', 'c'])

    >>> for val in myset:

     print(val)

    a

    c

    b

    Using the in and not in Operators to Test for a Value in a Set

    in operator can be used to determine whether a value exists in a set. not in operator can be used to determine whether a value does not exists in a set.

    Example:

    >>> myset = set([1, 2, 3])

    >>> if 1 in myset:

    print('The value 1 is in the set.')

    >>> if 99 not in myset:

    print('The value 99 is not in the set.')

    Finding the Union of Sets

    The union of two sets is a set that contains all the elements of both sets. In Python, the union method is used to get the union of two sets. Here is the general format:

    set1.union(set2)

    Example:

    >>> set1 = set([1, 2, 3, 4])

    >>> set2 = set([3, 4, 5, 6])

    >>> set3 = set1.union(set2)

    >>> set3

    {1, 2, 3, 4, 5, 6}

    The | operator can also be used to find the union of two sets. Here is the general format of an expression using the | operator with two sets:

    set1 | set2

    Example:

    >>> set1 = set([1, 2, 3, 4])

    >>> set2 = set([3, 4, 5, 6])

    >>> set3 = set1 | set2

    >>> set3

    {1, 2, 3, 4, 5, 6}

    Finding the Intersection of Sets

    The intersection of two sets is a set that contains only the elements that are found in both sets. In Python, the intersection method is used to get the intersection of two sets.

    Here is the general format:

    set1.intersection(set2)

    Example:

    >>> set1 = set([1, 2, 3, 4])

    >>> set2 = set([3, 4, 5, 6])

    >>> set3 = set1.intersection(set2)

    >>> set3

    {3, 4}

    The & operator also can be used to find the intersection of two sets. Here is the general format of an expression using the & operator with two sets:

    set1 & set2

    Example:

    >>> set1 = set([1, 2, 3, 4])

    >>> set2 = set([3, 4, 5, 6])

    >>> set3 = set1 & set2

    >>> set3

    {3, 4}

    Finding the Difference of Sets

    The difference of set1 and set2 is the elements that appear in set1 but do not appear in set2. In Python, the difference method call is used to get the difference of two sets.

    Here is the general format:

    set1.difference(set2)

    Example:

    >>> set1 = set([1, 2, 3, 4])

    >>> set2 = set([3, 4, 5, 6])

    >>> set3 = set1.difference(set2)

    >>> set3

    {1, 2}

    The – operator can also be used to find the difference of two sets. Here is the general format

    of an expression using the - operator with two sets:

    set1 set2

    Example:

    >>> set1 = set([1, 2, 3, 4])

    >>> set2 = set([3, 4, 5, 6])

    >>> set3 = set1 − set2

    >>> set3

    {1, 2}

    Finding the Symmetric Difference of Sets

    The symmetric difference of two sets is a set that contains the elements that are not shared by the sets. In other words, it is the elements that are in one set but not in both. In Python, the symmetric_difference method call is used to get the symmetric difference of two sets. Here is the general format:

    set1.symmetric_difference(set2)

    Example:

    >>> set1 = set([1, 2, 3, 4])

    >>> set2 = set([3, 4, 5, 6])

    >>> set3 = set1.symmetric_difference(set2)

    >>> set3

    {1, 2, 5, 6}

    The ^ operator can also be used to find the symmetric difference of two sets. Here is the general format of an expression using the ^ operator with two sets:

    set1 ^ set2

    Example:

    >>> set1 = set([1, 2, 3, 4])

    >>> set2 = set([3, 4, 5, 6])

    >>> set3 = set1 ^ set2

    >>> set3

    {1, 2, 5, 6}

    Finding Subsets and Supersets

    In Python, the issubset method call is used to determine whether one set is a subset of another. Here is the general format:

    set2.issubset(set1)

    The issuperset method call is used to determine whether one set is a superset of another. Here is the general format:

    set1.issuperset(set2)

    Example:

    >>> set1 = set([1, 2, 3, 4])

    >>> set2 = set([2, 3])

    >>> set2.issubset(set1)

    True

    >>> set1.issuperset(set2)

    True

    The <= operator can also be used to determine whether one set is a subset of another and the >= operator to determine whether one set is a superset of another.

    Here is the general format of an expression using the <= operator with two sets:

    set2 <= set1

    Here is the general format of an expression using the >= operator with two sets:

    set1 >= set2

    Example:

    >>> set1 = set([1, 2, 3, 4])

    >>> set2 = set([2, 3])

    >>> set2 <= set1

    True

    >>> set1 >= set2

    True

    >>> set1 <= set2

    False

    Dictionary Methods

    Dictionary objects have several methods, which are summarized in below Table.


    Syntax of above methods:

    1. dictionary.clear()

    2. dictionary.get(key, default)

    In the general format, dictionary is the name of a dictionary, key is a key to search for in the dictionary, and default is a default value to return if the key is not found.

    3. dictionary.items()

    4. dictionary.keys()

    5. dictionary.pop(key, default)

    In the general format, dictionary is the name of a dictionary, key is a key to search for in the dictionary, and default is a default value to return if the key is not found.

    6. dictionary.popitem()

    7. dictionary.values()

    Dictionary

    A dictionary is an object that stores a collection of data. Each element in a dictionary has two parts: a key and a value. A key is used to locate a specific value.

    Creating a Dictionary

    Create a dictionary by enclosing the elements inside a set of curly braces ( {} ). An element consists of a key, followed by a colon, followed by a value. The elements are separated by commas.

    Example:

    phonebook = {'Ashraf':'555−1111', 'Amjad':'555−2222', 'Anwar':'555-3333'}

    The values in a dictionary can be objects of any type, but the keys must be immutable objects.

    Retrieving a Value from a Dictionary

    To retrieve a value from a dictionary, you simply write an expression in the following general format:

    dictionary_name[key]

    If the key exists in the dictionary, the expression returns the value that is associated with the key. If the key does not exist, a KeyError exception is raised.

    A KeyError exception is raised if you try to retrieve a value from a dictionary using a nonexistent key. To prevent such an exception, you can use the in operator to determine whether a key exists before you try to use it to retrieve a value.

    Adding Elements to an Existing Dictionary

    Dictionaries are mutable objects. You can add new key-value pairs to a dictionary with an assignment statement in the following general format:

    dictionary_name[key] = value

    If key already exists in the dictionary, its associated value will be changed to value. If the key does not exist, it will be added to the dictionary, along with value as its associated value.

    Example:

    >>> phonebook = {'Ashraf':'555−1111', 'Amjad':'555−2222', 'Anwar':'555−3333'}

    >>> phonebook['Sam'] = '555−0123'

    >>> phonebook['Ashraf'] = '555−4444'

    >>> phonebook

    {'Ashraf': '555-4444', 'Anwar': '555−3333', 'Sam': '555−0123','Amjad': '555−2222'}

    Note: The elements in a dictionary are not stored in any particular order.

    Deleting Elements

    An existing key-value pair can be deleted from a dictionary with the del statement. Here is the general format:

    del dictionary_name[key]

    After the statement executes, the key and its associated value will be deleted from the dictionary. If the key does not exist, a KeyError exception is raised.

    Example:

    >>> phonebook = {'Ashraf':'555−1111', 'Amjad':'555−2222', 'Anwar':'555−3333'}

    >>> del phonebook['Ashraf']

    >>> phonebook

    {'Amjad':'555−2222', 'Anwar':'555−3333'}

    Getting the Number of Elements in a Dictionary

    The built-in len function is used to get the number of elements in a dictionary.

    Example:

    >>> phonebook = {'Ashraf':'555−1111', 'Amjad':'555−2222', 'Anwar':'555−3333'}

    >>> num_items = len(phonebook)

    >>> print(num_items)

    Creating an Empty Dictionary

    Sometimes you need to create an empty dictionary and then add elements to it as the program executes. An empty set of curly braces can be used to create an empty dictionary.

    >>> phonebook = {}

    >>> phonebook['Ashraf'] = '555-1111'

    >>> phonebook['Amjad'] = '555-2222'

    The built-in dict() method can also be used to create an empty dictionary, as shown in the following statement:

    phonebook = dict()

    After this statement executes, the phonebook variable will reference an empty dictionary.

    Using the for Loop to Iterate over a Dictionary

    The for loop is used in the following general format to iterate over all the keys in a dictionary:

    for var in dictionary:

    statement

    statement

    etc.

    This loop iterates once for each element in the dictionary. Each time the loop iterates, var is assigned a key.

    Example:

    >>> phonebook = {'Ashraf':'555−1111', 'Amjad':'555−2222', 'Anwar':'555−3333'}

    >>> for key in phonebook:

     print(key)

    >>> phonebook = {'Ashraf':'555−1111', 'Amjad':'555−2222', 'Anwar':'555−3333'}

    >>> for key in phonebook:

     print(key, phonebook[key])