Problem Solving with Python 3

 

Unit-III

lists

Most of the times a variable can hold a single value. However, in many cases, you need to assign more than that.

· List is a container that holds a number of items. Each element or value that is inside a list is called an item.

· All the items in a list are assigned to a single variable.

· Lists avoid having a separate variable to store each item .

· Lists can be simple or nested lists(A list within another list is nested) with varying types of values.

· Lists are one of the most flexible data storage formats in Python because they can have values added, removed, and changed.

 

Creating Lists

Lists are constructed using square brackets [ ] , it contains a list of items separated by commas.

1.>>> superstore=["metro", "tesco", "walmart", "kmart", "carrefour"]#Each item in the list is a string

2. >>> superstore            #contents of the list variable are displayed by executing the list variable name

["metro", "tesco", "walmart", "kmart", "carrefour"]

You can create an empty list without any items.

The syntax is,

list_name = [ ]

Examples:

1. >>> number_list = [4, 4, 6, 7, 2, 9, 10, 15]                     # contains items of the same type

2. >>> mixed_list = ['dog', 87.23, 65, [9, 1, 8, 1]]         #the items are string, float, integer and another list itself.

3.>>> type(mixed_list)                                                      #In Python, the list type is called as list.

<class 'list'>

4. >>> empty_list = []

5. >>> empty_list

[]

6. >>> type(empty_list)

<class 'list'>

 

Basic List Operations

(Explain Various Operations on list?)

Operations on list: 

·         Concatenation 

·         Repetitions 

·         Membership

·         Comparison

·         Indexing 

·         Slicing

·         Updating 

Concatenation operations :

In Python, lists can also be concatenated using the + sign, and the * operator is used to create a repeated sequence of list items. For example,

1. >>> list_1 = [1, 3, 5, 7]

2. >>> list_2 = [2, 4, 6, 8]

3. >>> list_1 + list_2                        # The list_1 and list_2 lists are added to form a new list.

[1, 3, 5, 7, 2, 4, 6, 8]

 

Repetition operations(multiplication operator):

You can use the multiplication operator on the list. It repeats the items the number of times you specify in the list.

Example:

>>> list_1 * 3                         # In the list_1 contents are repeated three times

[1, 3, 5, 7, 1, 3, 5, 7, 1, 3, 5, 7]

 

Comparison operations:

In below example contents of the lists list_1 and list_2 are compared using the == operator and the result is Boolean False since the items in both the lists are different.

Example:

>>> list_1 = [1, 3, 5, 7]

>>> list_2 = [2, 4, 6, 8]

>>> list_1 == list_2             

False

 

Membership Operation(in)

You can check for the presence of an item in the list using in and not in membership operators. It returns a Boolean True or False. For example,

Syntax:  item_name in listname

Example:

1. >>> list_items = [1,3,5,7]

2. >>> 5 in list_items

True

3. >>> 10 in list_items

False

Modifying Items in Lists(Update)

Lists are mutable in nature as the list items can be modified after you have created a list. You can modify a list by replacing the older item with a newer item in its place and without assigning the list to a completely new variable.

For example,

1. >>> city = ["hyderabad", "nalgonda", "secunderabad"]

2. >>> city[0] = "warangal"

3. >>> city

['warangal', 'nalgonda', 'secunderabad']

4. >>> city[2] = "khammam"

5. >>> city

['warangal', 'nalgonda', 'khammam']

6. >>> city[-1] = "rangareddy"

7. >>> city

['warangal', 'nalgonda', 'rangareddy']

 

When you assign an existing list variable to a new variable, an assignment (=) on lists does not make a new copy. Instead, assignment makes both the variable names point to the same list in memory.

For example,

1. >>> zoo = ["Lion", "Tiger", "Zebra"]

2. >>> forest = zoo

3. >>> type(zoo)

<class 'list'>

4. >>> type(forest)

<class 'list'>

5. >>> forest

['Lion', 'Tiger', 'Zebra']

6. >>> zoo[0] = "Fox"

7. >>> zoo

['Fox', 'Tiger', 'Zebra']

8. >>> forest

['Fox', 'Tiger', 'Zebra']

9. >>> forest[1] = "Deer"

10. >>> forest

['Fox', 'Deer', 'Zebra']

11. >>> zoo

['Fox', 'Deer', 'Zebra']

 

Indexing and Slicing in Lists

Indexing

As an ordered sequence of elements, each item in a list can be called individually, through indexing. The expression inside the bracket is called the index. Lists use square brackets [ ] to access individual items, with the first item at index 0, the second item at index 1 and so on. The index provided within the square brackets indicates the value being accessed.

The syntax for accessing an item in a list is,

list_name[index]

where index should always be an integer value and indicates the item to be selected. For the list superstore, the index breakdown is shown below.

1. >>> superstore = ["metro", "tesco", "walmart", "kmart", "carrefour"]

2. >>> superstore[0]

'metro'

2. >>> superstore[9]

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

IndexError: list index out of range

In addition to positive index numbers, you can also access items from the list with a negative index number, by counting backwards from the end of the list, starting at −1. Negative indexing

is useful if you have a long list and you want to locate an item towards the end of a list.

For the same list superstore, the negative index breakdown is shown below.

1. >>> superstore[-3]

'walmart'

 

Slicing of lists is allowed in Python wherein a part of the list can be extracted by specifying index range along with the colon (:) operator which itself is a list.

The syntax for list slicing is,

list_name[start:stop[:step]]

where both start and stop are integer values (positive or negative values). List slicing returns a part of the list from the start index value to stop index value which includes the start index value but excludes the stop index value.

Step specifies the increment value to slice by and it is optional. For the list fruits, the positive and negative index breakdown is shown below.

 

1. >>> fruits = ["grapefruit", "pineapple", "blueberries", "mango", "banana"]

2. >>> fruits[1:3]                               #All the items in the fruits list starting from an index value of

['pineapple', 'blueberries']              # 1 up to index value of 3 but excluding the index value of 3 is sliced

3. >>> fruits[:3]                                 # You can skip the start index value and specify only the stop index value

['grapefruit', 'pineapple', 'blueberries']

4. >>> fruits[2:]                                 # if you want to access the last stop items, then there is no need to specify the stop value

['blueberries', 'mango', 'banana']

5. >>> fruits[1:4:2]

['pineapple', 'mango']

6. >>> fruits[:]                       # If you skip both the start and stop index values  and specify only the colon operator

['grapefruit', 'pineapple', 'blueberries', 'mango', 'banana']

7. >>> fruits[::2]        #Using double colon has no value for start index and no value for stop index and jump the items by two steps.

['grapefruit', 'blueberries', 'banana']

8. >>> fruits[::-1]                  #All the items in a list can be displayed in reverse order by specifying a double colon followed by an index value of −1

['banana', 'mango', 'blueberries', 'pineapple', 'grapefruit']

9. >>> fruits[-3:-1]

['blueberries', 'mango']

 

The list() Function

The built-in list() function is used to create a list.

The syntax for list() function is,

list([sequence])

where the sequence can be a string, tuple or list itself. If the optional sequence is not specified then an empty list is created. For example,

1. >>> quote = "How you doing?"

2. >>> string_to_list = list(quote)      #The string variable quote is converted to a list using the list() function

3. >>> string_to_list

['H', 'o', 'w', ' ', 'y', 'o', 'u', ' ', 'd', 'o', 'i', 'n', 'g', '?']

4. >>> friends = ["j", "o", "e", "y"]

5. >>> friends + quote                                            #you cannot concatenate a list with a string value

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: can only concatenate list (not "str") to list

6. >>> friends + list(quote)            #In order to concatenate a string with the list, must convert the string #value to list type

['j', 'o', 'e', 'y', 'H', 'o', 'w', ' ', 'y', 'o', 'u', ' ', 'd', 'o', 'i', 'n', 'g', '?']

 

List Methods

Examples:

1. >>> cities = ["oslo", "delhi", "washington", "london", "seattle", "paris", "washington"]

2. >>> cities.count('seattle')

1

3. >>> cities.index('washington')

2

4. >>> cities.reverse()

5. >>> cities

['washington', 'paris', 'seattle', 'london', 'washington', 'delhi', 'oslo']

6. >>> cities.append('brussels')

7. >>> cities

['washington', 'paris', 'seattle', 'london', 'washington', 'delhi', 'oslo', 'brussels']

8. >>> cities.sort()

9. >>> cities

['brussels', 'delhi', 'london', 'oslo', 'paris', 'seattle', 'washington', 'washington']

10. >>> cities.pop()

'washington'

11. >>> cities

['brussels', 'delhi', 'london', 'oslo', 'paris', 'seattle', 'washington']

12. >>> more_cities = ["brussels", "copenhagen"]

13. >>> cities.extend(more_cities)

14. >>> cities

['brussels', 'delhi', 'london', 'oslo', 'paris', 'seattle', 'washington', 'brussels', 'copenhagen']

15. >>> cities.remove("brussels")

16. >>> cities

['delhi', 'london', 'oslo', 'paris', 'seattle', 'washington', 'brussels', 'copenhagen']

 

Populating Lists with Items

One of the popular way of populating lists is to start with an empty list [ ], then use the functions append() or extend() to add items to the list. For example,

1. >>> continents = []

2. >>> continents.append("Asia")

3. >>> continents.append("Europe")

4. >>> continents.append("Africa")

5. >>> continents

['Asia', 'Europe', 'Africa']

 

Program to Dynamically Build User Input as a List

1. list_items = input("Enter list items separated by a space ").split() 

2. print(f"List items are {list_items}")

3. items_of_list = []

4. total_items = int(input("Enter the number of items "))

5. for i in range(total_items):

6.         item = input("Enter list item: ")

7.         items_of_list.append(item)

8. print(f"List items are {items_of_list}")

Output

Enter list items separated by a space Asia Europe Africa

List items are ['Asia', 'Europe', 'Africa']

Enter the number of items 2

Enter list item: Australia

Enter list item: Americas

List items are ['Australia', 'Americas']

 

You can build a list from user-entered values in two ways. In the first method you chain input() and split() together using dot notation. This user-entered input string value is split based on spaces and the split() method returns a list of string items.

In the second method you have to specify the total number of items that you are planning to insert into the list beforehand itself . Based on this number we iterate through the for loop as many times using range() function . During each iteration, you need to append the user entered value to the list .

Traversing of Lists

Using a for loop you can iterate through each item in a list.

Program to Illustrate Traversing of Lists Using the for loop

1. fast_food = ["waffles", "sandwich", "burger", "fries"]

2. for each_food_item in fast_food:                                                           # list variable is specified in the for loop

3.         print(f"I like to eat {each_food_item}")

4. for each_food_item in ["waffles", "sandwich", "burger", "fries"]:     # you can specify a list directly in for loop

5.         print(f"I like to eat {each_food_item}")

Output

I like to eat waffles

I like to eat sandwich

I like to eat burger

I like to eat fries

I like to eat waffles

I like to eat sandwich

I like to eat burger

I like to eat fries

 

You can obtain the index value of each item in the list by using range() along with len() function.

 

Program to Display the Index Values of Items in List

1. silicon_valley = ["google", "amd", "yahoo", "cisco", "oracle"]

2. for index_value in range(len(silicon_valley)):

3.         print(f"The index value of '{silicon_valley[index_value]}' is {index_value}")

Output

The index value of 'google' is 0

The index value of 'amd' is 1

The index value of 'yahoo' is 2

The index value of 'cisco' is 3

The index value of 'oracle' is 4

You need to pass the list name as an argument to len() function and the resulting value will be passed as an argument to range() function to obtain the index value of each item in the list .

 

Map, Filter and Reduce

Reduce():

An operation that combines a sequence of elements into a single value is sometimes called reduce.

Syntax: reduce(function_name,sequence_variable)

Map()

Maps is a function  assigns a function on  each of the elements in a sequence.

Syntax: map(function_name,sequence_variable)

Filter()

A filter it selects some of the elements and filters out the others.

Syntax: filter(function_name,sequence_variable)

 

# Example of using map, filter, and reduce in Python 

data = [1, 2, 3, 4, 5] 

 

# Using the map to apply a function to each element 

# Lambda function returns the square of x 

result1 = map(lambda x: x * 2, data)  # Result: [2, 4, 6, 8, 10] 

 

# Using the filter to filter elements based on a condition 

# Lambda function returns True for an even number 

result2 = filter(lambda x: x % 2 == 0, data)  # Result: [2, 4] 

 

# Using reduce to aggregate elements 

# Lambda function returns product of x and y 

from functools import reduce 

result3 = reduce(lambda x, y: x * y, data)  # Result: 120 

 

list loop

Let’s see all the different ways to iterate over a list in Python and the performance comparison between them.

1.for loop

2.while loop

3.infinite loop

for Loop:

The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iteratable objects.

· Iterating over a sequence is called traversal.

· Loop continues until we reach the last item in the sequence.

· The body of for loop is separated from the rest of the code using indentation.

Syntax:

for var_name in input_list_name:

Example:

lst = [10, 50, 75, 83, 98, 84, 32]

  for x in lst:

    print(x)

Output:

10

50

75

83

98

84

32

 

while loop:

The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true.

When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.

Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by referring to their indexes.

Remember to increase the index by 1 after each iteration.

 Syntax:

while(condition) :

    Statement

        update_expression

Example:  

lst = [10, 50, 75, 83, 98, 84, 32]

 x = 0

 while x < len(lst):             #Iterating using while loop

    print(lst[x])

    x = x+1

Output:

10

50

75

83

98

84

32

 

Infinite Loop 

A loop becomes infinite loop if the condition given never becomes false. It keeps on running. Such loops are called infinite loop.

Example:

 

Lists Are Mutable

· Lists are mutable. (can be changed)

· Mutability is the ability for certain types of data to be changed without entirely recreating it.

· An item can be changed in a list by accessing it directly as part of the assignment statement.

· Using the indexing operator (square brackets[ ]) on the left side of an assignment, one of the list items can be updated.

Example:

>>> numbers = [42, 123]

>>> numbers[1] = 5

>>> numbers

[42, 5]

The one-eth element of numbers, which used to be 123, is now 5.

Lists are represented by boxes with the word list outside and the elements of the list

inside. numbers contains two elements; the diagram shows that the value of the second element has been reassigned from 123 to 5.

 

Aliasing

If a refers to an object and you assign b = a, then both variables refer to the same object:

>>> a = [1, 2, 3]

>>> b = a

>>> b is a

True

 

The association of a variable with an object is called a reference. In this example, there are two references to the same object.

An object with more than one reference has more than one name, so we say that the object is aliased.

If the aliased object is mutable, changes made with one alias affect the other:

>>> b[0] = 42

>>> a

[42, 2, 3]

 

Cloning or Copying a list

(Write a short note on cloning lists?)

Cloning or copying a list is simply creating another list that has the same elements as the original list. Elements in a list can be copied into another list by various methods.

For example,

For cloning a list in Python we can follow these approaches-

 By following the Slicing technique

This is the easiest and fastest way to clone a list. This method is considered when we want to modify a list and also keep a copy of the original. In this, we make a copy of the list itself, along with the reference.

 Example:

# Python program to copy or clone a list

# Using the Slice Operator

def Cloning(b):

            a = b[:]

            return a

# Driver Code

b = [4, 8, 2, 10, 15, 18]

c = Cloning(b)

print("Original List:", b)

print("After Cloning:", c)

 By using copy() method

The Python List copy() is an inbuilt method copy used to copy all the elements from one list to another.

# Python code to clone or copy a list

# Using built-in method copy()

def Cloning(li1):

            li_copy =[]

            li_copy = li1.copy()

            return li_copy

li1 = [4, 8, 2, 10, 15, 18]

li2 = Cloning(li1)

print("Original List:", li1)

print("After Cloning:", li2)

Output:

Original List: [4, 8, 2, 10, 15, 18]

After Cloning: [4, 8, 2, 10, 15, 18]

 List parameters

When you pass a list to a function, the function gets a reference to the list. If the function modifies the list, the caller sees the change. For example, delete_head removes the first element from a list:

def delete_head(t):

del t[0]

Here’s how it is used:

>>> letters = ['a', 'b', 'c']

>>> delete_head(letters)

>>> letters

['b', 'c']

The parameter t and the variable letters are aliases for the same object. The stack diagram looks like Figure

It is important to distinguish between operations that modify lists and operations that create new lists. For example, the append method modifies a list, but the + operator creates a new list:

>>> t1 = [1, 2]

>>> t2 = t1.append(3)

>>> t1

[1, 2, 3]

>>> t2

None

append modifies the list and returns None:

>>> t3 = t1 + [4]

>>> t1

[1, 2, 3]

>>> t3

[1, 2, 3, 4]

>>> t1

 

Tuples

·         A tuple is a sequence of values.

·         The values can be any type, and they are indexed by integers, so in that respect tuples are a lot like lists.

·         Tuples are immutable. Once a tuple is created, you cannot change its values.

·         A tuple is defined by putting a comma-separated list of values inside parentheses ( ). Each value inside a tuple is called an item.

The syntax for creating tuples is,

tuple_name = (item_1, item_2, item_3, ………….., item_n)

 

Examples:

1. >>> internet = ("cern", "timbernerslee", "www", 1980)

2. >>> internet

('cern', 'timbernerslee,' 'www', 1980)

3. >>> type(internet)

<class 'tuple'>

4. >>> f1 = "ferrari", "redbull", "mercedes", "williams", "renault"

5. >>> f1

('ferrari', 'redbull', 'mercedes', 'williams', 'renault')

6. >>> type(f1)

<class 'tuple'>

Another way to create a tuple is the built-in function tuple. With no argument, it creates an empty tuple. 

Example:

>>> t = tuple()

>>> t

Output: 

()

You can create an empty tuple without any values.

The syntax is, tuple_name = ()

For example,

1. >>> empty_tuple = ()

2. >>> empty_tuple

()

3. >>> type(empty_tuple)

<class ‘tuple’>

 

Tuple Assignment

Tuple assignment is more elegant:

>>> a, b = b, a

The left side is a tuple of variables; the right side is a tuple of expressions. Each value is assigned to its respective variable. All the expressions on the right side are evaluated before any of the assignments.

The number of variables on the left and the number of values on the right have to be the same:

>>> a, b = 1, 2, 3

ValueError: too many values to unpack

More generally, the right side can be any kind of sequence (string, list or tuple). For example, to split an email address into a user name and a domain, you could write:

>>> addr = 'monty@python.org'

>>> uname, domain = addr.split('@')

The return value from split is a list with two elements; the first element is assigned to uname, the second to domain:

>>> uname

'monty'

>>> domain

'python.org'

 

Tuples as Return Values

Strictly speaking, a function can only return one value, but if the value is a tuple, the effect is the same as returning multiple values. For example, if you want to divide two integers and compute the quotient and remainder, it is inefficient to compute x/y and then x%y. It is better to compute them both at the same time.

The built-in function divmod takes two arguments and returns a tuple of two values:

the quotient and remainder. You can store the result as a tuple:

>>> t = divmod(7, 3)

>>> t

(2, 1)

Or use tuple assignment to store the elements separately:

>>> quot, rem = divmod(7, 3)

>>> quot

2

>>> rem

1

Here is an example of a function that returns a tuple:

def min_max(t):

return min(t), max(t)

max and min are built-in functions that find the largest and smallest elements of a sequence. min_max computes both and returns a tuple of two values.

 

Variable-Length Argument Tuples

Functions can take a variable number of arguments. A parameter name that begins with * gathers arguments into a tuple.

If you have a sequence of values and you want to pass it to a function as multiple arguments, you can use the * operator. For example, divmod takes exactly two arguments; it doesnt work with a tuple:

>>> t = (7, 3)

>>> divmod(t)

TypeError: divmod expected 2 arguments, got 1

But if you scatter the tuple, it works:

>>> divmod(*t)

(2, 1)

Many of the built-in functions use variable-length argument tuples. For example, max and min can take any number of arguments:

>>> max(1, 2, 3)

3

 

Basic Tuple Operations(Explain tupple and it’s operations?)

Most list operators also work on tuples. Like in lists, you can use the + operator to concatenate tuples together and the * operator to repeat a sequence of tuple items.

Concatenation: Two tuples, tuple_1 and tuple_2, consisting of integer type are created . The tuple_1 and tuple_2 tuples are added to form a new tuple. The new tuple has all items of both the added tuples.

1. >>> tuple_1 = (2, 0, 1, 4)

2. >>> tuple_2 = (2, 0, 1, 9)

3. >>> tuple_1 + tuple_2

(2, 0, 1, 4, 2, 0, 1, 9)

Repetition

You can use the multiplication operator * on tuples. The items in the tuples are repeated the number of times you specify, Here tuple_1 items are repeated three times.

>>> tuple_1 = (2, 0, 1, 4)

>>> tuple_1 * 3

(2, 0, 1, 4, 2, 0, 1, 4, 2, 0, 1, 4)

The items in tuples are compared using == equal to operator, and the result is Boolean False since the items in the tuples are different.

>>> tuple_1 = (2, 0, 1, 4)

>>> tuple_2 = (2, 0, 1, 9)

>>> tuple_1 == tuple_2

False

Membership validation

You can check for the presence of an item in a tuple using in and not in membership operators. It returns a Boolean True or False. For example,

1. >>> tuple_items = (1, 9, 8, 8)

2. >>> 1 in tuple_items

True

3. >>> 25 in tuple_items

False

 

Comparison operators like <, <=, >, >=, == and != are used to compare tuples. Tuples are compared position by position. The first item of the first tuple is compared to the first item of the second tuple; if they are not equal then this will be the result of the comparison, or else the second item of the first tuple is compared to the second item of the second tuple; if they are not equal then this will be the result of the comparison, else the third item is considered, and so on.For example,

1. >>> tuple_1 = (9, 8, 7)

2. >>> tuple_2 = (9, 1, 1)

3. >>> tuple_1 > tuple_2

True

4. >>> tuple_1 != tuple_2

True

 

Indexing in Tuples

Each item in a tuple can be called individually through indexing. The expression inside the bracket is called the index. Square brackets [ ] are used by tuples to access individual items, with the first item at index 0, the second item at index 1 and so

The bracket operator indexes an element:

>>> t = ('a', 'b', 'c', 'd', 'e')

>>> t[0]

'a'

Slicing Slicing of tuples is allowed in Python wherein a part of the tuple can be extracted by

specifying an index range along with the colon (:) operator, which itself results as tuple type.

The slice operator selects a range of elements:

>>> t = ('a', 'b', 'c', 'd', 'e')

>>> t[1:3]

('b', 'c')

 

But if you try to modify one of the elements of the tuple, you get an error:

>>> t[0] = 'A'

TypeError: object doesn't support item assignment Because tuples are immutable, you can’t modify the elements.

But you can replace one tuple with another:

>>> t = ('A',) + t[1:]

>>> t

('A', 'b', 'c', 'd', 'e')

This statement makes a new tuple and then makes t refer to it.

The tuple() Function

The built-in tuple() function is used to create a tuple.

The syntax for the tuple() function is,

tuple([sequence])

where the sequence can be a number, string or tuple itself. If the optional sequence is not specified, then an empty tuple is created.

 

1. >>> norse = "vikings"

2. >>> string_to_tuple = tuple(norse)

3. >>> string_to_tuple

('v', 'i', 'k', 'i', 'n', 'g', 's')

 

Built-In Functions Used on Tuples

There are many built-in functions for which a tuple can be passed as an argument.

len() The len() function returns the numbers of items in a tuple.

sum() The sum() function returns the sum of numbers in the tuple.

sorted() The sorted() function returns a sorted copy of the tuple as a list while leaving the original tuple untouched.

count() The count() method counts the number of times the item has occurred in the tuple and returns it.

index()  The index() method searches for the given item from the start of the tuple and returns its index. If the value appears more than once, you will get the index of the first one. If the item is not present in the tuple, then ValueError is thrown by this method.

 

For example,

1. >>> years = (1987, 1985, 1981, 1996)

2. >>> len(years)

4

3. >>> sum(years)

7949

4. >>> sorted_years = sorted(years)

5. >>> sorted_years

[1981, 1985, 1987, 1996]

 

Program to Iterate Over Items in Tuples Using for Loop

1. ocean_animals = ("electric_eel", "jelly_fish", "shrimp", "turtles", "blue_whale")

2. def main():

3.         for each_animal in ocean_animals:

4.                     print(f"{each_animal} is an ocean animal")

5. if __name__ == "__main__":

6.         main()

Output

electric_eel is an ocean animal

jelly_fish is an ocean animal

shrimp is an ocean animal

turtle is an ocean animal

blue_whale is an ocean animal

 

Write Python Program to Swap Two Numbers Without Using Intermediate/Temporary Variables. Prompt the User for Input

1. def main():

2.         a = int(input("Enter a value for first number "))

3.         b = int(input("Enter a value for second number "))

4.         b, a = a, b

5.         print("After Swapping")

6.         print(f"Value for first number {a}")

7.         print(f"Value for second number {b}")

8. if __name__ == "__main__":

9.         main()

Output

Enter a value for the first number 5

Enter a value for the second number 10

After Swapping

Value for first number 10

Value for second number 5

 

Dictionary

(Write a short note on Dictionary data type in python?)

· Another useful data type built into Python is the Dictionary.

· A dictionary is a collection of an unordered set of key:value pairs, with the requirement that the keys are unique within a dictionary.

·Dictionaries are constructed using curly braces { }, wherein you include a list of key:value pairs separated by commas.

· Also, there is a colon (:) separating each of these key and value pairs, where the words to the left of the colon operator are the keys and the words to the right of the colon operator are the values.

· Unlike lists, which are indexed by a range of numbers, dictionaries are indexed by keys. Here a key along with its associated value is called a key:value pair. Dictionary keys are case sensitive.

 

The syntax for creating a dictionary is,

dictionary_name = {key_1:value_1, key_2:value_2, key_3:value_3, ………,key_n:value_n}

 

For example,

1. >>> fish = {"g": "goldfish", "s":"shark", "n": "needlefish", "b":"barramundi","m":"mackerel"}

2. >>> fish

{'g': 'goldfish', 's': 'shark', 'n': 'needlefish', 'b': 'barramundi', 'm': 'mackerel'}

Placing a comma-separated list of key:value pairs within the curly braces adds initial key: value pairs to the dictionary.

This is also the way dictionaries are written on output .

Each of the keys and values here is of string type. A value in the dictionary can be of any data type including string, number, list, or dictionary itself.

 

In dictionaries, the keys and their associated values can be of different types.

For example,

1. >>> mixed_dict = {"portable":"laptop", 9:11, 7:"julius"}

2. >>> mixed_dict

{'portable': 'laptop', 9: 11, 7: 'julius'}

3. >>> type(mixed_dict)

<class 'dict'>

 

Operations and Methods

Creating Dictionary

You can create an empty dictionary by specifying a pair of curly braces and without any key:value pairs. The syntax is,

dictionary_name = { }

For example,

1. >>> empty_dictionary = {}

2. >>> empty_dictionary

{}

3. >>> type(empty_dictionary)

<class 'dict'>

 

In dictionaries, the order of key:value pairs does not matter. For example,

1. >>> pizza = {"pepperoni":3, "calzone":5, "margherita":4}

2. >>> fav_pizza = {"margherita":4, "pepperoni":3, "calzone":5}

3. >>> pizza == fav_pizza

True

 

Accessing and Modifying key:value Pairs in Dictionaries

Each individual key:value pair in a dictionary can be accessed through keys by specifying it inside square brackets. The key provided within the square brackets indicates the key:value  pair being accessed.

The syntax for accessing the value for a key in the dictionary is,

dictionary_name[key]

The syntax for modifying the value of an existing key or for adding a new key:value pair to a dictionary is,

dictionary_name[key] = value

If the key is already present in the dictionary, then the key gets updated with the new value. If the key is not present then the new key:value pair gets added to the dictionary.

For example,

1. >>> cities = {"hyderabad":1305, "mumbai":1440, "delhi":1511,"kolkata":1480, "chennai":1520}

2. >>> cities["hyderabad"] = 1310

3. >>> cities

{'hyderabad': 1310, 'mumbai': 1440, 'delhi': 1511, 'kolkata': 1480, 'chennai': 1520}

4. >>> cities["delhi"]

1511

5. >>> cities["warangal"] = 1503

6. >>> cities

{'hyderabad': 1310, 'mumbai': 1440, 'delhi': 1511, 'kolkata': 1480, 'chennai': 1520,'warangal': 1503}

7. >>> cities["katak"]

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

KeyError: 'katak'

You can check for the presence of a key in the dictionary using in and not in membership operators. It returns either a Boolean True or False value. For example,

1. >>> clothes = {"rainy":"raincoats", "summer":"tees", "winter":"sweaters"}

2. >>> "spring" in clothes

False

3. >>> "spring" not in clothes

True

The del Statement

To delete the key:value pair, use the del statement followed by the name of the dictionary

along with the key you want to delete.

del dict_name[key]

1. >>> animals = {"r":"rat", "c":"cat", "m":"moose"}

2. >>> animals

{'r': 'rat', 'c': 'cat', 'm': 'moose'}

3. >>> del animals["c"]

4. >>> animals

{'r': 'rat', 'm': 'moose'}

 

Dictionary Methods

Dictionary allows you to store data in key:value format without depending on indexing. You can get a list of all the methods associated with dict in below table

For example,

1. >>> box_office_billion = {"avatar":2009, "titanic":1997, "starwars":2015, "harrypotter":

2011, "avengers":2012}

2. >>> box_office_billion_fromkeys = box_office_billion.fromkeys(box_office_billion)

3. >>> box_office_billion_fromkeys

{'avatar': None, 'titanic': None, 'starwars': None, 'harrypotter': None, 'avengers': None}

4. >>> box_office_billion_fromkeys = box_office_billion.fromkeys(box_office_

billion, "billion_dollar")

5. >>> box_office_billion_fromkeys

{'avatar': 'billion_dollar', 'titanic': 'billion_dollar', 'starwars': 'billion_dollar', 'harrypotter':

'billion_dollar', 'avengers': 'billion_dollar'}

6. >>> print(box_office_billion.get("frozen"))

None

7. >>> box_office_billion.get("frozen",2013)

2013

8. >>> box_office_billion.keys()

dict_keys(['avatar', 'titanic', 'starwars', 'harrypotter', 'avengers'])

9. >>> box_office_billion.values()

dict_values([2009, 1997, 2015, 2011, 2012])

10. >>> box_office_billion.items()

dict_items([('avatar', 2009), ('titanic', 1997), ('starwars', 2015), ('harrypotter', 2011),

('avengers', 2012)])

11. >>> box_office_billion.update({"frozen":2013})

12. >>> box_office_billion

{'avatar': 2009, 'titanic': 1997, 'starwars': 2015, 'harrypotter': 2011, 'avengers': 2012, ' frozen': 2013}

13. >>> box_office_billion.setdefault("minions")

14. >>> box_office_billion

{'avatar': 2009, 'titanic': 1997, 'starwars': 2015, 'harrypotter': 2011, 'avengers': 2012,

' frozen': 2013, 'minions': None}

15. >>> box_office_billion.setdefault("ironman", 2013)

16. >>> box_office_billion

{'avatar': 2009, 'titanic': 1997, 'starwars': 2015, 'harrypotter': 2011, 'avengers': 2012,

'minions': None, 'ironman': 2013}

17. >>> box_office_billion.pop("avatar")

2009

18. >>> box_office_billion.popitem()

('ironman', 2013)

19. >>> box_office_billion.clear()

{}

 

Built-In Functions Used on Dictionaries

There are many built-in functions for which a dictionary can be passed as an argument

The main operations on a dictionary are storing a value with some key and extracting the value for a given key.

 

Built-In Functions Used on Dictionaries

Built-in Functions Description

len() The len() function returns the number of items (key:value pairs) in a dictionary.

all() The all() function returns Boolean True value if all the keys in the dictionary are True else returns False.

any() The any() function returns Boolean True value if any of the key in the dictionary is True else returns False.

sorted() The sorted() function by default returns a list of items, which are sorted based on dictionary keys.

For example,

1. >>> presidents = {"washington":1732, "jefferson":1751, "lincoln":1809,"roosevelt":1858, "eisenhower":1890}

2. >>> len(presidents)

5

In Python, any non-zero integer value is True, and zero is interpreted as False. If all the keys are Boolean True values, then the output is True else it is False Boolean value for all() function in dictionaries. If any one of the keys is True then it results in a True Boolean value else False Boolean value for any() function in dictionaries

3. >>> all_dict_func = {0:True, 2:False}

4. >>> all(all_dict_func)

False

5. >>> all_dict_func = {1:True, 2:False}

6. >>> all(all_dict_func)

True

7. >>> any_dict_func = {1:True, 2:False}

8. >>> any(any_dict_func)

True

9. >>> sorted(presidents)

['eisenhower', 'jefferson', 'lincoln', 'roosevelt', 'washington']

10. >>> sorted(presidents, reverse = True)

['washington', 'roosevelt', 'lincoln', 'jefferson', 'eisenhower']

11. >>> sorted(presidents.values())

[1732, 1751, 1809, 1858, 1890]

12. >>> sorted(presidents.items())

[('eisenhower', 1890), ('jefferson', 1751), ('lincoln', 1809), ('roosevelt', 1858),('washington', 1732)]

 

ADVANCED LIST PROCESSING List Comprehension:

· List comprehensions provide a concise way to apply operations on a list.

· It creates a new list in which each element is the result of applying a given operation in a list.

·It consists of brackets containing an expression followed by a “for” clause, then a list.

· The list comprehension always returns a result list.

Syntax   list=[ expression for item in list if conditional ]

>>>L=[x**2 for x in range(0,5)]

>>>print(L) 

 [0, 1, 4, 9, 16]

>>>[x for x in range(1,10) if x%2==0]

[2, 4, 6, 8]

>>>[x for x in 'Python Programming' if x in ['a','e','i','o','u']]

['o', 'o', 'a', 'i']

 

Illustrative programs:

Sorting—arranging the elements within a list into a particular order—is a common activity. For example, a list of integers may be arranged in ascending order (that is, from smallest to largest). A list of strings may be arranged in lexicographical (commonly called alphabetical) order. Many sorting algorithms exist, and some perform much better than others. We will consider one sorting algorithm that is relatively easy to implement.

 

selection sort

Selection sort is one of the simplest sorting algorithms. It is similar to the hand picking where we take the smallest element and put it in the first position and the second smallest at the second position and so on. It is also similar. We first check for smallest element in the list and swap it with the first element of the list. Again, we check for the smallest number in a sub list, excluding the first element of the list as it is where it should be (at the first position) and put it in the second position of the list. We continue repeating this process until the list gets sorted.

 

ALGORITHM: 

[30, 10, 12, 8, 15, 1]

Step - 1: Get the length of the array.

length = len(array) → 6

Step - 2: First, we set the first element as minimum element.

Step - 3: Now compare the minimum with the second element. If the second element is smaller than the first, we assign it as a minimum.

Again we compare the second element to the third and if the third element is smaller than second, assign it as minimum. This process goes on until we find the last element.

Step - 4: After each iteration, minimum element is swapped in front of the unsorted array.

Step - 5: The second to third steps are repeated until we get the sorted array.

 

PROGRAM:

def selection_sort(array): 

    length = len(array) 

    for i in range(length-1): 

        minIndex = i   

        for j in range(i+1, length): 

            if array[j]<array[minIndex]: 

                minIndex = j 

        array[i], array[minIndex] = array[minIndex], array[i]  

    return array     

array = [21,6,9,33,3]

print("The sorted array is: ", selection_sort(array)) 

 

INSERTION SORT

(Write a program to sort the programs using insertion sort?) 

The insertion sort algorithm concept is based on the deck of the card where we sort the playing card according to a particular card.

While the card-playing, we compare the hands of cards with each other. Most of the player likes to sort the card in the ascending order so they can quickly see which combinations they have at their disposal.

The array spilled virtually in the two parts in the insertion sort - An unsorted part and sorted part.

The sorted part contains the first element of the array and other unsorted subpart contains the rest of the array. The first element in the unsorted array is compared to the sorted array so that we can place it into a proper sub-array.

It focuses on inserting the elements by moving all elements if the right-side value is smaller than the left side.

It will repeatedly happen until the all element is inserted at correct place.

Algorithm:

  • Spilt a list in two parts - sorted and unsorted.
  • Iterate from arr[1] to arr[n] over the given array.
  • Compare the current element to the next element.
  • If the current element is smaller than the next element, compare to the element before, Move to the greater elements one position up to make space for the swapped element.

Program:

def insertion_sort(list1):                                          # creating a function for insertion 

                  for i in range(1, len(list1)):                    # Outer loop to traverse through 1 to len(list1) 

              value = list1[i] 

 

            # Move elements of list1[0..i-1], that are 

            # greater than value, to one position ahead 

            # of their current position 

            j = i - 1 

            while j >= 0 and value < list1[j]: 

                list1[j + 1] = list1[j] 

                j -= 1 

            list1[j + 1] = value 

        return list1 

            # Driver code to test above 

  list1 = [10, 5, 13, 8, 2] 

print("The unsorted list is:", list1) 

  print("The sorted list1 is:", insertion_sort(list1)) 


Output:

The unsorted list is: [10, 5, 13, 8, 2]

The sorted list1 is: [2, 5, 8, 10, 13]

 

Merge sort

Merge sort is similar to the quick sort algorithm as works on the concept of divide and conquer. It is one of the most popular and efficient sorting algorithm. It is the best example for divide and conquer category of algorithms.

It divides the given list in the two halves, calls itself for the two halves and then merges the two sorted halves.

The sub lists are divided again and again into halves until we get the only one element each. Then we combine the pair of one element lists into two element lists, sorting them in the process. The sorted two element pairs is merged into the four element lists, and so on until we get the sorted list.

Algorithm As of now, we have a rough understanding of how merge sort is performed. For better understanding let's dive deep into the algorithm followed by the code:

  1. Create a merge_sort() function
  2. Initiate array list and divide it into subarrays.
  3. Create copies of the subarrays
  4. Create three-pointers that maintain indexes.
  5. Pick larger elements and place them in the right position
  6. Pick the remaining elements and sort them accordingly
  7. The result will be sorted array
  8. Print the sorted array.

 

Program:

def Merge_Sort(array):

    if len(array) > 1:

        #  mid is the point where the array is divided into two subarrays

        mid = len(array)//2

        Left = array[:mid]

        Right = array[mid:]

 

        Merge_Sort(Left)

        Merge_Sort(Right)

 

        i = j = k = 0

        while i < len(Left) and j < len(Right):

            if Left[i] < Right[j]:

                array[k] = Left[i]

                i += 1

            else:

                array[k] = Right[j]

                j += 1

            k += 1

 

        while i < len(Left):

            array[k] = Left[i]

            i += 1

            k += 1

 

        while j < len(Right):

            array[k] = Right[j]

            j += 1

            k += 1

 

# Print the array

def printarray(array):

    for i in range(len(array)):

        print(array[i], end=" ")

    print()

 

# Driver program

if __name__ == '__main__':

    array = [7, 2, 5, 6, 3, 1, 8, 4]

    print("Orignal Array is: ", array)

 

    Merge_Sort(array)

    print("Sorted array is: ")

    printarray(array)


Output:

Orignal Array is: [7, 2, 5, 6, 3, 1, 8, 4]

Sorted array is:

1 2 3 4 5 6 7 8

 

HISTOGRAM

· A histogram is a visual representation of the Distribution of a Quantitative variable.

· Appearance is similar to a vertical bar graph, but used mainly for continuous distribution

· It approximates the distribution of variable being studied

· A visual representation that gives a discretized display of value counts

 

def histogram(a):

    for i in a:

        sum =''

    while(i>0):

        sum=sum+'#' 

        i=i-1    

    print(sum)    

a=[4,5,7,8,12]    

histogram(a)

Output

****

*****

*******

********

************

 

 

 

 

 

 

 

 

 

Files and exception

A file is some information or data which stays in the computer storage devices. Python gives  you easy ways to manipulate these files. Generally files divide in two categories, text file and binary file. Text files are simple text where as the binary files contain binary data which is only  readable by computer.

· Text files: In this type of file, Each line of text is terminated with a special  character called EOL (End of Line), which is the new line character (‘\n’) in python by default.

· Binary files: In this type of file, there is no terminator for a line and the data is stored after converting it into machine understandable binary language.

 

An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions. In general, when a Python script encounters a situation that it cannot cope with, it raises an exception. An exception is a Python object that represents an error.

Text files: 

We can create the text files by using the syntax:  

Variable name=open (“file.txt”, file mode) 

For ex: f= open ("hello.txt","w+") 

· We declared the variable f to open a file named hello.txt. Open takes 2 arguments, the file that we want to open and a string that represents the kinds of permission or operation we want to do on the file

· Here we used "w" letter in our argument, which indicates write and the plus sign that means it will create a file if it does not exist in library

· The available option beside "w" are "r" for read and "a" for append and plus sign means if it is not there then create it

 

reading and writing files

( Explain File reading, writing. Give example?)

File Operation:

·         Open a file

·         Reading a file

·         Writing a file

·         Closing a file

1.Open ( ) function:

The open() function returns a file handler object for the file name. The open() function is commonly used with two arguments, where the first argument is a string containing the file name to be opened which can be absolute or relative to the current working directory.

The second argument is another string containing a few characters describing the way in which the file will be used as shown in TABLE. The mode argument is optional; r will be used if it is omitted. The file handler itself will not contain any data pertaining to the file.

Syntax:

file_object=open(“file_name” , ”mode”)

 

Example:

fp=open(“a.txt”,”r”)

 

Create a text file fp=open (“text.txt”,”w”)

 

2.Read ( ) function

When you use the open() function a file object is created. Here is the list of methods that can

be called on this object

Syntax: file_handler.read ()

Example:

 Output a.txt

fp=open(“a.txt”,”w”)

print(fp.read()) 

print(fp.read(6)) 

print (fp.readline()) 

print (fp.readline(3)) 

print (fp.readlines())

A file stores related data, 

information, settings or

commands  in secondary

storage device like  magnetic

disk, magnetic tape,  optical

disk, flash memory.

 

 

Reading file using looping:

Reading a line one by one in given file

fp=open(“a.txt”,”r”)

for line in fp:

print(line)

3. Write ( ) function

This method is used to add information or content to existing file.

 Syntax: file_handler.write( )

Example:                                                                                           Output:

 fp=open(“a.txt”,”w”) 

fp.write(“this file is a.txt”) 

fp.write(“to add more lines”) 

fp.close()

a.txt

A file stores related data,  information, settings or commands  in secondary storage device like  magnetic disk, magnetic tape,  optical disk, flash memory. this file is a.txt to  add more lines

 

 

 

 


4. Close ( ) function

Opening files consume system resources, and, depending on the file mode, other programs

may not be able to access them. It is important to close the file once the processing is completed. After the file handler object is closed, you cannot further read or write from the file. Any attempt to use the file handler object after being closed will result in an error.

The syntax for close() function is,

file_handler.close()

For example,

1. >>> file_handler = open("moon.txt","r")

2. >>> file_handler.close()

 

2. Write a program for one file content copy into another file:

source=open(“a.txt”,”r”) 

destination=open(“b.txt”,”w”)

for line in source:

destination.write(line) 

source. close() 

destination.close()

 

Format Operator

The argument of write has to be a string, so if we want to put other values in a file, we have to convert them to strings.

The easiest way to do that is with str:

>>> x = 52

>>> fout.write(str(x))

An alternative is to use the format operator, %. When applied to integers, % is the modulus operator. But when the first operand is a string, % is the format operator. The first operand is the format string, which contains one or more format sequences, which specify how the second operand is formatted. The result is a string.

 

For example, the format sequence '%d' means that the second operand should be formatted

as a decimal integer:

>>> camels = 42

>>> '%d' % camels

'42'

The result is the string '42', which is not to be confused with the integer value 42.

 

A format sequence can appear anywhere in the string, so you can embed a value in a sentence:

>>> 'I have spotted %d camels.' % camels

'I have spotted 42 camels.'

If there is more than one format sequence in the string, the second argument has to be a tuple. Each format sequence is matched with an element of the tuple, in order.

The following example uses '%d' to format an integer, '%g' to format a floating-point number, and '%s' to format a string:

>>> 'In %d years I have spotted %g %s.' % (3, 0.1, 'camels')

'In 3 years I have spotted 0.1 camels.'

The number of elements in the tuple has to match the number of format sequences in the string. Also, the types of the elements have to match the format sequences:

>>> '%d %d %d' % (1, 2)

TypeError: not enough arguments for format string

>>> '%d' % 'dollars'

TypeError: %d format: a number is required, not str

In the first example, there aren’t enough elements; in the second, the element is the wrong type.

 

Format character      Description

%c                               Character

%s                               String formatting

%d                              Decimal integer

%f                                Floating point real number

 

Filenames and Paths

Files are organized into directories (also called “folders”). Every running program has a “current directory”, which is the default directory for most operations. For example, when you open a file for reading, Python looks for it in the current directory.

The os module provides functions for working with files and directories (“os” stands for “operating system”).

os.getcwd returns the name of the current directory:

>>> import os

>>> cwd = os.getcwd()

>>> cwd

'/home/dinsdale'

cwd stands for current working directory.

The result in this example is /home/dinsdale, which is the home directory of a user named dinsdale.

A string like '/home/dinsdale' that identifies a file or directory is called a path.

A simple filename, like memo.txt, is also considered a path, but it is a relative path because it relates to the current directory. If the current directory is /home/dinsdale, the filename memo.txt would refer to /home/dinsdale/memo.txt.

os.path.abspath

A path that begins with / does not depend on the current directory; it is called an absolute path. To find the absolute path to a file, you can use os.path.abspath:

>>> os.path.abspath('memo.txt')

'/home/dinsdale/memo.txt'

os.path.exists

os.path provides other functions for working with filenames and paths. For example, os.path.exists checks whether a file or directory exists:

>>> os.path.exists('memo.txt')

True

os.path.isdir

If it exists, os.path.isdir checks whether its a directory:

>>> os.path.isdir('memo.txt')

False

>>> os.path.isdir('/home/dinsdale')

True

Similarly, os.path.isfile checks whether its a file.

os.listdir(cwd)

os.listdir returns a list of the files (and other directories) in the given directory:

>>> os.listdir(cwd)

['music', 'photos', 'memo.txt']

To demonstrate these functions, the following example walks through a directory,

prints the names of all the files, and calls itself recursively on all the directories:

 

def walk(dirname):

    for name in os.listdir(dirname):

        path = os.path.join(dirname, name)

        if os.path.isfile(path):

            print(path)

        else:

            walk(path)

 

os.path.join takes a directory and a filename and joins them into a complete path.

 

COMMAND LINE ARGUMENTS

( Explain command line arguments. Give example?)

· The command line argument is used to pass input from the command line to your program when they are started to execute. 

·Handling command line arguments with Python need sys module.

· sys module provides information about constants, functions and methods of the python interpreter. argv[ ] is used to access the command line argument.

· The argument list starts from 0. sys.argv[0]= gives file name sys.argv[1]=provides access to the first input

 

Errors and exception:

Errors

Errors are the mistakes in the program also referred as bugs. They are almost always the fault of the programmer. The process of finding and eliminating errors is called debugging. Errors can be classified into three major groups:

1. Syntax errors 

2. Runtime errors 

3. Logical errors 

Syntax errors

·         Syntax errors are the errors which are displayed when the programmer do mistakes when writing a program.

·         When a program has syntax errors it will not get executed.

·         Common Python syntax errors include:

1. leaving out a keyword 

2. putting a keyword in the wrong place 

3. leaving out a symbol, such as a colon, comma or brackets 

4. misspelling a keyword 

5. incorrect indentation 

6. empty block

Runtime errors:

· If a program is syntactically correct – that is, free of syntax errors – it will be run by the Python interpreter. 

·However, the program may exit unexpectedly during execution if it encounters a runtime error.

· When a program has runtime error I will get executed but it will not produce output.

Common Python runtime errors include:

1. division by zero

2. performing an operation on incompatible types

3. using an identifier which has not been defined

4. accessing a list element, dictionary value or object attribute which doesn’t exist

5. trying to access a file which doesn’t exist

Logical errors:

· Logical errors are the most difficult to fix. 

· They occur when the program runs without crashing, but produces an incorrect result.

· Common Python logical errors include:

1. using the wrong variable name 

2. indenting a block to the wrong level 

3. using integer division instead of floating-point division 

4. getting operator precedence wrong 

5. making a mistake in a Boolean expression

 

Exceptions:( Handling exceptions)

(Define Exception and explain types of exception?)

·         An exception(runtime time error)is an error, which occurs during the execution of a program that disrupts the normal flow of the program's instructions. 

·         When a Python script raises an exception, it must either handle the exception immediately otherwise it terminates or quit.

Exception Handling:

(Explain Exception Handling mechanism in python?)

· Exception handling is done by try and except  block.

· Suspicious code that may raise an exception, this kind of code will be placed in try block.

· A block of code which handles the problem is placed in except block.

Catching Exceptions:

1. try…except

2. try…except… finally

try ... except 

· The try statement works as follows:-

· First, the try clause (the statement(s) between the try and except keywords) is  executed.

· If no exception occurs, the except clause is skipped and execution of the try statement is finished.

· If an exception occurs during execution of the try clause, the rest of the clause is  skipped. Then if its type matches the exception named after the except keyword,  the except clause is executed, and then execution continues after the try statement.

Syntax

try:    

code that create exception

except:    

exception handling statement

Example:

try:    

    age=int(input("enter age:"))    

    print("ur age is:",age)

except:    

    print("enter a valid age")

Output

enter age:8

ur age is: 8

enter age:f

enter a valid age

 

Try –Except-Finally

·         A finally clause is always executed before leaving the try statement, whether an  exception has occurred or not.

·         The finally clause is also executed “on the way out” when any other clause of the try statement is left via a break, continue or return statement.

Syntax

try:

statements

except:

statements

finally:

statements

Example

X=int(input(“Enter the value of X”)) 

Y=int(input(“Enter the value of Y”))

try:

result = X / ( X – Y )

except Zero DivisionError:

print(“Division by Zero”)

else:

print(“result=”.result)

finally:

print (“executing finally clause”)

Raising Exceptions

In Python programming, exceptions are raised when corresponding errors occur at run time, but we can forcefully raise it using the keyword raise.

Syntax: >>> raise error name

modules

(Explain about modules with example?)

Module is a logical group of functions , classes, variables in a single python file saved with .py extension. In other words, we can also say that a python file is a module.

Name of the module is the same as the name of a file.

It allows us to logically arrange related code and makes the code easier to understand  and use.

 

Example 1: Creating module named series.py

Our module is successfully created. Now let us test our module by importing in some other file and check whether it is working or not. For verifying that, in a new file, two steps are needed to be done1.

 Import the module we have created to make it accessible

2. Call the functions of that module with module name and a dot (.) symbol.

Example 2: Accessing function in module created in Example 1.

Importing a module

Importing is the process of loading a module in other modules or files. It is necessary to import a module before using its functions, classes or other objects. It allows users to reference its objects. There are various ways of importing a module.

1. using import statement

2. using from import statement

3. using from import * statement

1. Importing Complete module

In this method, we can import the whole module all together with a single import statement. In this process, after importing the module, each function (or variable, objects etc.) must be called by the name of the module followed by dot (.) symbol and name of the function.

Syntax of function calling within module

import module

module.function_name()

For example, let us import the built-in module random, and call its function randint(), which generates a random integer between a range given by user.

This can be done by running the code below in console window directly or in a python file.

In this method, other functions or objects present in module random can be called similarly.

Here,random () is function present within module random.

2. Importing using from import statement

In this method of importing, instead of importing the entire module function or objects, only a particular object needed can be imported. In this method, objects can be directly accessed with its name.

Let us take an example of another module called math. This module contains various functions and variables. One such variable is pi, which contains value of π.

In this example, only a variable called pi is imported from math module, hence it can be directly accessed with its name. In this case, module name cannot be used for calling its objects, doing this will show NameError. Also other functions within the module math cannot be accessed, since only one variable pi is imported. You will be able to access them only after importing them individually with from import statement.

3.Importing entire module using from import *

This method can be used to import the entire module using from import * statement. Here,*represents all the functions of a module. Like previous method, an object can be accessed directly with its name.

Built-in Modules in python:

Random:

Math:

OS Module :

The OS module in python provide function for interacting with operating  system.

To access the OS module have to import the OS module in our program

Date/Time

This module helps in retrieving date and time properties of files and directories. These properties included when they are created, accessed etc. They also display current date and time

# write a python program to display date

import datetime

a=datetime.date(2000,9,18)

print(a)

Output:

2000-09-18

 

# write a python program to display time

import datetime

a=datetime.time(5,3)

print(a)

Output:

05:03:00

 

The dir( ) Function

The dir() built-in function returns a sorted list of strings containing the names defined by a module.

The list contains the names of all the modules, variables and functions that are defined in a module. Following is a simple example −

#!/usr/bin/python

# Import built-in module math

import math

content = dir(math)

print content

When the above code is executed, it produces the following result −

['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan',

'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp',

'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log',

'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh',

'sqrt', 'tan', 'tanh']

Here, the special string variable __name__ is the module's name, and __file__ is the filename from which the module was loaded.

 

The Pickle Module

Python provides a standard module called pickle. This is an amazing module that can take almost any Python object and convert it to a string representation; this process is called pickling. Reconstructing the object from the string representation is called unpickling. Between pickling and unpickling, the string representing the object may have been stored in a file or data or sent over a network connection to some distant machine.

If you have an object x and a file object f, which has been opened for writing, the simplest way to pickle the object is,

pickle.dump(x, f)

The dump() method writes a pickled representation of object x to the open file object f. If f is a file object, which has been opened for reading, then the simplest way to unpickle the object is,

x = pickle.load(f)

The load() method reads a pickled object representation from the open file object f and return the reconstituted object hierarchy specified therein.

Pickling is the standard way to make Python objects that can be stored and reused by other programs or by a future invocation of the same program; the technical term for this is “a persistent object.”

Because pickle is so widely used, many authors who write Python extensions must ensure that all data types are properly pickled and unpickled.

Write Python Program to Save Dictionary in Python Pickle

1. import pickle

2. def main():

3.     bbt = {'cooper': 'sheldon'}

4.    with open('filename.pickle', 'wb') as handle:

5.        pickle.dump(bbt, handle)

6.    with open('filename.pickle', 'rb') as handle:

7.        bbt = pickle.load(handle)

8.        print(f"Unpickling {bbt}")

9. if __name__ == "__main__":

10.    main()

Output

Unpickling {'cooper': 'sheldon'}

 

PACKAGES

(What is a package in python? Give examples.?)

Ø  A package is a directory which contains multiple python modules.

Ø  It is used to group multiple related python modules together.

Ø  A python package in addition to modules must contain a file called __init__.py. This file may be empty or contains data like other modules of package.

File __init__.py

It is a file that makes the package importable. When a package is imported in a script, this file is automatically executed. It initializes variables, objects and makes the functions in the package accessible. 

Let us create a package named pack and within this package create two modules first.py and second.py .

The __init__.py file created is empty. Module one contains function abc() and module two contains function xyz().  Packages can be imported in the same way as we import modules.  The various ways in which we can import from package are-

 

importpack.first 

pack.first.abc() 

 

from  pack  import first 

first.abc() 

 

from  pack.first import abc 

abc() 

 

There are more methods to import. We have used * to import all the functions from a module in the previous section. This method can also be used here. But by default importing package modules using * will show error.

This can be made possible using __all__ variable.  This variable when added to __init__.py file, can make modules within package accessible outside using from import * statement.

Hence, we need to add __all__ statement in __init__.py  

__all__= [‘ first ’] 

The above statement makes module first.py accessible using from import * statement. 

 

Now another way to import the module is given below:

Syntax to import using  from import *

from  pack import * 

first.abc() 

Here, we can clearly see that first.py module is now accessible, since we have added it to __all__ variable. But second.py module is not accessible simultaneously, since it was not added to __all__ attribute in __init__.py.

 

ILLUSTRATIVE PROGRAMS

1. WORD COUNT

num_words=0

with open("E:\\sample.txt",'r') as f:

    for line in f:

        words=line.split()

        num_words+=len(words)

print("Number of words:")

print(num_words)

 

Output:

Number of words:

9

2.COPY THE CONTENTS OF A FILE

 

with open("hello.txt") as f:

    with open("copy.txt","w")as f1:

        for line in f:

            f1.write(line)

 

No comments:

Post a Comment