192601 - python programming theory - drmrk.gnomio.com

90
1 PYTHON PROGRAMMING UNIT-I Short History of Python The Python programming language was developed in the late 1980s by Dutch programmer Guido van Rossum while working at CWI (the Centrum voor Wiskunde en Informatica in Amsterdam, Netherlands). The language was not named after the large snake species but rather after the BBC comedy series Monty Python’s Flying Circus. Guido van Rossum happens to be a fan. Just like the Linux OS, Python eventually became an open source software development project. However, Guido van Rossum still has a central role in deciding how the language is going to evolve. Python is a general-purpose language that was specifically designed to make programs very readable. Python also has a rich library making it possible to build sophisticated applications using relatively simple-looking code. Setting Up the Python Development Environment: versions of Python in use. Python 3 series is a new version of Python that fixes some less-than-ideal design decisions made in the early develop- ment of the Python language. IDE installation using the standard Python development kit that includes the IDLE IDE. You may download the kit (for free) from: http://python.org/download/ Python interactive shell window / Shell: To get started with Python, you need to open a Python interactive shell window. The IDLE interactive shell included with the Python IDE is shown in Figure. Python IDLE At the >>> prompt, you can type single Python instructions. The instruction is executed by the Python interpreter when the Enter/Return key is pressed.

Upload: others

Post on 19-Mar-2022

3 views

Category:

Documents


0 download

TRANSCRIPT

1

PYTHON PROGRAMMING

UNIT-I Short History of Python

The Python programming language was developed in the late 1980s by Dutch programmer Guido van Rossum while working at CWI (the Centrum voor Wiskunde en Informatica in Amsterdam, Netherlands).

The language was not named after the large snake species but rather after the BBC comedy series Monty Python’s Flying Circus. Guido van Rossum happens to be a fan.

Just like the Linux OS, Python eventually became an open source software development project. However, Guido van Rossum still has a central role in deciding how the language is going to evolve.

Python is a general-purpose language that was specifically designed to make programs very readable.

Python also has a rich library making it possible to build sophisticated applications using relatively simple-looking code.

Setting Up the Python Development Environment:

versions of Python in use. Python 3 series is a new version of Python that fixes some less-than-ideal design decisions made in

the early develop- ment of the Python language.

IDE installation using the standard Python development kit that includes the IDLE IDE. You may download the kit (for free) from:

http://python.org/download/ Python interactive shell window / Shell:

To get started with Python, you need to open a Python interactive shell window. The IDLE interactive shell included with the Python IDE is shown in Figure.

Python IDLE

• At the >>> prompt, you can type single Python instructions.

• The instruction is executed by the Python interpreter when the Enter/Return key is pressed.

2

• The interactive shell expects the user to type a Python instruction. • IDLE stands for integrated development learning environment • What is python shell? • Python shell is used to execute a single python command and gives result. • It is also called as python interactive shell or python interpreter.

Computational Thinking Computational thinking is a term used to describe the intellectual approach through which natural or artificial processes or tasks are understood and described as computational processes. To model the relevant aspects of the task and describe the task as an algorithm, we must understand the task from a “computational” perspective. A Sample Problem: Example: A = 10 B = 5 Find out the greatest among A and B If(A>B) then print A is greater else Print B is greater What is mean by algorithm? Algorithm is a step by step approach to write any program. What is Flow chart? Flow chart is a diagrammatical representation of an algorithm. Computational thinking :Biggest among two numbers- Algorithm:

1. Start the program 2. Get the input of A and B ; A = 10, B=5 3. Compare A and B ; if(A>B) 4. Print A is greater 5. Print B is greater 6. Stop the program.

Computational thinking: Biggest among two numbers- Flow chart:

3

Example:2 for Computational Thinking:

We are interested in purchasing about a dozen prize-winning novels from our favourite online shopping web site.

The thing is, we do not want to pay full price for the books. We would rather wait and buy the books on sale. More precisely, we have a target price for each book and will buy a book only when its sale price is below the target.

So, every couple of days, we visit the product web page of every book on our list and, for each book, check whether the price has been reduced to below our target. Algorithm: a. We compare numbers CURR and TARG b. We find the address of product I in list Addresses c. We search the web page content for a price d. We create a sequence 0, 1, 2, ..., N-1 from integer N Algorithm in detail:

1. Let N be the number of products in list Addresses.

For every product I = 0, 1, ..., N-1, execute these statements: 2. Let ADDR be the address in list Addresses for product I. 3. Download the web page whose address is ADDR and

let PAGE be the content of this web page 4. Find in PAGE the current price of product I and

let CURR be this value 5. Let TARG be the product I target price from list Targets

If CURR < TARG: Print ADDR

Expressions, Variables, and Assignments Algebraic Expressions and Functions

4

At the interactive shell prompt >>> , we type an algebraic expression, such as 3 + 7, and hit the Enter key on the keyboard to view the result of evaluating the expression:

>>> 3 + 7 10 Expressions that use different algebraic operators:

>>> 3 * 2 6

>>> 5 / 2 2.5 >>> 4 / 2 2.0

In the first two expressions, integers are added or multiplied and the result is an integer. In the third expression, an integer is divided by another and the result is shown in decimal point notation. The rule in Python is to return a number with a decimal point and a fractional part, even when the result is an integer. This is illustrated in the last expression, where integer 4 is divided by 2 and the result shown is 2.0 rather than 2.

Values without the decimal point are said to be of type integer or simply int. Values with decimal

points and fractional parts are said to be of type floating point or simply float. Let us continue evaluating expressions using values of both types: Ex: >>> 2 * 3 + 1 Output: 7 Ex: >>> (3 + 1) * 3 Output: 12 Ex: >>> 4.321 / 3 + 10 Output: 11.440333333333333 Ex: >>> 4.321 / (3 + 10) Output: 0.3323846153846154 Multiple operators are used in these expressions; the order of operations should be evaluated. The

standard algebra precedence rules apply in Python: Multiplication and division take precedence over addition and subtraction and in algebra,

parentheses are used when we want to explicitly specify the order in which operations should take place. If all else fails, expressions are evaluated from using the left to-right evaluation rule. This last rule is used in the next expression, where the addition is executed after the subtraction:

>>> 3 - 2 + 1 2

5

All the expressions we have evaluated so far are plain algebraic expressions involving number values (of type int or type float), algebraic operators (such as +, -, /, and *), and parentheses. When we hit the Enter key, the Python interpreter will read the expression and evaluate it in a way that we expect. Example of an algebraic expression:

>>> 3 3

Python evaluates expression 3 to . . . 3. The two types of number values, int and float, have different properties. For example, when two int

values are added, subtracted, or multiplied, the result is an int value. If at least one float value appears in the expression, the result is always a float value. Note that a float value is also obtained when two integer values (e.g., 4 and 2) are divided.

Other algebraic operators Exponentiation operator **:

>>> 2**3 8 >>> 2**4 16 So, xy is computed using the Python expression x**y. In order to obtain the integer quotient and

the remainder when two integer values are divided, operators // and % are used. The // operator in expression a//b returns the integer quotient obtained when integer a is divided by integer b. The % operator in expression a%b computes the remainder obtained when integer a is divided by integer b.

For example: >>> 14 // 3 4 >>> 14 % 3 2 In the first expression, 14 // 3 evaluates to 4 because 3 goes into 14 four times. In the second

expression, 14 % 3 evaluates to 2 because 2 is the remainder when 14 is divided by 3. Python also supports mathematical functions that can be used in an algebra. In algebra, the notation

f(x) = x + 1 is used to define function f() that takes an input, denoted by x, and returns a value, which is x+1. In order to use this function on input value 3, for example, use the notation f(3), which evaluates to 4. For example, the Python function abs() can be used to compute the absolute value of a number value:

>>> abs(-4) 4 >>> abs(4) 4 >>> abs(-3.2) 3.2 Some other functions in Python are min() and max(), which return the minimum or maximum,

respectively, of the input values: Example: >>> min(6, -2) -2 >>> max(6, -2) 6 >>> min(2, -4, 6, -2)

6

-4 >>> max(12, 26.5, 3.5) 26.5

Boolean Expressions and Operators Algebraic expressions evaluate to a number, whether of type int or float or one of the other number

types that Python supports. In an algebra class, expressions other than algebraic expressions are also common. For example, the expression 2 < 3 does not evaluate to a number; it evaluates to either True or False (True in this case). Python can also evaluate such expressions, which are called Boolean expressions.

Boolean expressions are expressions that evaluate to one of two Boolean values: True or False. These values are said to be of Boolean type, a type just like int and float and denoted bool in Python. Comparison operators (such as < or >) are commonly used operators in Boolean expressions. For example:

>>> 2 < 3 True >>> 3 < 2 False >>> 5 - 1 > 2 + 1 True The last expression illustrates that algebraic expressions on either side of a comparison operators

are evaluated before the comparison is made. Algebraic operators take precedence over comparison operators. For example, in 5-1> 2+1, the operators - and + are evaluated first, and then the comparison is made between the resulting values.

In order to check equality between values, the comparison operator == is used. Note that the operator has two = symbols, not one. For example:

>>> 3 == 3 True >>> 3 + 5 == 4 + 4 True >>> 3 == 5 – 3 False There are a few other logical comparison operators: >>> 3 <= 4 True >>> 3 >= 4 False >>> 3 != 4 True >>>3==4 False The Boolean expression 3 <= 4 uses the <= operator to test whether the expression on the left (3) is

less than or equal to the expression of the right (4). The Boolean expression evaluates to True. The >= operator is used to test whether the operand on the left is greater than or equal to the operand on the right. The expression 3!= 4 uses the != (not equal) operator to test whether the expressions on the left and right evaluate to different values.

Just as algebraic expression can be combined into larger algebraic expression, Boolean expressions can be combined together using Boolean operators and , or , and not to form larger Boolean expressions. The and operator applied to two Boolean expressions will evaluate to True if both expressions evaluate to True; if either expression evaluates to False, then it will evaluate to False:

>>> 2 < 3 and 4 > 5 False >>> 2 < 3 and True

7

True

Both expressions illustrate that comparison operators are evaluated before Boolean operators. This is because comparison operators take precedence over Boolean operators.

The or operator applied to two Boolean expressions evaluates to False only when both expressions are false. If either one is true or if both are true, then it evaluates to True.

>>> 3 < 4 or 4 < 3 True >>> 3 < 2 or 2 < 1 False The not operator is a unary Boolean operator, which means that it is applied to a single Boolean

expression (as opposed to the binary Boolean operators and and or). It evaluates to False if the expression is true or to True if the expression is false.

>>> not (3 < 4) False

Variables and Assignments Variables:

We assign names to values, those names are called variables. The value may change during the execution of program is called Variable. Example: a, b, value1 For example, value 3 may be assigned to variable x in an algebra problem as follows: x = 3.

A value can be assigned to a variable in python: >>> x = 4

The statement x=4 is called an assignment statement. Assignment Statements: The general format of an assignment statement is:

<variable>=<expression> Ex: sum=a+b/c*d x=a<b y=a**b z=abs(-10) x=min(2, 3, -10, 5) x= max(-99, 0, 25,3) An expression we refer to as <expression>lies on the right-hand side of the = operator; it can be an

algebraic, Boolean, or other kind of expression. On the left-hand side is a variable referred to as <variable>.

8

The assignment statement assigns to <variable> the value that <expression> evaluates to. In the last example, x is assigned value 4.

Once a value has been assigned to a variable, the variable can be used in a Python expression: >>> x 4

When Python evaluates an expression containing a variable, it will evaluate the variable to its assigned value and then perform the operations in the expression:

>>> 4 * x 16

An expression involving variables may appear on the right side of an assignment statement: >>> counter =4*x

In statement counter = 4 * x, x is first evaluated to 4, then the expression 4*4 is evaluated to 16, and then 16 gets assigned to variable counter:

>>> counter 16

The value of a variable can change. The same is true with Python variables. For example, suppose that the value of variable x is initially 4:

>>> x 4

Now let’s assign value 7 to variable x: >>> x = 7 >>> x 7

So the assignment statement x=7 changed the value of x from 4 to 7. Assignment and Equality Operator

We distinguish the assignment statement = and the equality operator ==. This is an assignment statement that assigns 7 to variable x:

>>> x = 7 The following is a Boolean expression that compares the value of variable x with number 7 and returns True if they are equal:

>>> x == 7 True

The expression evaluates to True because variable x has value 7. Variable Names

The characters making up a variable name can be lowercase and uppercase letters from the alphabet (a through z and A through Z), the underscore character (_), and, except for the first character, digits 0 through 9: • myList and _list are OK, but 5 list is not.

• list6 and l_2 are OK, but list-3 is not. • mylist and myList are different variable names.

Even when a variable name is “legal” (i.e., follows the rules), it might not be a “good” name. Here are some general good names:

• A name should be meaningful: Name price is better than name p. • For a multiple-word name, use either the underscore as the delimiter (e.g., temp_var and interest_rate) or use camelCase capitalization (e.g., tempVar, TempVar, interestRate or InterestRate); pick one style and use it consistently throughout your program. • Shorter meaningful names are better than longer ones.

9

The below names are used as reserved keywords of the Python language. We cannot use them other than as Python commands. Strings

The Python string type, denoted by str, is used to represent and manipulate text data or, in other words, a sequence of characters, including blanks, punctuation, and various symbols. A string value is represented as a sequence of characters that is enclosed within quotes:

>>> 'Hello, World!' 'Hello, World!' >>> s ='hello' >>> s 'hello' The first expression, 'Hello, world!', is an expression that contains just one string value and it

evaluates to itself, just as expression 3 evaluates to 3. The statement s = 'hello' assigns string value 'hello' to variable s. String Operators

Python provides operators to process text (i.e., string values). Like numbers, strings can be compared using comparison operators: ==, !=, < , >, and so on. Operator ==, for example, returns True if the strings on either side of the operator have the same value:

>>> s =='hello' True >>> t ='world' >>> s != t True >>> s == t False

While == and != test whether two strings are equal or not, the comparison operators < and > compare strings using the dictionary order:

>>> s < t True >>> s > t False

The + operator, when applied to two strings, evaluates to a new string that is the concatenation (i.e., the joining) of the two strings:

>>> s + t 'helloworld' >>> s +''+t 'hello world'

In the second example, the names s and t are evaluated to the string values 'hello' and 'world', respectively, which are then concatenated with the single blank space string ''. When a string gets multiplied by an integer, then

>>> 3 *'A' 'AAA' >>> 'hello ' *2 'hello hello ' >>> 30 * '-' '------------------------------'

Multiplying a string s by an integer k gives us a string obtained by concatenating k copies of string s. Multiplying string '-' 30 times. With the in operator, we can check whether a character appears in a string:

>>> s ='hello' >>> 'h' in s True >>> 'g' in s False

Usage and explanation of String operators Usage Explanation

10

x in s True if string x is a substring of string s, and false otherwise. x not in s False if string x is a substring of string s, and true otherwise. s+t Concatenation of string s and string t. s*n , n*s Concatenation of n copies of s. s[i] Character of string s at index i. len(s) Length of string s.

The in operator also can be used to check whether a string appears in another:

>>> 'll' in s True

Since 'll' appears in string s, we say that 'll' is a substring of s. The length of a string can be computed using the len() function:

>>> len(s) 5

Indexing Operator The individual characters of a string can be accessed using the indexing operator []. We define the

concept of an index first. The index of a character in a string is the character’s offset (i.e., position in the string) with respect to the first character. The first character has index 0, the second has index 1 (because it is one away from the first character), the third character has index 2, and so on. The indexing operator [] takes a non-negative index i and returns a string consisting of the single character at index i.

>>> s[0] 'h' >>> s[1] 'e' >>> s[4] 'o'

Negative indexes may be used to access the characters from the back (right side) of the string. For example, the last character and second to last can be retrieved using negative indexes -1 and -2, respectively.

>>> s[-1] 'o' >>> s[-2] 'l'

Lists In Python, lists are usually stored in a type of object called a list. A list is a sequence of objects. The

objects can be of any type: numbers, strings, even other lists. For example, we assign the variable pets as the list of strings representing several pets:

>>> pets = ['goldfish', 'cat', 'dog'] The variable pets evaluates to the list:

>>> pets ['goldfish', 'cat', 'dog'] In Python, a list is represented as a comma-separated sequence of objects enclosed within square

brackets. An empty list is represented as []. Lists can contain items of different types. For example, >>> things = ['one', 2, [3, 4]]

has three items: the first is string 'one', the second is integer 2, and the third item is list [3, 4]. List Operators

For example, the items in the list may be accessed individually using the indexing operator, just as individual characters can be accessed in a string:

>>> pets[0] 'goldfish'

11

>>> pets[2] 'dog'

Negative indexes can be used too: >>> pets[-1] 'dog'

Usage and explanation of List operators

Usage Explanation x in lst True if object x is in list lst, false otherwise.

x not in lst False if object x is in list lst, true otherwise. lstA + lstB Concatenation of lists lstA and lstB. lst * n , n * lst Concatenation of n copies of list. lst lst[i] Item at index i of list lst. len(lst) Length of list lst. min(lst) Smallest item in list lst. max(lst) Largest item in list lst. sum(lst) Sum of items in list lst

The length of a list (i.e., the number of items in it) is computed using function len():

>>> len(pets) 3

Like strings, lists can be “added,” meaning that they can be concatenated. They can also be “multiplied” by an integer k, which means that k copies of the list are concatenated:

>>> pets + pets ['goldfish', 'cat', 'dog', 'goldfish', 'cat', 'dog'] >>> pets * 2 ['goldfish', 'cat', 'dog', 'goldfish', 'cat', 'dog']

If we want to check whether string 'rabbit' is in the list, we can use the in operator in a Boolean expression that evaluates to True if string 'rabbit' appears in list pets:

>>> 'rabbit' in pets False >>> 'dog' in pets True

We include in the table functions min(), max(), and sum(), which can take a list as input and return the smallest item, the largest item, or the sum of the items, respectively, in the list:

>>> lst = [23.99, 19.99, 34.50, 120.99] >>> min(lst) 19.99 >>> max(lst) 120.99 >>> sum(lst) 199.4699999999999

Lists Are Mutable, Strings Are Not

An important property of lists is that they are mutable. For example, suppose that we want to be more specific about the type of cat in list pets. We would like pets[1] to evaluate to 'cymric cat' instead of just plain 'cat'. To do this, we assign 'cymric cat' to pets[1]:

>>> pets[1] = 'cymric cat'

12

>>> pets ['goldfish', 'cymric cat', 'dog'] So, the list no longer contains the string 'cat' at index 1; instead, it contains the string 'cymric cat'. While lists are mutable, strings are not. It means that, we cannot change the individual characters of a string value. For example, suppose that we misspelled the type of cat:

>>> myCat = 'cymric bat' We would like to correct the mistake by changing the character at index 7 from a 'b' to a 'c'.

>>> myCat[7] = 'c' List Methods We have seen functions that operate on lists such as, for example, the min() function:

>>> numbers = [6, 9, 4, 22] >>> min(numbers) 4

In expression min(numbers), we say that function min() is called with one input argument, the list numbers. There are also functions that are called on lists. For example, to add 'guinea pig' to list pets, we would call function append() on list pets as follows:

>>> pets.append('guinea pig') >>> pets ['goldfish', 'cymric cat', 'dog', 'guinea pig']

Let’s do this again and add another 'dog' to list pets: >>> pets.append('dog') >>> pets ['goldfish', 'cymric cat', 'dog', 'guinea pig', 'dog']

The function append() is a list function. Another example of a list method is the count() method.

When called on a list with an input argument, it returns the number of times the input argument appears in the list.

>>> pets.count('dog') 2 We say that method count() is called on list pets (with input argument 'dog'). To remove the first occurrence of 'dog', we can use the list method remove().

>>> pets.remove('dog') >>> pets ['goldfish', 'cymric cat', 'guinea pig', 'dog']

The list method reverse() reverses the order `of the objects: >>> pets.reverse() >>> pets ['dog', 'guinea pig', 'cymric cat', 'goldfish']

Some commonly used list methods We can view a listing of all list methods in the interactive shell using the help() documentation function:

>>> help(list) Help on class list in module built-ins: Usage Explanation lst.append(item) Adds item to the end of list lst. lst.count(item) Returns the number of occurrences of item in list lst. lst.index(item) Returns the index of the first occurrence of item in list lst. lst.insert(index, item) Inserts item into list just before index index. lst.pop() Removes last item in the list. lst.remove(item) Removes first occurrence of item in the list. lst.reverse() Reverses the order of items in the list. lst.sort() Sorts the list.

13

The sort() method sorts the items in the list in increasing order, using the ordering that “naturally” applies to the objects in the list.

>>> pets.sort() >>> pets ['cymric cat', 'dog', 'goldfish', 'guinea pig']

A list of numbers would be sorted using the usual increasing number order:

>>> lst = [4, 2, 8, 5] >>> lst.sort() >>> lst [2, 4, 5, 8]

Objects and Classes In Python, every value, whether a simple integer value (such as 3) or a more complex value (such as the string 'Hello, World!' or the list ['hello', 4, 5]) is stored in memory as an object. Object is a container for the value that sits inside your computer’s memory.

Objects are containers for values, integer or other, that hide the complexity of integer storage and processing and provide the programmer with the only information that the value of the object and what kind of operations can be applied to it. Object Type

Every object has associated with it a type and a value. We illustrate this in the below figure with four objects: an integer object with value 3, a floating point object with value 3.0, a string object with value 'Hello World', and a list object with value [1, 1, 2, 3, 5, 8].

An object’s type indicates what kind of values the object can hold and what kind of operations can

be performed on the object. The types include the integer (int), floating point (float), Boolean (bool), string (str), and list (list) types.

The Python type() function can be used to determine an object’s type: >>> type(3) <class 'int'> >>> type(3.0) <class 'float'> >>> type('Hello World') <class 'str'> >>> type([1, 1, 2, 3, 5, 8]) <class 'list'>

When used on a variable, the type() function will return the type of the object the variable refers to: >>> a = 3 >>> type(a) <class 'int'>

Variables Do Not Have a Type A variable is just a name. Only the object it refers to has a type. >>> type(a) <class 'int'>

14

It really means that the object that variable a currently refers to is of type integer. We emphasize currently because the type of object that a refers to may change. For example, if we assign 3.0 to a:

a = 3.0 then a will refer to a float value: >>> type(a) <class 'float'> Python programming language is said to be object-oriented because values are always stored in

objects. In programming languages other than Python, values of certain types are not stored in abstract entities such as objects but explicitly in memory. The term class is used to refer to types whose values are stored in objects. Because every value in Python is stored in an object, every Python type is a class. Valid Values for Number Types

Every object has a value that must be legal for the object’s type. For example, an integer object can have value 3 but not 3.0 or 'three'. The integer values can be arbitrarily large. For example, we can create an integer object whose value is 21024:

>>>x=2**1024 >>>x 17976931348623159077293051907890247336179769789423065727343008 ... 7163350510684586298239947245938479716304835356329624224137216 Actually, there is a limit to how large the value stored in an integer object can be: The value is

limited by the available computer memory. This is simply because it is not possible to store an integer value that has more digits than can be stored in the computer memory.

The Python floating point (float) type is used to represent real numbers as fractions with finite decimal representations:

>>> pi = 3.141592653589793 >>> 2.0**30 1073741824.0 Operators for Number Types Python provides operators and built-in mathematical functions like abs() and min() to construct

algebraic expressions. The below table list the arithmetic expression operators available in Python. Operation Description Type (if x and y are integers) x+y Sum ` Integer x-y Difference Integer x*y Product Integer x/y Division Float x // y Integer division Integer x%y Remainder of x // y Integer -x Negative x Integer abs(x) Absolute value of x Integer x**y x to the power y Integer For every operation other than division (/), the following holds: If both operands x and y (or just x for unary operations - and abs()) are integers, the result is an integer. If one of the operands is a float value, the result is a float value. For division (/), the result is a float value.

Comparison operators are used to compare values. There are six comparison operations in Python, as shown in Table.

Operation Description < Less than

15

<= Less than or equal > Greater than >= Greater than or equal == Equal != Not equal

Example:

>>> 3 <= 3 < 4 True Precedence Rules

The operator precedence rules in Python are shown in below Table.

Operator Description [expressions...] List definition x[], x[index:index] Indexing operator ** Exponentiation +x, -x Positive, negative signs *, /, //, % Product, division, integer division, remainder +, - Addition, subtraction in, not in,<, <=, >, >=, <>, !=, == Comparisons, including membership and identity tests not x Boolean NOT and Boolean AND or Boolean OR The order in which operators are evaluated is defined either explicitly using parentheses or

implicitly using either the operator precedence rules or the left-to-right evaluation rule if the operators have the same precedence.

Example: >>> 2 - 3 + 1 0

Creating Objects

To create an integer object with value 3 (and assign it to variable x), we can use this statement: >>> x = 3

Note that the type of the integer object that is created is not explicitly specified. Python also supports a way to create objects that makes the object type explicit:

>>> x = int(3) >>> x 3 The function int() is called a constructor; it is used to explicitly instantiate an integer object. The

value of the object is determined by the function argument: The object created with int(3) has value 3. If no argument is given, a default value is given to the object.

>>> x = int() >>> x 0 So, the default value for integers is 0. The constructor functions for the floating point, list, and string

types are float(), list(), and str(), respectively. We illustrate their usage with no argument to determine the default values for those types. For float objects, the default value is 0.0:

>>> y = float() >>> y 0.0

The default values for strings and lists are, respectively, ' '(the empty string) and [ ] (the empty list): >>> s = str() >>> s ' '

16

>>> lst = list() >>> lst [ ]

Implicit Type Conversions If an algebraic or logical expression involves operands of different types, Python will convert each

operand to the type that contains the others. For example, True is converted to 1 before integer addition is executed to give an integer result:

>>> True + 5 6 The reason for this is that the Boolean type is a “subtype” of the integer type, as illustrated in below

figure. Boolean values True and False typically behave like values 1 and 0. Integers can be written using decimal-point notation (3 is 3.0) but not vice versa (2.65 cannot be

represented as an integer), int type is contained in the float type, as shown in above Figure. Example : The expression 3 + 0.35 in which an int value and a float value are added. The float type

contains the int type so 3 is converted to 3.0 before floating point addition of two float values is done: >>> 3 + 0.35 3.35

Explicit Type Conversions Type conversions can also be done explicitly using the constructor functions. For example, the int()

constructor creates an integer from a float input argument; it does so by removing the fractional part of the argument:

>>> int(3.4) 3 >>> int(-3.6) -3 The float() constructor applied to an integer will change the representation to a floating point one,

unless an overflow occurs. >>> float(3) 3.0 The string constructor str(), when applied to a number, returns the string representation of the

number: >>> str(2.72) '2.72'

Python Standard Library

The core Python programming language has functions such as max() and sum() and classes such as int, str, and list. While those are all the built-in Python functions and classes. In addition to the core functions and classes, Python has many more functions and classes defined in the Python Standard Library. The Python Standard Library consists of thousands of functions and classes organized into components called modules. Each module contains a set of functions and/or classes related to a particular application domain. More than 200 built-in modules together form the Python Standard Library. Each module in the Standard Library contains functions and classes to support application programming in a certain domain. The Standard Library includes modules to support are,

• Network programming • Web application programming • Graphical user interface (GUI) development • Database programming • Mathematical functions • Pseudorandom number generators

Module math

17

The core Python language supports only basic mathematical operators; other mathematical functions such as the square root function or the trigonometric functions, the math module is required. The math module is a library of mathematical constants and functions. To use a math module function, the module must first be explicitly imported:

>>> import math The import statement makes available all the math functions defined in module math. The square

root function sqrt() is defined in module math, but the Python interpreter doesn’t know about sqrt, the name of the square root function. We must tell the interpreter explicitly as defined below.

>>> math.sqrt(3) 1.7320508075688772

Math module Functions The below table lists some of the commonly used functions defined in the math module.

Function Explanation sqrt(x) √x ceil(x) x

(i.e., the smallest integer≥x) floor(x) x(i.e., the largest integer≤x) cos(x) cos(x) sin(x) sin(x) log(x, base) logbase(x) pi 3.141592653589793 e 2.718281828459045 The value of variable math.pi is an approximation for the mathematical constant π, and the value of

math.e is an approximation for the Euler constant e. Module fractions

The fractions module makes available a new type of number, called the Fraction type. The Fraction type is used to represent fractions and do rational arithmetic, such as:

1 +3 =5 To use the fractions module, we first need to import it:

>>> import fractions To create a Fraction object, we use the Fraction() constructor with two arguments: a numerator and a denominator. Here is how we can define 3 and 1 :

>>> a = fractions.Fraction(3, 4) >>> b = fractions.Fraction(1, 2)

When we evaluate expression a, we get >>> a Fraction(3, 4)

Note that a does not evaluate to 0.75. As with other numbers, Fraction objects can be added, and the result is a Fraction object:

>>> c = a + b >>> c Fraction(5, 4)

PYTHON PROGRAMMING

UNIT-II

IMPERATIVE PROGRAMMING

18

A Python program that implements a computer application is a sequence of multiple Python statements. This sequence of Python statements is stored in one or more files created by the developer using an editor. Our First Python Program

A specialized editor for programmers comes with tools to facilitate and speed up the program development process. Such a software development environment is called an Integrated Development Environment (IDE).

Several IDEs can be used to develop Python programs. Each has features that are helpful for Python programming, including automatic indentation, abilities to run/debug Python code within the editor, and easy access to the Python Standard Library. Three popular IDEs are IDLE (which is included with the Python development kit), Komodo, and PyDev with Eclipse.

In order to write the first program, we will need to use the editor that is included in the Python IDE. How the editor is opened depends on the IDE. For example, if you are using the IDLE Python IDE, click on the File tab in the IDLE window and then on the New Window button. This will open up a new window; we will use to type the first Python program.

Module: hello.py line1 = 'Hello Python Developer..' line2 = 'Welcome to the world of Python!' print(line1) print(line2) This program consists of four statements, one in each line. Lines 1 and 2 have assignment statements

and lines 3 and 4 are calls to the print() function. Once we have typed the program, we will want to execute it. For example, if you are using the IDLE IDE, hit key F5 on your keyboard (or, using your mouse, click on the Run tab of the IDLE shell window menu and the on the Run Module button.) We will be asked to save the program in a file. The file name must have the suffix '.py'. After we have saved the file (as hello.py, in a folder of your choice), the program is executed and this is printed in the interactive shell: >>> ========================= RESTART ========================== >>> Hello Python developer... Welcome to the world of Python!

The Python interpreter has executed all the statements in the program in order, from line 1 to line 4. The below diagram shows the flowchart of the program. A flowchart is a diagram that illustrates the flow of execution of a program. In the example, flowchart shows that the four statements are executed in order from top to bottom.

19

An application program is typically run from outside a software development environment such as IDLE, so it is important to know how to execute Python programs at the command line. An easy way to run your program is to run this command at the prompt of a command line window:

>>> hello.py Hello Python developer... Welcome to the world of Python! Python Modules

The file hello.py we have created and saved is an example of a user-defined Python module. A module is simply a file containing Python code. Every file containing Python code and whose file name ends in .py is a Python module. The file hello.py we created is a module, and so are files math.py, fractions.py and turtle.py hidden in some folder on your computer and implementing the corresponding Standard Library components. The code in a module is to be executed. For example, when we ran hello.py by hitting F5, the code in the module got executed, from beginning to end. When we execute an import statement on a module such as math, >>> import math the code in the file math.py gets executed. That Python code happens to define a bunch of math functions. Built-In Function print() Our first program has two lines of code in which the function print() is used. This function prints, within the interactive shell, whatever argument is given to it. For example, if given a number, it prints the number:

>>> print(0) 0

Similarly, if given a list, it prints it: >>> print([0, 0, 0])

[0, 0, 0] A string argument is printed without the quotes:

>>> print('zero') zero

If the input argument contains an expression, the expression is evaluated and the result is printed: >>> x = 0 >>> print(x) 0

Interactive Input with input() The input() function is used to interact with the user. It is always used on the right side of an

assignment statement, >>> x = input('Enter your first name: ')

When Python executes this input() function, Python will first print its input argument (string 'Enter your first name: ') in the shell:

Enter your first name: and then it will interrupt the execution and wait for the user to type something at the keyboard. The printed string 'Enter your first name: ' is essentially a prompt. When the user types something and hits the Enter/Return key on her keyboard, the execution will resume and whatever the user has typed will be assigned to variable name:

>>> name = input('Enter your first name: ') Enter your first name: Anand >>> name 'Anand' The next program asks the user to enter his first and last name and then prints a personalized greeting

on the screen.

20

Module: input.py 1 first = input('Enter your first name: ') 2 last = input('Enter your last name: ') 3 line1 = 'Hello '+ first + ''+ last + '...' 4 print(line1) 5 print('Welcome to the world of Python!') When we run this program, the statement in line 1 is executed first; it prints the message 'Enter your

first name: ' and interrupts the execution of the program until the user types something using the keyboard and presses the Enter/Return key. Whatever the user typed is assigned to variable first. Line 2 is similar. In line 3, string concatenation is used to create the greeting string printed in line 4. Here is a sample execution of the program:

>>> Enter your first name: Anand Enter your last name: Kumar

Hello Anand Kumar... Welcome to the world of Python! Function input() Returns a String When the input function is called, whatever the user types is treated as a string. Let’s check what happens when the user enters a number:

>>> x = input('Enter a value for x: ') Enter a value for x: 5 >>> x '5'

The Python interpreter treats the value entered as a string '5', not integer 5. We check this: >>> x == 5 False >>> x =='5' True The input() function will always treat whatever the user types as a string. Function eval() The eval() allows us to execute arbitrary strings as Python code. It accepts a source string and returns an object. The syntax of eval is: eval(expression, globals=None, locals=None) expression: this string is parsed and evaluated as a Python expression globals (optional): a dictionary to specify the available global methods and variables. locals (optional): another dictionary to specify the available local methods and variables.

If both globals and locals are omitted, the current global and local namespaces are used. The function eval() takes a string as input and evaluates the string as if it were a Python expression. Examples:

>>> eval('3') 3 >>> eval('3 + 4') 7 >>> eval('len([3, 5, 7, 9])') 4

21

The function eval() can be used together with the function input() when we expect the user to type an expression (a number, a list, etc.) when requested. All we need to do is wrap the eval() function around the input() function: The effect is that whatever the user types will be evaluated as an expression. For example, a number entered by the user is treated as a number:

>>> x = eval(input('Enter x: ')) Enter x: 5

We check that x is indeed a number and not a string: >>> x == 5 True >>> x =='5'

False Comments in Python

Comments can be included anywhere which means inline as well. Comments in Python start with a # character. When the interpreter encounters a # symbol anywhere, (except inside a string because a # within a string just means #), it omits everything that is present after it until the end of that line. The # tag actually tells the interpreter to stop reading anything present after it. Types of Comments Comments can either be

Single-line or Multi-line

1. Single-line Comments: They can appear either in an individual line or inline with some other code.

Example: 1 2

#Comments in Python start like this print("Comments in Python start with a #")

Output: Comments in Python start with a #

As we can see in the above output, the print statement is executed whereas the comment statement is not present in the output. 2. Multi-line Comments:

Multi-line comments appear in more than one line. All the lines to be commented are to be prefixed by a #. If you don’t do so, you will encounter an error. Example:

If we have more than one comment line, all of them need to be prefixed by a #. Example:

1 2 3

#Comments in Python #start with this character

print("Comments in Python")

22

Output: Comments in Python The above output shows that all lines prefixed with a # character are not returned in the output.

Docstring Comments Docstrings are not actually comments, but, they are documentation strings. These docstrings are within triple quotes. They are not assigned to any variable and therefore, at times, serve the purpose of comments as well. They are used particularly when you need to affiliate some documentation related to a class or a function, etc. Example:

1 2 3 4

""" Using docstring as a comment. This code divides 2 numbers

""" Output: ‘ Using docstring as a comment. This code divides 2 numbers Functions in Python

Function is a set of statements that take inputs, do some specific computation and produces output. The idea is to put some commonly or repeatedly done task together and make a function, so that instead of writing the same code again and again for different inputs, we can call the function.

Functions that readily come with Python are called built-in functions. If we use functions written by others in the form of library, it can be termed as library functions. User-Defined Functions

Functions that we define ourselves to do certain specific task are referred as user-defined functions. Advantages of user-defined functions

1. User-defined functions help to decompose a large program into small segments which makes program easy to understand, maintain and debug.

2. If repeated code occurs in a program. Function can be used to include those codes and execute when needed by calling that function.

3. Programmers working on large project can divide the workload by making different functions. Rules to define a function:

Function blocks begin with the keyword def followed by the function name and parentheses ( ). Any input parameters or arguments should be placed within these parentheses. We can also define

parameters inside these parentheses. The first statement of a function can be an optional statement - the documentation string of the

function or docstring. The code block within every function starts with a colon : and is indented. The statement return [expression] exits a function, optionally passing back an expression to the

caller. A return statement with no arguments is the same as return None.

Syntax: def function_name(argument1, argument2, ...) : statement_1 statement_2 ....

Example:

1. >>> def hello(): 2. print("Hello")

23

Calling a function

Calling a function in Python is similar to other programming languages, using the function name, parenthesis() and parameter. Syntax: function_name(arg1, arg2) Example: def my_function(): print("Hello from a function") my_function()

Call by Value and Call by Reference Functions can be invoked in two ways: Call by Value or Call by Reference. These two ways are

generally differentiated by the type of values passed to them as parameters. The parameters passed to function are called actual parameters whereas the parameters received by function are called formal parameters. Call by Value: In this parameter passing method, values of actual parameters are copied to function’s formal parameters and the two types of parameters are stored in different memory locations. So any changes made inside functions are not reflected in actual parameters of caller. Call by Reference: Both the actual and formal parameters refer to same locations, so any changes made inside the function are actually reflected in actual parameters of caller.

All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function. Example: # Function definition is here def changeme( mylist ): "This changes a passed list into this function" mylist.append([1,2,3,4]); print "Values inside the function: ", mylist return # Now you can call changeme function mylist = [10,20,30]; changeme( mylist ); print "Values outside the function: ", mylist We are maintaining reference of the passed object and appending values in the same object. So, this would produce the following result −

Values inside the function: [10, 20, 30, [1, 2, 3, 4]] Values outside the function: [10, 20, 30, [1, 2, 3, 4]]

There is one more example where argument is being passed by reference and the reference is being overwritten inside the called function. # Function definition is here def changeme( mylist ): "This changes a passed list into this function" mylist = [1,2,3,4]; # This would assig new reference in mylist print "Values inside the function: ", mylist return # Now you can call changeme function mylist = [10,20,30]; changeme( mylist );

24

print "Values outside the function: ", mylist The parameter mylist is local to the function changeme. Changing mylist within the function does not affect mylist. The function accomplishes nothing and finally this would produce the following result −

Values inside the function: [1, 2, 3, 4] Values outside the function: [10, 20, 30]

Function Definitions Are “Assignment” Statements

Functions are really ordinary Python statements, similar to assignment statements. Python does not allow calling a function before it is defined, just as a variable cannot be used in an expression before it is assigned. Example:

1 s = input('Enter square or cube: ') 2 if s =='square': 3 def f(x): 4 return x*x 5 else: 6 def f(x): 7 return x*x*x In this, function f() is defined within a Python program, just as an assignment statement can be in a

program. The actual definition of f() depends on the input entered by the user at execution time. By typing cube at the prompt, function f() is defined to be the cubic function:

>>> Enter square or cube: cube >>> f(3) 27

If, however, the user types square, then f() would be the quadratic function. Python Variables and Assignments

Functions are either called from within the interactive shell or by another program, which we will refer to as the calling program. In order to be able to design functions, we need to understand how values created in the calling program—or the interactive shell—are passed as input arguments to the function. Example:

When the assignment >>> a = 3

is executed, the integer object 3 and its name a are created. Python will store the name in a table maintained by Python. This is illustrated in the below figure, The variable a now refers to the integer object with value 3:

>>> a 3

The above figure shows that additional variables are in the table: variable b referring to float object 3.0, variable c referring to str object 'hello', and variable d referring to list object [2, 3, 5, 8, 11]. In other words, it illustrates that these assignments have also been made:

>>> b = 3.0 >>> c ='hello' >>> d = [2, 3, 5, 8, 11]

In general, a Python assignment statement has this syntax:

25

<variable> = <expression> The <expression> to the right of the = assignment operator is evaluated and the resulting value is

stored in an object of the appropriate type; then the object is assigned to <variable>, which is said to refer to the object or to be bound to the object.

Scope of Variables

All variables in a program may not be accessible at all locations in that program. This depends on the declaration of a variable. The scope of a variable determines the portion of the program where we can access a particular identifier. There are two basic scopes of variables in Python − Global variables Local variables. Global vs. Local variables Variables that are defined inside a function body are called a local variable, and the variables defined outside a function are called a global variable. This means that local variables can be accessed only inside the function in which they are declared, whereas global variables can be accessed throughout the program body by all functions. Example:

total = 0; # This is global variable. # Function definition is here def sum( arg1, arg2 ): # Add both the parameters and return them. " total = arg1 + arg2; # Here total is local variable. print "Inside the function local total : ", total return total; # Now you can call sum function sum( 10, 20 ); print "Outside the function global total : ", total

When the above code is executed, it produces the following result – Inside the function local total : 30 Outside the function global total : 0 Swapping: Consider a fundamental assignment problem. Let a and b refer to two integer values:

>>> a = 6 >>> b = 3 Suppose we need to swap the values of a and b. In other words, after the swap, a will refer to 3

and b will refer to 6, as shown below.

If we start by assigning the value of b to a: a=b then variable a will refer to the same object that variable b refers to. So we will have both a and b refer to 3 and we would have “lost” integer object 6. Before we execute a=b, we must save a reference to 6 and then assign that to b at the end:

>>> temp = a # temp refers to 6 >>> a = b # a refers to 3 >>> b = temp # b refers to 6

In Python, there is a simpler way to achieve the swap. Python supports the multiple assignment statement: >>> a = 6

26

>>> b = 3 >>> a, b = b, a >>> a 3 >>> b 6 In the multiple assignment statement a, b = b, a, the two expressions on the right of = are evaluated

to two objects and then each is assigned to the corresponding variable. A value can be assigned to several variables simultaneously:

>>> i = j = k = 0 The three variables i, j, and k are all set to 0. Types of User-Defined Functions in Python (or) Types of Parameter Passing

In real time, a function may be defined with or without parameters (also called as arguments), and a function may or may not return a value. It is completely depends upon the user requirement. The following are the list of available types of functions in Python.

1. Function with no argument and no Return value 2. Function with no argument and with Return value 3. Python Function with argument and No Return value 4. Function with argument and Return value

1. Python Function with No arguments and No Return value

In this type of function in Python, while defining, declaring or calling the function, we won’t pass any arguments to the function. This type of functions will not return any value when we call the function.

Whenever we are not expecting any return value, we might need some statements to be printed as output. In such a scenario, we can use this type of functions. Example:

In this type of function in Python program, we are going to calculate the Sum of 2 integer values and print the output from the user defined function itself. # Python Function with No Arguments, and No Return Value

def Adding(): a = 20 b = 30 Sum = a + b print("After Calling the Function:", Sum) Adding() If you observe the Adding() function, We haven’t passed any arguments /parameters to the function.

We declared the integer variables a, b and assigned 20 to a and 30 to b. In the next line we calculate the sum using Arithmetic operator (+). Below print statement is used to print the output.

After Calling the Function: 50 Whenever we call the Adding() function, it will print the same output because the values of a and b are fixed inside the function. 2. Python Function with no arguments and with Return value

In this type of function in Python, We won’t pass any arguments to the function while defining, declaring or calling the function. When we call the function, this type of functions will return some value. Example:

In this type of function in Python program, we are going to calculate the multiplication of 2 integer values using the user defined function without arguments and return keyword. # Python Function with No Arguments, and with Return Value

def Multiplication():

27

a = 10 b = 25 Multi = a * b return Multi print("After Calling the Multiplication Function: ", Multiplication()) Within the Multiplication () function, we haven’t passed any arguments /parameters. Next, we

declared the integer variables of Multi, a, b and we assigned 10 to a, and 25 to b. In the next line we Multiplied both a and b using Arithmetic operator (*)

Lastly, print statement is used to print the output. Remember, we are using the print statement outside the defined function, and we are using the function name inside the print statement. (nothing but calling the function) After Calling the Multiplication Function: 250

Whenever we call the Multiplication() function, it will print the same output because the values of a and b are fixed inside the function.

3. Python Function with arguments and No Return value

If we observe the above 2 methods, No matter how many times we execute, it will give the same output. We don’t have any control over the variable values (a, b) because they are fixed values.

In real-time, we mostly deal with dynamic data means we have to allow the user to enter their own values rather than fixed ones. This type of function in Python allows us to pass the arguments to the function while calling the function. But, this type of functions in Python will not return any value when we call the function. Example:

This program for type of function in Python allows the user to enter 2 integer values and then, we are going to pass those values to the user defined function to Multiply them. # Python Function with Arguments, and No Return Value

def Multiplications(a, b): Multi = a * b print("After Calling the Function:", Multi) Multiplications(10, 20) Within the Multiplication(a, b) function, We declared the variables of Multi and also we also had

(a, b) arguments in the function. This means, this function will allow the user to pass 2 values. In the next line we added both a and b using Arithmetic operator (*). In the next line, print statement

is used to print the output, After Calling the Function: 200

In the above output, we called the Multiplication function with different values, and it is giving the output as per the values.

4. Python Function with arguments and Return value

This method allows us to pass the arguments to the function while calling the function. This type of functions in Python will return some value when we call the function. This type of user defined functions are called as fully dynamic function means, it provide maximum control to the end-user. Example:

This type of function in Python program allows the user to enter 2 integer values and then, we are going to pass those values to the user defined function to add those values and return the value using return keyword. # Python Function with Arguments, and No Return Value

def Addition(a, b): Sum = a + b return Sum

28

# We are calling the Function Outside the Function Definition print("After Calling the Function:", Addition(25, 45))

Within the Addition(a, b) function, We declared the variables of Sum and also we also had (a, b)

arguments in the function. This means, this function will allow the user to pass 2 values. In the next line, we added both a and b using Arithmetic operator(*). In the next line, print statement is used to print the output

After Calling the Function: As you can see from the above output, we called the addition function with different values, and it is giving the output as per the values. Python Recursive Function

In Python, a function can call other functions. It is the function that can call itself. These types of functions are termed as recursive functions. Example of recursive function: To find the factorial of an integer.

Factorial of a number is the product of all the integers from 1 to that number. For example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720. Program to find factorial of a number

def calc_factorial(x): """This is a recursive function to find the factorial of an integer""" if x == 1: return 1 else: return (x * calc_factorial(x-1)) num = 4 print("The factorial of", num, "is", calc_factorial(num))

In the above example, calc_factorial() is a recursive functions as it calls itself. When we call

this function with a positive integer, it will recursively call itself by decreasing the number. Each function call multiples the number with the factorial of number 1 until the number is equal to one. This recursive call can be explained in the following steps. 1. calc_factorial(4) # 1st call with 4 2. 4 * calc_factorial(3) # 2nd call with 3 3. 4 * 3 * calc_factorial(2) # 3rd call with 2 4. 4 * 3 * 2 * calc_factorial(1) # 4th call with 1 5. 4 * 3 * 2 * 1 # return from 4th call as number=1 6. 4 * 3 * 2 # return from 3rd call 7. 4 * 6 # return from 2nd call 8. 24 # return from 1st call

Our recursion ends when the number reduces to 1. This is called the base condition. Every recursive function must have a base condition that stops the recursion or else the function calls itself infinitely. Advantages of Recursion

1. Recursive functions make the code look clean and elegant. 2. A complex task can be broken down into simpler sub-problems using recursion. 3. Sequence generation is easier with recursion than using some nested iteration.

Disadvantages of Recursion

1. Sometimes the logic behind recursion is hard to follow through. 2. Recursive calls are expensive (inefficient) as they take up a lot of memory and time.

29

3. Recursive functions are hard to debug.

PYTHON PROGRAMMING

UNIT-III

TEXT DATA, FILES & EXCEPTIONS I. STRINGS, REVISITED String Representation: A string is represented as a sequence of characters that is enclosed within quotes, whether single or double quotes:

>>> "Hello, World!" 'Hello, World!' >>> 'hello' 'hello'

Assign String to a Variable Assigning a string to a variable is done with the variable name followed by an equal sign and the

string: Example :

a = "Hello" print(a)

Output: Hello Strings are Arrays

Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters. However, Python does not have a character data type, a single character is simply a string with a length of 1. Square brackets can be used to access elements of the string. Example Get the character at position 1 (remember that the first character has the position 0):

a = "Hello World!" print(a[1])

Output: e Negative Indexing

Use negative indexes to start the slice from the end of the string: Example Get the characters from position 5 to position 1, starting the count from the end of the string:

b = "helloworld” print(b[-5:-2])

Output : wor String Length

To get the length of a string, use the len() function. Example

The len() function returns the length of a string: a = "Hello, World!" print(len(a))

Output: 13

Formatted Output

30

If we want to print a text like -He said, "What's there?"- We can neither use single quote or double quotes. This will result into SyntaxError as the text itself contains both single and double quotes. 1. >>> print("He said, "What's there?"") 2. ... 3. SyntaxError: invalid syntax 4. >>> print('He said, "What's there?"') 5. ... 6. SyntaxError: invalid syntax

One way to get around this problem is to use triple quotes. Triple quotes also allow the creation of multiline strings. Alternatively, we can also use escape sequences.

# Python Program for Creation of String # Creating a String with single Quotes String1 = 'Welcome to computer World' print("String with the use of Single Quotes: ") print(String1) # Creating a String with double Quotes String1 = "I'm computer" print("\nString with the use of Double Quotes: ") print(String1) # Creating a String with triple Quotes String1 = '''I'm a computer I help "the world"''' print("\nString with the use of Triple Quotes: ") print(String1) # Creating String with triple Quotes allows multiple lines String1 = '''computerworld do Process speed''' print("\nCreating a multiline String: ") print(String1)

Output: String with the use of Single Quotes: Welcome to computer World String with the use of Double Quotes: I'm computer String with the use of Triple Quotes: I'm a computer and I help “the world" Creating a multiline String: computerworld do Process speed Function Format()

The str.format() method of strings help a user to get a fancier Output. Strings in Python can be formatted with the use of format() method which is very versatile and powerful tool for formatting of

31

Strings. Format method in String contains curly braces {} as placeholders which can hold arguments. A string can be left(<), right(>) or center(^) justified with the use of format specifiers, separated by colon(:). Integers such as Binary, hexadecimal, etc. and floats can be rounded or displayed in the exponent form with the use of format specifiers.

# Python Program for Formatting of Strings # Default order String1 = "{} {} {}".format('Good', 'For', 'Health') print("Print String in default order: ") print(String1) # Positional Formatting String1 = "{1} {0} {2}".format('Good', 'For', 'Health') print("\nPrint String in Positional order: ") print(String1) # Keyword Formatting String1 = "{l} {f} {g}".format(g = 'Good', f = 'For', l = 'Health') print("\nPrint String in order of Keywords: ") print(String1) # Formatting of Integers String1 = "{0:b}".format(16) print("\nBinary representation of 16 is ") print(String1) # Formatting of Floats String1 = "{0:e}".format(165.6458) print("\nExponent representation of 165.6458 is ") print(String1) # Rounding off Integers String1 = "{0:.2f}".format(1/6) print("\none-sixth is : ") print(String1) # String alignment String1 = "|{:<10}|{:^10}|{:>10}|".format('Geeks','for','Geeks') print("\nLeft, center and right alignment with Formatting: ") print(String1) Output: Print String in default order: Good For Health Print String in Positional order: For Good Health Print String in order of Keywords: Health For Good Binary representation of 16 is 10000

32

Exponent representation of 165.6458 is 1.656458e+02 one-sixth is : 0.17 Left, center and right alignment with Formatting: |Health | For | Good|

Formatting output using String modulo operator(%) : The % operator can also be used for string formatting. It interprets the left argument much like a printf()-style format string to be applied to the right argument. In Python, there is no printf() function but the functionality of the ancient printf is contained in Python. To this purpose, the modulo operator % is overloaded by the string class to perform string formatting. Therefore, it is called string modulo operator.

# Python Program for Old Style Formatting of Integers Integer1 = 12.3456789 print("Formatting in 3.2f format: ") print('The value of Integer1 is %3.2f' %Integer1) print("\nFormatting in 3.4f format: ") print('The value of Integer1 is %3.4f' %Integer1)

Output: Formatting in 3.2f format: The value of Integer1 is 12.35 Formatting in 3.4f format: The value of Integer1 is 12.3457 String modulo operator ( % ) is still available in Python(3.x) and user is using it widely. But

nowadays the old style of formatting is removed from the language. # Python program to use string modulo operator(%) to print fancier output # print integer and float value print("Geeks : % 2d, Portal : % 5.2f" %(1, 05.333)) # print integer value print("Total students : % 3d, Boys : % 2d" %(240, 120)) # print octal value print("% 7.3o"% (25)) # print exponential value print("% 10.3E"% (356.08977)) Output : Geeks : 1, Portal : 5.33 Total students : 240, Boys : 120 031 3.561E+02

Escape Sequence

An escape sequence starts with a backslash and is interpreted differently. If we use single quote to represent a string, all the single quotes inside the string must be escaped. In general, an escape sequence in a string is a sequence of characters starting with a \ that defines a special character and that is interpreted by function print().

33

Escape Sequence Description

\newline Backslash and newline ignored

\\ Backslash

\' Single quote

\" Double quote

\a ASCII Bell

\b ASCII Backspace

\f ASCII Formfeed

\n ASCII Linefeed

\r ASCII Carriage Return

\t ASCII Horizontal Tab

\v ASCII Vertical Tab

\ooo Character with octal value ooo

\xHH Character with hexadecimal value HH

Example:

1. >>> print("C:\\Python32\\Lib") 2. C:\Python32\Lib 3. 4. >>> print("This is printed\n in two lines") 5. This is printed 6. in two lines 7. 8. >>> print("This is \x48\x45\x58 representation") 9. This is HEX representation II. The Indexing Operator, Revisited We introduced the indexing operator []:

>>> s ='hello'

34

>>> s[0] 'h'

The indexing operator takes an index i and returns the single-character string consisting of the character at index i. The indexing operator can also be used to obtain a slice of a string. For example:

>>> s[0:2] 'he'

The expression s[0:2] evaluates to the slice of string s starting at index 0 and ending before index 2. In general, s[i:j] is the substring of string s that starts at index i and ends at index j-1. Here are more examples, also illustrated in below figure.

>>> s[3:4] 'l' >>> s[-3:-1] 'll'

The last example shows how to get a slice using negative indexes: The substring obtained starts at index 3 and ends before index 1 (i.e., at index 2). If the slice we want starts at the first character of a string, we can drop the first index:

>>> s[:2] 'he'

In order to obtain a slice that ends at the last character of a string, we must drop the second index: >>> s[-3:] 'llo'

Slicing Lists A slice of a list is a list. In other words, when the indexing operator is applied to a list with two arguments, it will return a list. When the indexing operator is applied to a list with only one argument, say an index i; in that case, the item of the list at index i is returned. The indexing operator is one of many operators that are shared between the string and the list classes. The indexing operator can also be used to obtain a slice of a list. For example, if pets is defined as,

>>> pets = ['goldfish', 'cat', 'dog'] we can get slices of pets with the indexing operator:

>>> pets[:2] ['goldfish', 'cat'] >>> pets[-3:-1] ['goldfish', 'cat'] >>> pets[1:] ['cat', 'dog']

String Methods The string class supports a large number of methods. These methods provide the developer with a text-processing toolkit that simplifies the development of text-processing applications. Python has a set of built-in methods that we can use it on strings. All string methods returns new values. They do not change the original string.

Method Description

capitalize() Converts the first character to upper case

35

casefold() Converts string into lower case

center() Returns a centered string

count() Returns the number of times a specified value occurs in a string

encode() Returns an encoded version of the string

endswith() Returns true if the string ends with the specified value

expandtabs() Sets the tab size of the string

find() Searches the string for a specified value and returns the position of where it was found

format() Formats specified values in a string

format_map() Formats specified values in a string

index() Searches the string for a specified value and returns the position of where it was found

isalnum() Returns True if all characters in the string are alphanumeric

isalpha() Returns True if all characters in the string are in the alphabet

36

isdecimal() Returns True if all characters in the string are decimals

isdigit() Returns True if all characters in the string are digits

isidentifier() Returns True if the string is an identifier

islower() Returns True if all characters in the string are lower case

isnumeric() Returns True if all characters in the string are numeric

isprintable() Returns True if all characters in the string are printable

isspace() Returns True if all characters in the string are whitespaces

istitle() Returns True if the string follows the rules of a title

isupper() Returns True if all characters in the string are upper case

join() Joins the elements of an iterable to the end of the string

ljust() Returns a left justified version of the string

lower() Converts a string into lower case

37

lstrip() Returns a left trim version of the string

maketrans() Returns a translation table to be used in translations

partition() Returns a tuple where the string is parted into three parts

replace() Returns a string where a specified value is replaced with a specified value

rfind() Searches the string for a specified value and returns the last position of where it was found

rindex() Searches the string for a specified value and returns the last position of where it was found

rjust() Returns a right justified version of the string

rpartition() Returns a tuple where the string is parted into three parts

rsplit() Splits the string at the specified separator, and returns a list

rstrip() Returns a right trim version of the string

split() Splits the string at the specified separator, and returns a list

38

splitlines() Splits the string at line breaks and returns a list

startswith() Returns true if the string starts with the specified value

strip() Returns a trimmed version of the string

swapcase() Swaps cases, lower case becomes upper case and vice versa

title() Converts the first character of each word to upper case

translate() Returns a translated string

upper() Converts a string into upper case

zfill() Fills the string with a specified number of 0 values at the beginning

Example 1:

1. >> "ProGRammiNg".lower() 2. 'programing' 3. >>> " ProGRammiNg ".upper() 4. 'PROGRAMING' 5. >>> "This will split all words into a list".split() 6. ['This', 'will', 'split', 'all', 'words', 'into', 'a', 'list'] 7. >>> ' '.join(['This', 'will', 'join', 'all', 'words', 'into', 'a', 'string']) 8. 'This will join all words into a string' 9. >>> 'Happy New Year'.find('ew') 10. 7 11. >>> 'Happy New Year'.replace('Happy','Brilliant') 12. 'Brilliant New Year' Example 2:

var = 'PYTHON' print (var.capitalize()) # Python

39

var = 'cOmPuteR' print (var.swapcase()) # CoMpUTEr

var = 'welcome to Python programming' print (var.title()) # Welcome To Python Programming var='Computer science' str='e' print (var.count(str)) # 2 var1='Eagle Eyes' print (var1.count('e')) # 2 var2='Eagle Eyes' print (var2.count('E',0,5)) # 1

String Comparison Functions 1. islower() – Returns ‘True’ if all the characters in the String are in lowercase. If any of the char is in uppercase, it will return False.

va='Python' print (va.islower()) # False va='python' print (va.islower()) # True

2. isupper() – Returns ‘True’ if all the characters in the String are in uppercase. If any of the char is in lowercase, it will return False.

va='Python' print (va.isupper()) # False var='PYTHON' print (va.isupper()) # True

3. isdecimal() – Returns ‘True’ if all the characters in String are decimal. If any character in the String is of other data-type, it will return False. Decimal characters are those from the Unicode category Nd. Ex:

num=u'2016' print (num.isdecimal()) # True

4. isdigit() – Returns ‘True’ for any char for which isdecimal() would return ‘True and some characters in the ‘No’ category. If there are any characters other than these, it will return False’. Precisely, digits are the characters for which Unicode property includes: Numeric_Type=Digit or Numeric_Type=Decimal. For example, superscripts are digits but fractions not.

print ('2'.isdigit()) # True print ('²'.isdigit()) # True

5. isnumeric() – Returns ‘True’ if all the characters of the Unicode String lie in any one of the categories Nd’, No, and NI.

40

If there are any characters other than these, it will return False. Precisely, Numeric characters are those for which Unicode property includes: Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numeric. Example:

num=u'2016' print (num.isnumeric()) # True num=u'year2016' print (num.isnumeric()) # False

6. isalpha() – Returns ‘True’ if String contains at least one character (non-empty String) and all the characters are alphabetic, ‘False’ otherwise.

print ('python'.isalpha()) # True print ('python3'.isalpha()) # False

7. isalnum() – Returns ‘True’ if String contains at least one character (non-empty String) and all the characters are either alphabetic or decimal digits, ‘False’ otherwise. print ('python'.isalnum())

# True print ('python3'.isalnum()) # True

Padding Functions 1. rjust(width[,fillchar]) – Returns string filled with input char while pushing the original content on the right side. By default, the padding uses a space. Otherwise ‘fillchar’ specifies the filler character.

var='Python' print (var.rjust(10)) # Python print (var.rjust(10,'-')) # ----Python

2. ljust(width[,fillchar]) – Returns a padded version of String with the original String left-justified to a total of width columns By default, the padding uses a space. Otherwise ‘fillchar’ specifies the filler character.

var='Python'

41

print (var.ljust(10)) # Python print (var.ljust(10,'-')) # Python----

3. center(width[,fillchar]) – Returns string filled with the input char while pushing the original content into the center. By default, the padding uses a space. Otherwise ‘fillchar’ specifies the filler character.

var='Python' print (var.center(20)) # Python print (var.center(20,'*')) # *******Python*******

4. zfill(width) – Returns string filled with the original content padded on the left with zeros so that total length of String becomes equal to the input size. If there is a leading sign (+/-) present in the String, then with this function padding starts after the symbol, not before it.

var='Python' print (var.zfill(10)) # 0000Python var='+Python' print (var.zfill(10)) # +000Python

Search Functions 1. find(str [,i [,j]]) – Searches for ‘str’ in complete String (if i and j not defined) or in a sub-string of String (if i and j are defined).This function returns the index if ‘str’ is found else returns ‘-1’. Here, i=search starts from this index, j=search ends at this index.

var="Tech Beamers" str="Beam" print (var.find(str)) # 5 var="Tech Beamers" str="Beam" print (var.find(str,4)) # 5 var="Tech Beamers" str="Beam" print (var.find(str,7)) # -1

2. index(str[,i [,j]]) – This is same as ‘find’ method. The only difference is that it raises ‘ValueError’ exception if ‘str’ doesn’t exist.

var='Tech Beamers' str='Beam' print (var.index(str)) # 5 var='Tech Beamers' str='Beam' print (var.index(str,4)) # 5 var='Tech Beamers' str='Beam' print (var.index(str,7)) # ValueError: substring not found

42

3. rfind(str[,i [,j]]) – This is same as find() just that this function returns the last index where ‘str’ is found. If ‘str’ is not found, it returns ‘-1’.

var='This is a good example' str='is' print (var.rfind(str,0,10)) # 5 print (var.rfind(str,10)) # -1

4. count(str[,i [,j]]) – Returns the number of occurrences of substring ‘str’ in the String. Searches for ‘str’ in the complete String (if i and j not defined) or in a sub-string of String (if i and j are defined). Where: i=search starts from this index, j=search ends at this index.

var='This is a good example' str='is' print (var.count(str)) # 2 print (var.count(str,4,10)) # 1

String Substitution Functions 1. replace(old,new[,count]) – Replaces all the occurrences of substring ‘old’ with ‘new’ in the String. If the count is available, then only ‘count’ number of occurrences of ‘old’ will be replaced with the ‘new’ var. Where old =substring to replace, new =substring

var='This is a good example' str='was' print (var.replace('is',str)) # Thwas was a good exampleprint (var.replace('is',str,1)) # Thwas is a good example

2. split([sep[,maxsplit]]) – Returns a list of substring obtained after splitting the String with ‘sep’ as a delimiter. Where, sep= delimiter, the default is space, maxsplit= number of splits to be done

var = "This is a good example" print (var.split()) # ['This', 'is', 'a', 'good', 'example']print (var.split(' ', 3)) # ['This', 'is', 'a', 'good example']

3. splitlines(num) – Splits the String at line breaks and returns the list after removing the line breaks. Where, num = if this is a positive value. It indicates that line breaks will appear in the returned list.

var='Print new line\nNextline\n\nMove again to new line' print (var.splitlines()) # ['Print new line', 'Nextline', '', 'Move again to new line']print (var.splitlines(1)) # ['Print new line\n', 'Nextline\n', '\n', 'Move again to new line']

4. join(seq) – Returns a String obtained after concatenating the sequence ‘seq’ with a delimiter string. Where: the seq= sequence of elements to join

seq=('ab','bc','cd') str='=' print (str.join(seq)) # ab=bc=cd

Miscellaneous String Functions 1. lstrip([chars]) – Returns a string after removing the characters from the beginning of the String. Where: Chars=this is the character to be trimmed from the String. The default is whitespace character.

43

var=' This is a good example ' print (var.lstrip()) # This is a good example var='*****This is a good example*****' print (var.lstrip('*')) # This is a good example**********

2. rstrip() – Returns a string after removing the characters from the End of the String. Where: Chars=this is the character to be trimmed from the String. The default is whitespace character.

var=' This is a good example ' print (var.rstrip()) # This is a good example var='*****This is a good example*****' print (var.lstrip('*')) # *****This is a good example

3. rindex(str[,i [,j]]) – Searches for ‘str’ in the complete String (if i and j not defined) or in a sub-string of String (if i and j are defined). This function returns the last index where ‘str’ is available. If ‘str’ is not there, then it raises a ValueError exception. Where: i=search starts from this index, j=search ends at this index.

var='This is a good example' str='is' print (var.rindex(str,0,10)) # 5 print (var.rindex(str,10)) # ValueError: substring not found

4. len(string) – Returns the length of given String var='This is a good example' print (len(var)) # 22 FILES A file is a sequence of bytes stored on a secondary memory device, such as a disk drive. A file could be a text document or spreadsheet, an html file, or a Python module. Such files are referred to as text files. Text files contain a sequence of characters that are encoded using some encoding (ASCII, utf-8, etc.). A file also can be an executable application (like python.exe), an image or an audio file. Theses file are referred as binary files because they are just a sequence of bytes and there is no encoding. All files are managed by the file system. File System The file system is the component of a computer system that organizes files and provides ways to create, access, and modify files. While files may be physically stored on various secondary (hardware) memory devices, the file system provides a uniform view of the files that hides the differences between how files are stored on the different hardware devices. The effect is that reading or writing files is the same, whether the file is on a hard drive, flash memory stick, or DVD-RW. Files and its Path There are always two parts of a file in the computer system, the filename and its extension. Also, the files have two key properties - its name and the location or path, which specifies the location where the file exists. The file name has two parts, and they are separated by a dot (.) or period.

44

Files are grouped together into directories or folders. A folder may contain other folders in addition to (regular) files. The file system organizes files and folders into a tree structure. The MAC OS X file system organization is shown below. The folder on top of the hierarchy is called the root directory. In UNIX, Mac OS X, and Linux file systems, the root folder is named /; in the MS Windows OS, every hardware device will have its own root directory g., C(e.:\). Every folder and file in a file system has a name. Every file can be specified using a pathname that is useful for locating the file efficiently. The file pathname can be specified in two ways. The absolute pathname of a file consists of the sequence of folders, starting from the root directory that must be traversed to get to the file. The absolute pathname is represented as a string in which the sequence of folders is separated by forward (/) or backward (\) slashes, depending on the operating system. For example, the absolute pathname of folder Python 3.1 is

/Applications/Python 3.1 while the absolute pathname of file example.txt is

/Users/test/example.txt The relative pathname of a file is the sequence of directories that must be traversed, starting from the current working directory, to get to the file. If the current working directory is Users, the relative pathname of file example.txt is,

test/example.txt If the current working directory is test, the relative pathname of executable file date is

../../bin/date The double-period notation (..) is used to refer to the parent folder, which is the folder containing the current working directory. Opening and Closing a File Processing a file consists of these three steps: 1. Opening a file for reading or writing 2. Reading from the file and/or writing to the file 3. Closing the file I. File Opening in Python

A built-in open method is used to create a Python file-object, which provides a connection to the file that is residing on programmer's machine. After calling the function open, programmers can transfer strings of data to and from the external file that is residing in the machine. Open() function is used to open a file in Python. It’s mainly required two arguments, first the file name and then file opening mode. Syntax:

file_object = open(filename [,mode] [,buffering])

In the above syntax the parameters used are: filename: It is the name of the file. mode: It tells the program in which mode the file has to be open. buffering: Here, if the value is set to zero (0), no buffering will occur while accessing a file, if the value

is set to top one (1), line buffering will be performed while accessing a file. Modes of File Opening in Python The file can be opened in the following modes:

Mode Description

45

r Opens a file for reading only. (It's a default mode.)

w Opens a file for writing. (If a file doesn't exist already, then it creates a new file. Otherwise, it's truncate a file.)

x Opens a file for exclusive creation. (Operation fails if a file does not exist in the location.)

a Opens a file for appending at the end of the file without truncating it. (Creates a new file if it does not exist in the location.)

t Opens a file in text mode. (It's a default mode.)

b Opens a file in binary mode.

+ Opens a file for updating (reading and writing.)

r+ Opens a file for both reading and writing. The file pointer placed at the beginning of the file.

w+ Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.

a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

rb Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode.

wb Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.

File Object Attributes

If an attempt to open a file fails then open returns a false value, otherwise it returns a file object that provides various information related to that file. Example:

# file opening example in Python fo = open("sample.txt", "wb") print ("File Name: ", fo.name) print ("Mode of Opening: ", fo.mode) print ("Is Closed: ", fo.closed)

46

print ("Softspace flag : ", fo.softspace)

Output:

File Name: sample.txt Mode of Opening: wb Is Closed: False Softspace flag: 0

II. File Reading In Python

For reading and writing text data different text-encoding schemes are used such as ASCII (American Standard Code for Information Interchange), UTF-8 (Unicode Transformation Format), UTF-16. Once a file is opened using open() method then it can be read by a method called read(). Example: # Open a file fo = open("foo.txt", "wb") fo.write( "Python is a great language.\nYeah its great!!\n") # Close opened file fo.close() File Writing In Python

Similarly, for writing data to files, we have to use open() with 'wt' mode, clearing and overwriting the previous content. Also, we have to use write() function to write into a file. Example:

# Write text data to a file with open('filename.txt' , 'wt') as f: f.write ('hi there, this is a first line of file.\n') f.write ('and another line.\n')

Output:

hi there, this is a first line of file. and another line.

The use of 'with' statement in the example establishes a context in which the file will be used. As the control leaves the 'with' block, the file gets closed automatically. Writing A File That Does Not Exist

The problem can be easily solved by using another mode - technique, i.e., the 'x' mode to open a file instead of 'w' mode. . Example:

with open('filename' , 'wt') as f: f.write ('Hello, This is sample content.\n') # This will create an error that the file 'filename' doesn't exist. with open ('filename.txt' , 'xt') as f: f.write ('Hello, This is sample content.\n')

In binary mode, we should use 'xb' instead of 'xt'. Working of append() mode

47

# Python code to illustrate append() mode file = open('geek.txt','a') file.write("This will add this line") file.close()

The rename() Method The rename() method takes two arguments, the current filename and the new filename. Syntax os.rename(current_file_name, new_file_name) Example import os # Rename a file from test1.txt to test2.txt os.rename( "test1.txt", "test2.txt" ) The remove() Method We can use the remove() method to delete files by the name of the file to be deleted as the argument. Syntax os.remove(file_name) Example import os # Delete file test2.txt os.remove("text2.txt") III. Closing A File In Python

In Python, it is not system critical to close all your files after using them, because the file will auto close after Python code finishes execution. You can close a file by using close() method. Syntax:

file_object.close();

Example:

try: # Open a file fo = open("sample.txt", "wb") # perform file operations finally: # Close opened file fo.close()

Flushing the Output When a file is opened for writing, a buffer is created in memory. All writes to the file are really writes to this buffer; nothing is written onto the disk, at least not just yet. The reason for not writing to disk is that writing to secondary memory such as a disk takes a long time, and a program making many writes would be very slow if each write had to done onto the secondary memory. The close() function will flush writes from the buffer to the file on disk before closing, so it is critical not to forget to close the file. We can also flush the writes without closing the file using the flush() function:

>>> outfile.flush() ERRORS AND EXCEPTIONS

When writing a program, many things can go wrong, we mistake in the code is termed as an error and it will abruptly terminate the program.

48

Types of Errors:

Syntax errors Errors which are encountered at runtime (Exceptions)

1. Syntax errors

Errors caused by not following the proper structure (syntax) of the language are called syntax or parsing errors. Example: >>> p >>> print "hello" SyntaxError: Missing parentheses in call to 'print'. Did you mean print("hello")?rint "hello"")?

In Python 3.x, print is a built-in function and requires parentheses. The statement above violates this usage and hence syntax error is displayed.

As we can see in the error message, the code is not indented properly. Syntax errors are easy to fix, Python will show the line number where the error is, with an error message. 2. Exceptions

Errors can also occur at runtime and these are called exceptions. The code may be syntactically correct but it may happen that during run-time Python encounters something which it can't handle, then it raises an exception. Example: Dividing a number by zero or trying to write to a file which is read-only.

When a Python script raises exception, it creates an Exception object. If the script doesn't handle

exception the program will terminate abruptly. Python Built-in Exceptions

Python provides us some basic exception classes that can be described below.

Exception Class Event

Exception Base class for all exceptions

ArithmeticError Raised when numeric calculations fails

FloatingPointError Raised when a floating point calculation fails

ZeroDivisionError Raised when division or modulo by zero takes place for all numeric types

AssertionError Raised when Assert statement fails

OverflowError Raised when result of an arithmetic operation is too large to be represented

ImportError Raised when the imported module is not found

IndexError Raised when index of a sequence is out of range

49

Exception Class Event

KeyboardInterrupt Raised when the user interrupts program execution, generally by pressing Ctrl+c

IndentationError Raised when there is incorrect indentation

SyntaxError Raised by parser when syntax error is encountered

KeyError Raised when the specified key is not found in the dictionary

NameError Raised when an identifier is not found in the local or global namespace

TypeError Raised when a function or operation is applied to an object of incorrect type

ValueError Raised when a function gets argument of correct type but improper value

IOError Raised when an input/ output operation fails

RuntimeError Raised when a generated error does not fall into any category

Example : 1) ArithmeticError

ArithmeticError is the base class for all arithmetic exceptions which are raised for errors in arithmetic operations, such as,

OverflowError ZeroDivisionError FloatingPointError

In the program below, a number is being divided by zero, which will raise an ArithmeticErrorexception. try: a = 10/0 print (a) except ArithmeticError: print ("Arithmetic exception raised." ) else: print ("Success.") Arithmetic exception raised

2) AssertionError

An AssertionError is raised by a failed assert statement. In the program below, the value of 2 variables is compared to check if they are equal or not. The assert statement raises an exception when the expression returns false. Since values are not equal in this example an exception will be raised.

try: a=10 b=20 assert a==b, "Value mismatch" except AssertionError as e:

50

print(e) Value mismatch

3) IndexError An IndexError exception is raised when you refer a sequence which is out of range. In the example

below, the list abc contains only 3 entries, but the 4th index is being accessed, which will result an IndexError exception.

abc=[10,20,30] print(abc[3]) --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-4-92b42b7756a1> in <module>() 1 abc=[10,20,20] ----> 2 print(abc[3]) IndexError: list index out of range

4) ValueError

A ValueError is raised when a function receives a value that has the right type but an invalid value. In example below, an int is being printed but value given is a character, hence it will raise a ValueError exception.

try: print(int('a')) except ValueError: print ('Caught ValueError Exception') else: print ('No exception') Caught ValueError Exception

Handling an Exception

Python handles exceptions using try and except blocks. In try block, we can write the code which is suspicious to raise an exception, and in except block, we can write the code which will handle this exception. Syntax:

try: You do your operations here; ...................... except ExceptionI: If there is ExceptionI, then execute this block. except ExceptionII: If there is ExceptionII, then execute this block. ...................... else: If there is no exception then execute this block.

Here are few important points about the above-mentioned syntax −

A single try statement can have multiple except statements. This is useful when the try block contains statements that may throw different types of exceptions.

You can also provide a generic except clause, which handles any exception.

After the except clause(s), you can include an else-clause. The code in the else-block executes if the code in the try: block does not raise an exception.

51

The else-block is a good place for code that does not need the try: block's protection.

Example: In the example below, Program is asking the user to input total marks scored by a student and number

of sections in exam, based on which it will calculate the average marks scored per section. Total_Marks = int(input("Enter Total Marks Scored: ")) Num_of_Sections = int(input("Enter Num of Sections: ")) Average = 0 try: Average = int(Total_Marks/Num_of_Sections) except ZeroDivisionError: print("There has to be atleast 1 or more than 1 sections.") print("Average marks scored per section is: ",Average)

Output: Enter Total Marks Scored: 5 Enter Num of Sections: 0 There has to be atleast 1 or more than 1 sections. Average marks scored per section is: 0 In above example, if we notice, the line where divison is happening is written inside try block,

because it is suspected to raise an exception in case if zero is entered for number of sections, and the except block is written to handle the corresponding exception for any such event. CONTROL STATEMENTS

Decision making is giving conditions occurring while execution of the program and specifying

actions taken according to the conditions. Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome. We

need to determine which action to take and which statements to execute if outcome is TRUE or FALSE otherwise.

Python programming language provides following types of decision making statements.

Sl.No. Statement & Description

1 if statements An if statement consists of a boolean expression followed by one or more statements.

2 if...else statements An if statement can be followed by an optional else statement, which executes when the boolean expression is FALSE.

3 nested if statements You can use one if or else if statement inside another if or else if statement(s).

1) If statements

If statement is one of the most commonly used conditional statement and decides whether certain statements need to be executed or not. If statement checks for a given condition, if the condition is true, then the set of code present inside the if block will be executed.

The If condition evaluates a Boolean expression and executes the block of code only when the Boolean expression becomes TRUE. Syntax: If (Boolean expression): Block of code #Set of statements to execute if the condition is true

52

Here, the condition will be evaluated to a Boolean expression (true or false). If the condition is true, then the statement or program present inside the if block will be executed and if the condition is false, then the statements or program present inside the if block will not be executed.

The flowchart of a if structure is as follows.

Python programming language assumes any non-zero and non-null values as TRUE, and if it is

either zero or null, then it is assumed as FALSE value. Example:mo var = 100 if ( var == 100 ) : print "Value of expression is 100" print "Good bye!" When the above code is executed, it produces the following result

Value of expression is 100 Good bye!

2) If-else statements

The statement itself tells that if a given condition is true then execute the statements present inside if block and if the condition is false then execute the else block. Else block will execute only when the condition becomes false, this is the block where you will perform some actions when the condition is not true.

If-else statement evaluates the Boolean expression and executes the block of code present inside the if block if the condition becomes TRUE and executes a block of code present in the else block if the condition becomes FALSE. Syntax:

if(Boolean expression): Block of code #Set of statements to execute if condition is true else: Block of code #Set of statements to execute if condition is false Here, the condition will be evaluated to a Boolean expression (true or false). If the condition is true

then the statements or program present inside the if block will be executed and if the condition is false then the statements or program present inside else block will be executed. Flowchart of if-else

53

If we observe the above flow chart, first the controller will come to if condition and evaluate the condition if it is true and then the statements of if block will be executed otherwise else block will be executed and later the rest of the code present outside if-else block will be executed. Example:

1 num = 5

2 if(num > 10):

3 print(“number is greater than 10”)

4 else:

5 print(“number is less than 10”)

Output: number is less than 10

This statement will always be executed. 3) elif statements

In python, we have one more conditional statement called elif statements. Elif statement is used to check multiple conditions only if the given if condition false. It's similar to an if-else statement and the only difference is that in else we will not check the condition but in elif we will do check the condition.

Elif statements are similar to if-else statements but elif statements evaluate multiple conditions. Syntax:

if (condition): #Set of statement to execute if condition is true elif (condition): #Set of statements to be executed when if condition is false and elif condition is true else: #Set of statement to be executed when both if and elif conditions are false

Example: 1 1 num = 3

2 if (num == 0):

3 print(“Number is Zero”)

4

5 elif (num > 5):

6 print(“Number is greater than 5”)

54

7

8 else:

9 print(“Number is smaller than 5”) Output: Number is greater than 5

In the above example, we have declared a variable called ‘num’ with the value as 10, and in if statement we are checking the condition if the condition becomes true. Then the block of code present inside the if condition will be executed.

If the condition becomes false then it will check the elif condition if the condition becomes true, then a block of code present inside the elif statement will be executed. If it is false then a block of code present inside the else statement will be executed. 4) Nested if-else statements

Nested if-else statement means that a if statement or if-else statement is present inside another if or if-else block. Python provides this feature to check multiple conditions in a given program.

An if statement present inside another if statement which is present inside another if statementso on. Syntax:

if(condition): #Statements to execute if condition is true if(condition): #Statements to execute if condition is true #end of nested if #end of if

The above syntax clearly says that the if block will contain another if block in it and so on. If block can contain ‘n' number of if block inside it. Example: 1 1 num = 5

2 if(num >0):

3 print(“number is positive”)

4

5 if(num<10):

6 print(“number is less than 10”) Output: number is positive

PYTHON PROGRAMMING

UNIT-IV LOOPING STATEMENTS IN PYTHON Python programming language provides 4 types of loops to handle looping requirements.

55

SL.No. Loop Type & Description

1 For loop Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.

2 Nested loops We can use one or more loop inside any another while, for or do-while loop.

3 While loop Repeats a statement or group of statements while a given condition is TRUE. It tests the condition before executing the loop body.

4 Do-While loop The do-while loop continues until a given condition satisfies.

Advantages of loops There are the following advantages of loops in Python.

1. It provides code re-usability. 2. Using loops, we do not need to write the same code again and again. 3. Using loops, we can traverse over the elements of data structures (array or linked lists).

1) FOR LOOP

The for loop is used in the case where we need to execute some part of the code until the given condition is satisfied. For loop is also called as a per-tested loop. It is better to use for loop if the number of iteration is known in advance.

Syntax of For loop in Python:

for <variable> in <sequence>: for I in [10,20,30,40,50] # body_of_loop that has set of statements which requires repeated execution Here <variable> is a variable that is used for iterating over a <sequence>. On every iteration it takes the next value from <sequence> until the end of sequence is reached.

56

Example

The following example shows the use of for loop to iterate over a list of numbers. i=0

n=10 for i in range(i,n): print(i,end = ' ')

Output: 0 1 2 3 4 5 6 7 8 9

For loop with else block In Python, we can have an optional ‘else’ block associated with the loop. The ‘else’ block

executes only when the loop has completed all the iterations. Example:

for val in range(5): print(val) else: print("The loop has completed execution") Output: 0 1 2 3 4

The loop has completed execution Note: The else block only executes when the loop is finished. Function range()

We can also use a range() function in for loop to iterate over numbers defined by range(). Syntax : range(n): generates a set of whole numbers starting from 0 to (n-1). Example: range(8) is equivalent to [0, 1, 2, 3, 4, 5, 6, 7] range(start, stop): generates a set of whole numbers starting from start to stop-1. Example: range(5, 9) is equivalent to [5, 6, 7, 8] range(start, stop, step_size):

The default step_size is 1 which is why when we didn’t specify the step_size, the numbers generated are having difference of 1. However by specifying step_size we can generate numbers having the difference

57

of step_size. Example: range(1, 10, 2) is equivalent to [1, 3, 5, 7, 9] For loop example using range() function: Here we are using range() function to calculate and display the sum of first 5 natural numbers.

# Program to print the sum of first 5 natural numbers # variable to store the sum sum = 0 # iterating over natural numbers using range() for val in range(1, 6): # calculating sum sum = sum + val # displaying sum of first 5 natural numbers print(sum) Output: 15

One-Dimensional Lists

Lists can be viewed as one-dimensional tables. A one-dimensional table can easily be represented in Python as a list. For example, the list,

>>> l = [3, 5, 7] can be viewed as the table, Multi Dimensional Lists

Multi dimensional lists are the lists within lists. It contains multiple rows and columns (table format).

Accessing a multidimensional list:

# Python program to demonstrate printing of complete multidimensional list a = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]] print(a) Output: [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]

Two-Dimensional Lists A two-dimensional table such as this is represented in Python as a list of lists, also referred to as a

two-dimensional list. An item in a two-dimensional table is typically accessed by using its “coordinates” (i.e., its row index and column index). For example, the value 8 in the table is in row 2 (counting from the topmost row and starting with index 0) and column 0 (counting from the leftmost column). In other words, 8 is located at index 0 of list t[2], or at t[2][0]

58

In general, the item located in row i and column j of a two-dimensional list t is accessed with the expression t[i][j]:

>>> t[2][0] # the element in row 2, column 0 8 >>> t[0][0] # the element in row 0, column 0 4 >>> t[1][2] # the element in row 1, column 2 9

To assign a value to the entry in row i and column j, we simply use the assignment statement. For example: >>> t[2][3] = 7

The entry in row 2 and column 3 of t is now 7: >>> t [[4, 7, 2, 5], [5, 1, 9, 2], [8, 3, 6, 7]]

We need to access all entries of a two-dimensional list in some order and not just a single entry at a specified row and column. To visit entries of a two-dimensional list systematically, the nested loop pattern is used. Two-Dimensional Lists and the Nested Loop Pattern

When we printed the value of two-dimensional list t, the output we got was a list of lists rather than a table with rows in different lines. Often it is nice to print the content of a two-dimensional list so it looks like a table. The next approach uses the iteration pattern to print each row of the table in a separate line:

>>> for row in t: print(row)

[4, 7, 2, 5] [5, 1, 9, 2] [8, 3, 6, 7] Suppose that instead of printing each row of the table as a list, we would like to have a function print2D() that prints the items in t as shown next:

>>> print2D(t) 4 7 2 5 5 1 9 2 8 3 6 7

We use the nested loop pattern to implement this function. The outer for loop is used to generate the rows, while the inner for loop iterates over the items in a row and prints them: def print2D(t): #prints values in 2D list t as a 2D table for row in t: for item in row: # print item followed by a blank space print(item, end='' )

print() # move to next line Suppose we need to develop function incr2D() that increments the value of every number in a two-dimensional list of numbers:

>>> print2D(t) 4 7 2 5 5 1 9 2 8 3 6 7 >>> incr2D(t) >>> print2D(t) 5 8 3 6 6 2 10 3 9 4 7 8

Clearly, the function incr2D() will need to execute:

59

t[i][j] += 1 for every row index i and column index j of an input two-dimensional list t. We can use the nested loop pattern to generate all combinations of row and column index. 2) Nested For loop in Python

When a for loop is present inside another for loop then it is called a nested for loop. Example:

for num1 in range(3): for num2 in range(10, 14): print(num1, ",", num2) Output: 0 , 10 0 , 11 0 , 12 0 , 13 1 , 10 1 , 11 1 , 12 1 , 13 2 , 10 2 , 11 2 , 12 2 , 13

3) Python While Loop

The while loop is to be used in the scenario where we don't know the number of iterations in advance. The block of statements is executed in the while loop until the condition specified in the while loop is satisfied. It is also called a pre-tested loop. Syntax of while loop

while condition: #body_of_while

The body_of_while is set of Python statement which requires repeated execution. These set of statements execute repeatedly until the given condition returns false. Flow of while loop 1. First the given condition is checked, if the condition returns false, the loop is terminated and the control jumps to the next statement in the program after the loop. 2. If the condition returns true, the set of statements inside loop are executed and then the control jumps to the beginning of the loop for next iteration.

These two steps happen repeatedly as long as the condition specified in while loop remains true. Example

In this example, we have a variable num and we are displaying the value of num in a loop, the loop has a increment operation where we are increasing the value of num. This is very important step, the while loop must have a increment or decrement operation, else the loop will run indefinitely, we will cover this later in infinite while loop.

num = 1 # loop will repeat itself as long as # num < 10 remains true while num < 10: print(num) #incrementing the value of num

60

num = num + 3 Output: 1 4 7

i) Infinite while loop Example 1: This will print the word ‘hello’ indefinitely because the condition will always be true.

while True: print("hello")

Example 2: num = 1 while num<5: print(num) This will print ‘1’ indefinitely because inside loop we are not updating the value of num, so the

value of num will always remain 1 and the condition num < 5 will always return true. ii) Nested while loop in Python

When a while loop is present inside another while loop then it is called nested while loop. Example:

i = 1 j = 5 while i < 4: while j < 8: print(i, ",", j) j = j + 1 i = i + 1 Output: 1 , 5 2 , 6 3 , 7

iii) While loop with else block

We can have a ‘else’ block associated with while loop. The ‘else’ block is optional. It executes only after the loop finished execution.

num = 10 while num > 6: print(num) num = num-1 else: print("loop is finished") Output: 10 9 8 7 loop is finished

61

4) Python Do While Loop

Python doesn't have do-while loop. It is also called post tested loop. It is used when it is necessary to execute the loop at least once (mostly menu driven programs).The do while loop is used to check condition after executing the statement. It is like while loop but it is executed at least once. Syntax:

do { //statement

} while (condition); Example

i = 1 while True:

print(i) i = i + 1 if(i > 5): break

Output: 1 2 3 4 5

Additional Iteration Control Statements Loop control statements change execution from its normal sequence. Python supports the following control statements.

SL.No. Control Statement & Description

1 Break statement Terminates the loop statement and transfers execution to the statement immediately following the loop.

2 Continue statement Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.

1. Break statement in Python

The break statement is used to terminate the loop when a certain condition is met. The break statement is generally used inside a loop along with a if statement so that when a particular condition (defined in if statement) returns true, the break statement is encountered and the loop terminates. Syntax: The syntax of break statement in Python

break Flow diagram:

62

Example:

In this example, we are searching a number ’88’ in the given list of numbers. The requirement is to display all the numbers till the number ’88’ is found and when it is found, terminate the loop and do not display the rest of the numbers.

# program to display all the elements before number 88 for num in [11, 9, 88, 10, 90, 3, 19]: print(num) if(num==88): print("The number 88 is found") print("Terminating the loop") break Output: 11 9 88 The number 88 is found Terminating the loop

2) Python Continue Statement The continue statement is used inside a loop to skip the rest of the statements in the body of loop

for the current iteration and jump to the beginning of the loop for next iteration. The break and continue statements are used to alter the flow of loop, break terminates the loop when a condition is met and continue skip the current iteration. Syntax : The syntax of continue statement in Python is,

Continue

Flow diagram:

63

Example: We have a list of numbers and we want to print only the odd numbers out of that list. We can do

this by using continue statement. We are skipping the print statement inside loop by using continue statement when the number is even, this way all the even numbers are skipped and the print statement executed for all the odd numbers.

# program to display only odd numbers for num in [20, 11, 9, 66, 4, 89, 44]: # Skipping the iteration when number is even if num%2 == 0: continue # This statement will be skipped for all even numbers print(num) Output: 11 9 89

CONTAINERS AND RANDOMNESS DICTIONARY Definition:

A Dictionary is a collection of unordered sequence of key-value pairs enclosed within curly braces. A Dictionary contains a collection of indices, which are called keys, and a collection of values. The association of a key and a value is called a key-value pair or sometimes an item.

The squiggly-brackets{}, represent an empty dictionary Key and value are separated by colon and the items are separated by commas. Example:

>>> Fruits= {'apple':60,'mango':89,'orange':90} >>> Fruits {'apple': 60, 'mango': 89, 'orange': 90}

Properties: 1. Each key is associated with a single value

64

2. Keys must be unique 3. Keys are immutable

Values in a dictionary can be known by accessing the key >>> Fruits['orange'] 90

Dictionary Operators The below table shows some of the operators that can be used within dictionaries.

Operation Explanation k in d True if k is a key in dictionary d, else False k not in d False if k is a key in dictionary d, else True d[k] Value corresponding to key k in dictionary d len(d) Number of (key, value) pairs in dictionary d

The dictionary class supports some of the same operators that the list class supports. The indexing operator ([]) can be used to access a value using the key as the index:

>>> days['Fr'] 'Friday'

The indexing operator can also be used to change the value corresponding to a key or to add a new (key, value) pair to the dictionary:

>>> days {'Fr': 'Friday', 'Mo': 'Monday', 'Tu': 'Tuesday', 'We': 'Wednesday', 'Th': 'Thursday'} >>> days['Sa']='Sat' >>> days {'Fr': 'Friday', 'Mo': 'Monday', 'Tu': 'Tuesday', 'We': 'Wednesday', 'Th': 'Thursday', 'Sa': 'Sat'}

Operations in a Dictionary: There are 2 operators in a Dictionary. They are,

i) Traversing Operator ii) Membership Operator

a. Traversing Operator:

Traversing a dictionary can be done with a help of for loop. For loop iterates over the keys and prints the values of a dictionary Example:

Fruits={'apple': 60, 'mango': 89, 'orange': 90} for i in Fruits: print(i)

Output : apple mango orange b. Membership Operator: Membership operator „in‟ returns True if the key is found, otherwise returns False. The in and not in operators are used to check whether an object is a key in the dictionary: Example 1: >>> Fruits

{'apple': 60, 'mango': 89, 'orange': 90} >>> 'orange' in Fruits True >>> 'lime' in Fruits False

65

Example 2:

>>> days {'Fr': 'Friday', 'Mo': 'Monday', 'Tu': 'Tuesday', 'We': 'Wednesday', 'Th': 'Thursday'} >>> 'Fr' in days True >>> 'Su' in days False >>> 'Su' not in days True

Inbuilt Functions in Dictionary

1. min() – Finds the minimum in a dictionary 2. max() – Finds the maximum in a dictionary 3. len() – Finds the Length of a dictionary

Example: >>> Fruits {'apple': 60, 'mango': 89, 'orange': 90} >>> min(Fruits) 'apple' >>> max(Fruits) 'orange' >>> len(Fruits) 3

Methods in Dictionary S.No Method name Description 1. keys() returns all the keys in a dictionary 2. values() returns all the values in a dictionary 3. items() returns all the items in a dictionary 4. get(key,default) returns the value associated with the specified key. If the key is not present , then returns the default value given 5. update(value) updates the value to the dictionary 6. pop() removes the item from the dictionary and returns the removed value 7. popitem() removes and returns an arbitrary item from the dictionary 8. clear() Removes all the items from the dictionary 9. Del an operator that deletes the dictionary itself 1. keys():

keys() method returns all the keys in a dictionary Syntax: Dictionary_name.keys() Example:

>>> Fruits {'apple': 60, 'mango': 89, 'orange': 90} >>> Fruits.keys() dict_keys(['apple', 'mango', 'orange'])

2. values(): values() method returns all the values in a dictionary

Syntax: Dictionary_name.values() Example:

Fruits {'apple': 60, 'mango': 89, 'orange': 90} >>> Fruits.values() dict_values([60, 89, 90])

66

3.items(): items() method returns all the key_value pairs

Syntax: Dictionary_name.items() Example:

>>> Fruits {'apple': 60, 'mango': 89, 'orange': 90} >>> Fruits.items() dict_items([('apple', 60), ('mango', 89), ('orange', 90)])

4. get(key,default) get() method returns the value associated with the specified key. If the key is not present , then

returns the default value given. Syntax: Dictionary_name.get(key,default) Example:

>>> Fruits {'apple': 60, 'mango': 89, 'orange': 90} >>> Fruits.get('mango',-1) 89 >>> Fruits.get('lime',-1) -1

5. update(value): update(value) updates the value to the dictionary

Syntax: Dictionary_name.update(value) Example:

>>> Fruits {'apple': 60, 'mango': 89, 'orange': 90} >>> Fruits1={'lime':10,'banana':100} >>> Fruits.update(Fruits1) >>> Fruits {'apple': 60, 'mango': 89, 'orange': 90, 'lime': 10, 'banana': 100}

6.pop(): pop() method removes the item from the dictionary and returns the removed value

Syntax: Dictionary_name.pop(key) Example:

>>> Fruits {'apple': 60, 'mango': 89, 'orange': 90, 'lime': 10, 'banana': 100} >>> Fruits.pop('mango') 89

7.popitem(): popitem() method removes and returns an arbitrary item from the dictionary

Syntax: Dictionary_name.popitem() Example:

>>> Fruits {'apple': 60, 'orange': 90, 'lime': 10, 'banana': 100} >>> Fruits.popitem() ('banana', 100) >>> Fruits {'apple': 60, 'orange': 90, 'lime': 10}

8.clear() clear() method deletes the contents from the dictionary

Syntax: Dictionary_name.clear() Example:

>>> Fruits

67

{'apple': 60, 'orange': 90, 'lime': 10} >>> Fruits.clear() >>> Fruits {}

9.Del() : The del keyword removes the item with the specified key name. thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } del thisdict["model"] print(thisdict)

Example: The del keyword can also delete the dictionary completely: thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } del thisdict print(thisdict) #this will cause an error because "thisdict" no longer exists.

Copy a Dictionary

We cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be a reference to dict1, and changes made in dict1 will automatically also be made in dict2.

There are ways to make a copy, one way is to use the built-in Dictionary method copy(). Example : Make a copy of a dictionary with the copy() method:

thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } mydict = thisdict.copy() print(mydict)

Another way to make a copy is to use the built-in method dict(). Example: Make a copy of a dictionary with the dict() method:

thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } mydict = dict(thisdict) print(mydict)

Nested Dictionaries

A dictionary can also contain many dictionaries, this is called nested dictionaries. Example : Create a dictionary that contain three dictionaries:

myfamily = { "child1" : { "name" : "Emil", "year" : 2004 },

68

"child2" : { "name" : "Tobias", "year" : 2007 }, "child3" : { "name" : "Linus", "year" : 2011 } }

Other Built-In Container Types We introduce two more useful container classes in python are tuple and set.

Tuple Definition: Tuples are ordered sequence of values separated by commas and enclosed in parenthesis. A tuple

is a sequence of immutable Python objects. Tuples are sequences, like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets. Example:

>>> t = ('a', 'b', 'c', 'd', 'e') >>> t ('a', 'b', 'c', 'd', 'e') >>> type(t) <class 'tuple'>

Tuples are immutable, the elements of a tuple cannot be over written. >>> t = ('a', 'b', 'c', 'd', 'e') >>> t[0]='d' Traceback (most recent call last): File "<pyshell#20>", line 1, in <module> t[0]='d' TypeError: 'tuple' object does not support item assignment

To create a tuple with a single element, you have to include a final comma: >>> t1 = 'a',

Another way to create a tuple is the built-in function tuple. With no argument, it creates an empty tuple: >> t = tuple()

>>> t ( )

Operations in a Tuple There are 2 operators in tuple. They are,

Repetition Operator Concatenation Operator 1. Repetition Operator: It can repeat the same tuple by number of times. Example:

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

2. Concatenation Operator: It can join 2 tuples by using’+’ operator. Example:

>>> t1=('f','g') >>> t = ('a', 'b', 'c', 'd', 'e') >>> t+t1 ('a', 'b', 'c', 'd', 'e', 'f', 'g')

Inbuilt Functions in tuple min() – Finds the minimum in a tuple max() – Finds the maximum in a tuple

69

sum() – Finds the sum of a tuple len() – Finds the Length of a tuple

Example: >>> t=(5,8,9,1,4) >>> max(t) 9 >>> min(t) 1 >>> len(t) 5 >>> sum(t) 27

Tuple Assignment

It is often useful to swap the values of two variables. With conventional assignments, we have to use a temporary variable. Example: Swap a and b values:

>>> temp = a >>> a = b >>> b = temp

This solution is cumbersome; 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 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 = '[email protected]' >>> uname, domain = addr.split('@')

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

Tuple as return values

A function can only return one value, but if the value is a tuple, the effect is the same as returning multiple values. Example:

def min_max(l): mini=min(l) maxi=max(l) return(maxi,mini) l=[20,10,30,9,8] a,b=min_max(l) print("Maximum number in the list",b) print("Minimum number in the list",a)

Output: Maximum number in the list 30 Minimum number in the list 8

Tuple Methods 1.index() - index() method find the index of the value passed as argument. Syntax: Tuplename.index(value) Example:

70

>>> T = ('ram','ravi','raja','rani') >>> T.index('rani') 3

2.count() - count() method returns the count of the value passed as argument appears in the tuple. Syntax: tuplename.count(value) Example:

>>> T=[10,10,10,20,30,40,50,90] >>> T.count(10) 3

Nesting of Tuples A Tuple can also contain many tuples are called nested tuples.

Example: tuple1 = (0, 1, 2, 3) tuple2 = ('python', 'geek') tuple3 = (tuple1, tuple2) print(tuple3)

Output : ((0, 1, 2, 3), ('python', 'geek'))

Deleting a Tuple A tuple can be deleted by using del function. Example: tuple3 = ( 0, 1)

del tuple3 print(tuple3)

Output : Error: Traceback (most recent call last): File "d92694727db1dc9118a5250bf04dafbd.py", line 6, in <module> print(tuple3) NameError: name 'tuple3' is not defined

Set in Python

A set is an unordered and unindexed collection of items. In Python sets are written with curly brackets.. Every element is unique (no duplicates) and must be immutable (which cannot be changed). However, the set itself is mutable. We can add or remove items from it. Sets can be used to perform mathematical set operations like union, intersection, symmetric difference etc. Creating a Set

Sets can be created by using the built-in set() function with an iterable object or a sequence by placing the sequence inside curly braces, separated by ‘comma’.

# Creating a Set set1 = set() print("Intial blank Set: ") print(set1) # Using the set() constructor to make a set: thisset = set(("apple", "banana", "cherry")) # note the double round-bracketsprint(thisset) # Creating a Set with the use of a List set1 = set(["Geeks", "For", "Geeks"]) print("\nSet with the use of List: ") print(set1)

Output:

71

Intial blank Set: set() {'cherry', 'apple', 'banana'} Set with the use of List: {'Geeks', 'For'}

Accessing Values in a Set We cannot access individual values in a set. We can only access all the elements together as shown

above. But we can also get a list of individual elements by looping through the set. Example :

Days=set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"]) for d in Days: print(d)

Output: Wed Sun Fri Tue Mon Thu Sat A set contains only unique elements but at the time of set creation, multiple duplicate values can

also be passed. Order of elements in a set is undefined and is unchangeable. Type of elements in a set need not be the same, various mixed up data type values can also be passed to the set.

# Creating a Set with a List of Numbers # (Having duplicate values) set1 = set([1, 2, 4, 4, 3, 3, 3, 6, 5]) print("\nSet with the use of Numbers: ") print(set1) # Creating a Set with a mixed type of values # (Having numbers and strings) set1 = set([1, 2, 'Geeks', 4, 'For', 6, 'Geeks']) print("\nSet with the use of Mixed Values") print(set1)

Output: Set with the use of Numbers: {1, 2, 3, 4, 5, 6} Set with the use of Mixed Values {1, 2, 4, 'Geeks', 6, 'For'}

Set Methods Python has a set of built-in methods that we can use on sets.

Method Description

add() Adds an element to the set

clear() Removes all the elements from the set

72

copy() Returns a copy of the set

difference() Returns a set containing the difference between two or more sets

difference_update() Removes the items in this set that are also included in another, specified set

discard() Remove the specified item

intersection() Returns a set, that is the intersection of two other sets

intersection_update() Removes the items in this set that are not present in other, specified set(s)

isdisjoint() Returns whether two sets have a intersection or not

issubset() Returns whether another set contains this set or not

issuperset() Returns whether this set contains another set or not

pop() Removes an element from the set

remove() Removes the specified element

symmetric_difference() Returns a set with the symmetric differences of two sets

symmetric_difference_update() inserts the symmetric differences from this set and another

union() Return a set containing the union of sets

update() Update the set with the union of this set and others

Adding Items to a Set We can add elements to a set by using add() method. Again as discussed there is no specific index

attached to the newly added element. Example :

Days=set(["Mon","Tue","Wed","Thu","Fri","Sat"]) Days.add("Sun") print(Days)

When the above code is executed, it produces the following result. set(['Wed', 'Sun', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat'])

Removing Item from a Set We can remove elements from a set by using discard() and remove() method.

Example 1 : Days=set(["Mon","Tue","Wed","Thu","Fri","Sat"]) Days.discard("Sun") print(Days)

When the above code is executed, it produces the following result. set(['Wed', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat'])

Example 2 :

73

# Creating a Set set1 = set([1, 2, 3, 4, 5, 6,7, 8, 9, 10, 11, 12]) print("Intial Set: ") print(set1) # Removing elements from Set using Remove() method set1.remove(5) set1.remove(6) print("\nSet after Removal of two elements: ") print(set1)

Output: Intial Set: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12} Set after Removal of two elements: {1, 2, 3, 4, 7, 8, 9, 10, 11, 12}

Using pop() method

Pop() function can also be used to remove and return an element from the set, but it removes only the last element of the set. Note: If the set is unordered then there’s no such way to determine which element is popped by using the pop() function.

# Creating a Set set1 = set([1, 2, 3, 4, 5, 6,7, 8, 9, 10, 11, 12]) print("Intial Set: ") print(set1) # Removing element from the set using the pop() method set1.pop() print("\nSet after popping an element: ") print(set1)

Output: Intial Set: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12} Set after popping an element: {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}

Using clear() method To remove all the elements from the set, clear() function is used. # Removing all the elements from set using clear() method set1.clear()

Union of Sets The union operation on two sets produces a new set containing all the distinct elements from both

the sets. Union is performed by using | operator and also using the method union().In the below example, the element “Wed” is present in both the sets.

DaysA = set(["Mon","Tue","Wed"]) DaysB = set(["Wed","Thu","Fri","Sat","Sun"]) AllDays = DaysA|DaysB print(AllDays)

When the above code is executed, it produces the following result. Please note the result has only one “wed”.

set(['Wed', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat']) Example 2:

# initialize A and B A = {1, 2, 3, 4, 5}

74

B = {4, 5, 6, 7, 8} # use union function on A >>> A.union(B) {1, 2, 3, 4, 5, 6, 7, 8}

Intersection of Sets Intersection of A and B is a set of elements that are common in both sets.Intersection is performed

using & operator. Same can be accomplished using the method intersection(). In the below example the element “Wed” is present in both the sets. DaysA = set(["Mon","Tue","Wed"]) DaysB = set(["Wed","Thu","Fri","Sat","Sun"]) AllDays = DaysA & DaysB print(AllDays)

When the above code is executed, it produces the following result. Please note the result has only one “wed”.

set(['Wed']) Example 2:

# initialize A and B A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # use intersection function on A >>> A.intersection(B) {4, 5}

Difference of Sets Difference of A and B (A - B) is a set of elements that are only in A but not in B. Similarly, B - A is

a set of element in B but not in A. Difference is performed using - operator. Same can be accomplished using the method difference(). In the below example the element “Wed” is present in both the sets so it will not be found in the result set.

DaysA = set(["Mon","Tue","Wed"]) DaysB = set(["Wed","Thu","Fri","Sat","Sun"]) AllDays = DaysA - DaysB print(AllDays)

When the above code is executed, it produces the following result. Please note the result has only one “wed”.

set(['Mon', 'Tue']) Example 2:

# initialize A and B A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # use difference function on A >>> A.difference(B) {1, 2, 3} # use difference function on B >>> B.difference(A) {8, 6, 7}

Compare Sets We can check if a given set is a subset or superset of another set. The result is True or False depending on the elements present in the sets.

DaysA = set(["Mon","Tue","Wed"]) DaysB = set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"]) SubsetRes = DaysA <= DaysB SupersetRes = DaysB >= DaysA print(SubsetRes)

75

print(SupersetRes) When the above code is executed, it produces the following result.

True True

Python Frozenset

Frozenset is a new class that has the characteristics of a set, but its elements cannot be changed once assigned. While tuples are immutable lists, frozensets are immutable sets.

Sets being mutable are unhashable, so they can't be used as dictionary keys. But, frozensets are hashable and can be used as keys to a dictionary. Definition and Usage The frozenset() function returns an unchangeable frozenset object (which is like a set object, only unchangeable). Syntax:

frozenset(iterable) Parameter Values

Parameter Description

iterable An iterable object, like list, set, tuple etc.

Example 1: mylist = ['apple', 'banana', 'cherry'] x = frozenset(mylist)

Output: frozenset({'banana', 'apple', 'cherry'})

Example 2: # initialize A and B A = frozenset([1, 2, 3, 4]) B = frozenset([3, 4, 5, 6]) >>> A.isdisjoint(B) False >>> A.difference(B) frozenset({1, 2}) >>> A | B frozenset({1, 2, 3, 4, 5, 6})

Character Encodings and Strings String objects are used to store text, that is, a sequence of characters. The characters could be upper-

and lowercase letters from the alphabet, digits, punctuation marks, and possibly symbols like the dollar sign ($). In order to create a variable whose value is the text ’An apple costs $0.99!’.

>>> text = 'An apple costs $0.99!' The variable text then evaluates to the text:

>>> text 'An apple costs $0.99!'

ASCII The American Standard Code for Information Interchange (ASCII) was developed in the

1960s. It defines a numeric code for 128 characters, punctuation, and a few other symbols common in the American English language.

The decimal ASCII code for lowercase a is 97. The & sign is encoded with decimal ASCII code 38. ASCII codes 0 through 32 and 127 include nonprintable characters, such as backspace (decimal code 8),

76

horizontal tab (decimal code 9), and line feed (decimal code 10). We can explore the ASCII encodings using the Python function ord(), which returns the decimal ASCII code of a character:

>>> ord('a') 97 The sequence of characters of a string value (such as 'dad') is encoded as a sequence of ASCII codes

100, 97, and 100. What is stored in memory is exactly this sequence of codes. Of course, each code is stored in binary. As ASCII decimal codes go from 0 to 127, they can be encoded with seven bits; because a byte (eight bits) is the smallest memory storage unit, each code is stored in one byte.

The symbol &, for example, is encoded with decimal ASCII code 38, which corresponds to binary code 0100110 or hex code 0x26.

>>> encoding('dad') Char Decimal Hex Binary d 100 64 1100100 a 97 61 1100001 d 100 64 1100100

The function chr() is the inverse of function ord(). It take a numeric code and returns the character corresponding to it.

>>> chr(97) 'a'

Unicode Unicode was developed to be the universal character-encoding scheme. It covers all characters in

all written languages, modern or ancient, and includes technical symbols from science, engineering, and mathematics, punctuation, and so on. In Unicode, every character is represented by an integer code point. The code point is not necessarily the actual byte representation of the character, however; it is just the identifier for the particular character.

For example, the code point for lowercase ‘k’ is the integer with hex value 0x006B, which corresponds to decimal value 107. 107 is also the ASCII code for letter ‘k’. Unicode conveniently uses a code point for ASCII characters that is equal to their ASCII code. To include character ‘k’, for example, you would use the Python escape sequence \u006B:

>>> '\u006B' 'k' In the next example, the escape sequence \u0020 is used to denote the Unicode character with code

point 0x0020 (in hex, corresponding to decimal 32). >>> 'Hello\u0020World !' 'Hello World !'

We now try a few examples in several different languages. Let’s start with my name in Cyrillic: >>> '\u0409\u0443\u0431\u043e\u043c\u0438\u0440' 'Љубомир' Here is ‘Hello World!’ in Greek: >>> '\u0393\u03b5\u03b9\u03b1\u0020\u03c3\u03b1\u03c2 \u0020\u03ba\u03cc\u03c3\u03bc\u03bf!' 'Γεια σας κόσμο!' Finally, let’s write ‘Hello World!’ in Chinese: >>> chinese = '\u4e16\u754c\u60a8\u597d!' >>> chinese '世界您好!

Let’s check that the basic string operators work on this string. >>> len(chinese) 5 >>> chinese[0] '世'

String operators also work on the alphabet used in the string. The ord() and chr() functions extend from ASCII to Unicode:

77

>>> ord(chinese[0]) 19990 >>> chr(19990) '世'

UTF-8 Encoding for Unicode Characters ASCII text is a Unicode text encoded with the UTF-8 encoding. In some situations, our Python

program will receive text without a specified encoding. In that case, Python treat the “text” as a sequence of raw bytes stored in an object of type bytes. This is because files downloaded from the web could be images, video, audio, and not just text.

Consider this content of a text file downloaded from the web: >>> content b'This is a text document\nposted on the\nWWW.\n' Variable content refers to an object of type bytes. As we can verify, the letter b in the front of the

“string” indicates that: >>> type(content) <class 'bytes'> To decode it to a string encoded using the UTF-8 Unicode encoding, we need to use the decode()

method of the bytes class: >>> content.decode('utf-8') 'This is a text document\nposted on the\nWWW.\n'

Module random

Python can generate such random numbers by using the random module. As usual, if we need to use functions in the random module, we need to import it first:

>>> import random Generating a Single Random Number

The random() method in random module generates a float number between 0 and 1. Example:

import random n = random.random() print(n)

Output 0.2112200

Generating Number in a Range The randint() method generates a integer between a given range of numbers.

Example: import random n = random.randint(0,22) print(n)

Output 2

Generating a List of numbers Using For Loop We can use the above randint() method along with a for loop to generate a list of numbers. We

first create an empty list and then append the random numbers generated to the empty list one by one. Example:

import random randomlist = [] for i in range(0,5): n = random.randint(1,30) randomlist.append(n)

78

print(randomlist) Output

[10, 5, 21, 1, 17] Using random.sample()

We can also use the sample() method available in random module to directly generate a list of random numbers. Here, we specify a range and give how many random numbers we need to generate. Example:

import random #Generate 5 random numbers between 10 and 30 randomlist = random.sample(range(10, 30), 5) print(randomlist)

Output [16, 19, 13, 18, 15]

PYTHON PROGRAMMING

UNIT-V

NAMESPACES Encapsulation in Functions

Encapsulation is the packing of data and functions operating on that data into a single component and restricting the access to some of the object’s components. Encapsulation means that the internal representation of an object is generally hidden from view outside of the object’s definition. A class is an example of encapsulation as it encapsulates all the data that is member functions, variables.

I. Difference between Abstraction and Encapsulation Abstraction is a mechanism which represents the essential features without including

implementation. Encapsulation — Information hiding. Abstraction — Implementation hiding.

Private members: Using OOP in Python, we can restrict access to methods and variables. This prevents data from

direct modification which is called encapsulation. In Python, we denote private attribute using underscore as prefix i.e single “ _ “ or double “ __“.. Example of accessing private member data

class Person: def __init__(self): self.name = 'Manjula' self.__lastname = 'Dube' def PrintName(self): return self.name +' ' + self.__lastname #Outside class P = Person()print(P.name) print(P.PrintName())

79

print(P.__lastname) #AttributeError: 'Person' object has no attribute '__lastname'

II. Code Reuse and Modularity

A function is a block of code which is used to perform some action, and it is also called as reusable code. A function provides higher modularity and code re-usability.

As Python is an interpreted language, it follows a top-down approach. The most important factor in any programming language is the ‘modules’. The module is a program that can be included or imported to the other programs so that it can be reused in the future without writing the same module again.

Python that helps us to invoke the functions automatically by operating the system during run-time or when the program is executed, and this is what we call as the main function. Example :

1 print(“Good Morning”)

2

3 def main():

4 print(“Hello Python”)

5

6 print(“Good Evening”)

Output: Good Morning Good Evening If we observe the above program, it has printed only ‘Good Morning’ and ‘Good Evening’ and it

did not print the term ‘Hello Python’ which is because we didn’t call it manually or we didn’t use the python’s main function here. Modularity

Modularity refers to the act of partitioning the code into modules building them first followed by linking and finally combining them to form a complete project. Modularity ensures re-usability and minimize the duplication.

A module in Python is nothing but a file containing Python definitions followed by methods & statements. The module name is generated out of the file name by removing the suffix “.py”. For example, if the file name is fibonacci.py, the module name is fibonacci. Let's create a module. We save the following code in the file fibonacci.py:

def fib(n): if n == 0: return 0 elif n == 1: return 1 else: return fib(n-1) + fib(n-2) def ifib(n): a, b = 0, 1 for i in range(n): a, b = b, a + b return a

We can import this module in the interactive python shell and call the functions by prefixing them with "fibonacci.":

>>> import fibonacci

80

>>> fibonacci.fib(30) 832040

NAMESPACES

A name in Python is a way to access a variable like in any other languages. Python is more flexible when it comes to the variable declaration. We can declare a variable by assigning a name to it. We can use names to reference values. Example:

num = 5 str = 'Z' seq = [0, 1, 1, 2, 3, 5] #We can even assign a name to a function. def function(): print('It is a function.') foo = function foo() A namespace is a simple system to control the names in a program. A namespace is a dictionary of

variable names (keys) and their corresponding objects (values). Namespaces play a key role in the execution of function calls and the normal control flow of a program. Python implements namespaces in the form of dictionaries. It maintains a name-to-object mapping where names act as keys and the objects as values. Multiple namespaces may have the same name but pointing to a different variable. Types of Namespaces

1. Local Namespace Creation of local functions creates the local namespace. This namespace covers the local names

inside a function. Python creates this namespace for every function called in a program. It remains active until the function returns.

2. Global Namespace When a user creates a module, a global namespace gets created. This namespace covers the names

from various imported modules used in a project. Python creates this namespace for every module included in your program. It’ll last until the program ends.

3. Built-in Namespace

81

This namespace covers the built-in functions and built-in exception names. Python creates it as the interpreter starts and keeps it until you exit. The built-in namespace encompasses global namespace and global namespace encompasses local namespace. Some functions like print(), id() are examples of built in namespaces. Lifetime of a namespace:

A lifetime of a namespace depends upon the scope of objects, if the scope of an object ends, the lifetime of that namespace comes to an end. It is not possible to access inner namespace’s objects from an outer namespace.

Scopes A scope refers to a region of a program where a namespace can be directly accessed, i.e. without

using a namespace prefix. The scope of a name is the area of a program where this name can be unambiguously used, for example, inside of a function. A name's namespace is identical to its scope. Scopes are defined statically, but they are used dynamically.

During program execution there are the following nested scopes available: the innermost scope is searched first and it contains the local names the scopes of any enclosing functions, which are searched starting with the nearest enclosing scope the next-to-last scope contains the current module's global names the outermost scope, which is searched last, is the namespace containing the built-in names.

Example:

# var1 is in the global namespace var1 = 5 def some_func(): # var2 is in the local namespace var2 = 6 def some_inner_func(): # var3 is in the nested local # namespace var3 = 7

Modules as Namespaces

Module is a file consisting of Python code. A module can define functions, classes and variables. When the module is executed (imported), and then the module is (also) a namespace. This namespace has a name, which is the name of the module. In this namespace, the names that are defined in the global scope of the module: the names of functions, values, and classes defined in the module. These names are all referred to as the module’s attributes.

1. Module Attributes To get access to all the functions in the Standard Library module math, we import the module: >>> import math Once a module is imported, the Python built-in function dir() can be used to view all the module’s

attributes. dir() is a powerful inbuilt function in Python3, which returns list of the attributes and methods of any object (say functions , modules, strings, lists, dictionaries etc.) Syntax :

dir({object}) Example:

>>> dir(math) ['__doc__', '__file__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'factorial', 'floor', 'fmod', 'frexp',

82

'fsum', 'hypot', 'isinf', 'isnan', 'ldexp', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc'] Python - Math Module

Some of the most popular mathematical functions are defined in the math module. These include trigonometric functions, representation functions, logarithmic functions, angle conversion functions, etc.

Pie (π) is a well-known mathematical constant, which is defined as the ratio of the circumference to the diameter of a circle and its value is 3.141592653589793.

>>> import math >>>math.pi 3.141592653589793

Another well-known mathematical constant defined in the math module is e. It is called Euler's number and it is a base of the natural logarithm. Its value is 2.718281828459045.

>>>math.e 2.718281828459045

Locating Modules

When you import a module, the Python interpreter searches for the module in the following sequences

The current directory. If the module is not found, Python then searches each directory in the shell variable PYTHONPATH. If all else fails, Python checks the default path. On UNIX, this default path is normally /usr/local/lib/python3/.

The module search path is stored in the system module sys as the sys.path variable. The sys.path variable contains the current directory, PYTHONPATH, and the installation dependent default.

2. Python - Sys Module The sys module provides functions and variables used to manipulate different parts of the Python

runtime environment. i) sys.path This is an environment variable that is a search path for all Python modules.

>>>sys.path ['', 'C:\\python36\\Lib\\idlelib', 'C:\\python36\\python36.zip', 'C:\\python36\\DLLs', 'C:\\python36\\lib', 'C:\\python36', 'C:\\Users\\acer\\AppData\\Roaming\\Python\\Python36\\site-packages', 'C:\\python36\\lib\\site-packages']

ii) sys.version This attribute displays a string containing the version number of the current Python interpreter.

>>>sys.version '3.7.0 (v3.7.0:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)]'

iii) sys.maxsize Returns the largest integer a variable can take.

>>> import sys >>>sys.maxsize 9223372036854775807

iv) sys.exit This causes the script to exit back to either the Python console or the command prompt. This is

generally used to safely exit from the program in case of generation of an exception. 3. Top-Level Module A computer application is a program that is typically split across multiple files (i.e., modules). In every

Python program, one of the modules is special: It contains the “main program” by which we mean the code

83

that starts the application. This module is referred to as the top-level module. The remaining modules are essentially “library” modules that are imported by the top-level module and contain functions and classes that are used by the application.

We have seen that when a module is imported, the Python interpreter creates a few “bookkeeping” variables in the module namespace. One of these is variable __name__. Python will set its value in this way:

• If the module is being run as a top-level module, attribute __name__ is set to the string __main__. • If the file is being imported by another module, whether the top-level or other, at- tribute __name__ is set to the module’s name.

We use the next module to illustrate how __name__ is assigned: print('My name is {}'.format(__name__))

When this module is executed by running it from the shell (e.g., by hitting F5 in the IDLE shell), it is run as the main program (i.e., the top-level module):

>>> My name is __main__ So the __name__ attribute of the imported module is set to __main__. The module name is also the top-level module when it is run at the command line:

> python name.py My name is __main__ If, however, another module imports module name, then module name will not be top level. In the next import statement, the shell is the top-level program that imports the mod- ule name.py:

>>> import name My name is name

Here is another example. The next module has only one statement, a statement that imports module name.py:

import name When module import.py is run from the shell, it is run as the main program that imports module name.py:

>>> My name is name

In both cases, the __name__ attribute of the imported module is set to the name of the module. The __name__ attribute of a module is useful for writing code that should be executed only when

the module is run as the top-level module. This would be the case, for example, if the module is a “library” module that contains function definitions and the code is used for debugging. All we need to do is make the debugging code a code block of this if statement:

if __name__ == '__main__': # code block

If the module is run as a top-level module, the code block will be executed; otherwise it will not. Different Ways to Import Module Attributes

We have three different ways to import a module and its attributes. We again use the module example as our running example:

1 'an example module' 2 def f(): 3 print('Executing f()') 4 5 def g(): 6 print('Executing g()') 7 8 x=0 # global var

One way to get access to functions f() or g(), or global variable x, is to: >>> import example

This import statement will find the file example.py and run the code in it. This will instantiate two function objects and one integer object and create a namespace, called example, where the names of the created

84

objected will be stored. In order to access and use the module attributes, we need to specify the module namespace:

>>> example.f() Executing f()

As we have seen, calling f() directly would result in an error. Therefore, the import statement did not bring name f into the namespace of module __main__ (the module that imported example); it only brings the name of the module example, as illustrated below. Instead of importing the name of the module, it is also possible to import the names of the needed attributes themselves using the from command:

>>> from example import f As illustrated in above diagram, from copies the name of attribute f to the scope of the main program, the module doing the import, so that f can be referred to directly, without having to specify the module name.

>>> f() Executing f()

Finally, is is also possible to use from to import all the attributes of a module using the wild card *: >>> from example import * >>> f() Executing f() >>> x 0

The below diagram shows that all the attributes of example are copied to the namespace__main__. Exceptional Control Flow

Exception is an abnormal condition that halts the execution of the program. The default exceptional control flow is to stop the program and print the error message contained in the exception object.

I. Exceptions and Exceptional Control Flow

When an exception occurs, the normal flow of execution is interrupted and leads to an error message. Example :

1. a = int(input("Enter a:")) 2. b = int(input("Enter b:")) 3. c = a/b; 4. print("a/b = %d"%c) 5. 6. #other code: 7. print("Hi I am other part of the program") Output:

Enter a:10 Enter b:0 Traceback (most recent call last): File "exception-test.py", line 3, in <module> c = a/b; ZeroDivisionError: division by zero

85

When execution returns to the shell, the information contained in the exception object is printed in the shell. In addition to the type of error and a friendly error message, the output also includes a traceback, which consists of all the function calls that got interrupted by the error.

II. Catching and Handling Exceptions

All the runtime (and syntax) errors that we have encountered are called exceptions in Python. All exceptions are subclasses of the Exception class.

When an exception occurs, the normal flow of execution is interrupted. Python checks to see if the line of code which caused the exception is inside a try block. If it is, it checks to see if any of the except blocks associated with the try block can handle that type of exception. If an appropriate handler is found, the exception is handled, and the program continues from the next statement after the end of that try-except.

The format of a try/except pair of statements is: try: <indented code block 1> except: <indented code block 2> <non-indented statement> The execution of <indented code block 1> is attempted first. If it goes through without any raised

exceptions, then <indented code block 2> is ignored and execution continues with <non-indented statement>. Example :

>>> n = int(raw_input("Please enter a number: ")) Please enter a number: 23.5 Output: Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: '23.5' Assuming we want to ask the user to enter an integer number. If we use a raw_input(), the input

will be a string, which we have to cast into an integer. If the input has not been a valid integer, we will generate (raise) a ValueError.

With the aid of exception handling, we can write robust code for reading an integer from input: while True: try: n = raw_input("Please enter an integer: ") n = int(n) break except ValueError: print("No valid integer! Please try again ...") print "Great, you successfully entered an integer!"

The while loop is entered. The code within the try clause will be executed statement by statement.

If no exception occurs during the execution, the execution will reach the break statement and the while loop will be left. If an exception occurs, i.e. in the casting of n, the rest of the try block will be skipped and the except clause will be executed. The raised error, in our case a ValueError, has to match one of the names after except. In our example only one, i.e. "ValueError:". After having printed the text of the print statement, the execution does another loop. It starts with a new raw_input(). Advantages of exception handling:

1. It separates normal code from code that handles errors.

86

2. Exceptions can easily be passed along functions in the stack until they reach a function which knows how to handle them. The intermediate functions don’t need to have any error-handling code.

3. Exceptions come with lots of useful error information built in – for example, they can print a traceback which helps us to see exactly where the error occurred.

III. Declaring multiple exceptions The python allows us to declare the multiple exceptions with the except clause. Declaring multiple

exceptions is useful in the cases where a try block throws multiple exceptions. Syntax:

try: #block of code except (<Exception 1>,<Exception 2>,<Exception 3>,...<Exception n>) #block of code else: #block of code

Example: try: a=10/0; except ArithmeticError,StandardError: print "Arithmetic Exception" else: print "Successfully Done"

Output:

Arithmetic Exception IV. The finally block

We can use the finally block with the try block in which, we can pace the important code which must be executed before the try statement throws an exception. ntax

try: # block of code # this may throw an exception finally: # block of code # this will always be executed

87

The finally clause will be executed at the end of the try-except block – if there is no exception, if an

exception is raised and handled, if an exception is raised and not handled, and even if we exit the block using break, continue or return. We can use the finally clause for cleanup code that we always want to be executed:

try: age = int(input("Please enter your age: ")) except ValueError: print("Hey, that wasn't a number!") else: print("I see that you are %d years old." % age) finally: print("It was really nice talking to you. Goodbye!")

Important Two Mark Questions with Answers 1) What is Python? What are the benefits of using Python? Python is a programming language with objects, modules, threads, exceptions and automatic memory management. It is a high-level, interpreted, interactive, and object-oriented scripting language. Python is designed to be highly readable. The benefits of pythons are that it is simple and easy, portable, extensible, build-in data structure and it is an open source. 2) What are the applications of Python? Python is used in various software domains some application areas are given below.

Web and Internet Development Games Scientific and computational applications Language development Image processing and graphic design applications What are the advantages of Python? Interpreted Free and open source Extensible Object-oriented Built-in data structure Readability High-Level Language Cross-platform

3) What are the supported data types in Python? Python has five standard data types:

Numbers Strings Lists Tuples Dictionaries

4) What are the built-in type does python provides? There are mutable and Immutable types of Pythons built in types Mutable built-in types

List Sets Dictionaries

Immutable built-in types

88

Strings Tuples Numbers

5) What is namespace in Python? In Python, every name introduced has a place where it lives and can be hooked for. This is known as namespace. It is like a box where a variable name is mapped to the object placed. Whenever the variable is searched out, this box will be searched, to get corresponding object. 6) What is a dictionary in Python? Python dictionary is one of the supported data types in Python. It is an unordered collection of elements. The elements in dictionaries are stored as key–value pairs. Dictionaries are indexed by keys. For example, we have a dictionary named ‘dict’. It contains some keys: Country, Capital along with their corresponding values: India and New Delhi. dict={‘Country’:’India’,’Capital’:’New Delhi’, } 7) What is the difference between arrays and lists.

Arrays Lists

Arrays can only store homogeneous data (data of the same type).

Lists can store heterogenous and arbitrary data.

Since only one type of data can be stored, arrays use memory for only one type of objects. Thus, mostly, arrays use lesser memory than lists.

Lists can store data of multiple data types and thus require more memory than arrays.

Length of an array is pre-fixed while creating it, so more elements cannot be added.

Since the length of a list is not fixed, appending items in it is possible.

8) What is negative index in Python? Python sequences can be index in positive and negative numbers. For positive index, 0 is the first index, 1 is the second index and so forth. For negative index, (-1) is the last index and (-2) is the second last index and so forth. 9) What are local variables and global variables in Python? Global Variables: Variables declared outside a function or in global space are called global variables. These variables can be accessed by any function in the program. Local Variables: Any variable declared inside a function is known as a local variable. This variable is present in the local space and not in the global space. Example: 1 2 3 4 5 6

a=2 def add(): b=3 c=a+b print(c) add()

10) What is the difference between lists and tuples?

Lists Tuples

Lists are mutable, i.e., they can be edited.

Tuples are immutable (Tuples are lists which cannot be edited).

89

Lists are usually slower than tuples. Tuples are faster than lists.

Syntax: list_1 = [10, ‘Intellipaat’, 20] Syntax: tup_1 = (10, ‘Intellipaat’ , 20)

11) What are functions in Python? A function is a block of code which is executed only when it is called. To define a Python function, the def keyword is used. Example: 1 2 3

def Newfunc(): print("Hi, Welcome to Edureka") Newfunc(); #calling the function

Output: Hi, Welcome to Edureka 12) How can you generate random numbers in Python? Random module is the standard module that is used to generate a random number. The method is defined as: 1 2

import random random.random

13) How do you write comments in python? Comments in Python start with a # character. However, alternatively at times, commenting is done using docstrings(strings enclosed within triple quotes). Example: #Comments in Python start like this print("Comments in Python start with a #") Output: Comments in Python start with a # 14) What are docstrings in Python? Docstrings are not actually comments, but, they are documentation strings. These docstrings are within triple quotes. They are not assigned to any variable and therefore, at times, serve the purpose of comments as well. Example:

""" Using docstring as a comment. This code divides 2 numbers """

15) What is tuple in Python? A tuple is a built-in data collection type. It allows us to store values in a sequence. It is immutable, so no change is reflected in the original data. It uses () brackets rather than [] square brackets to create a tuple. We cannot remove any element but can find in the tuple. We can use indexing to get elements. It also allows traversing elements in reverse order by using negative indexing. Tuple supports various methods like max(), sum(), sorted(), Len() etc. 16) What are the different types of operators in Python? Python uses a rich set of operators to perform a variety of operations. Some individual operators like membership and identity operators are not so familiar but allow to perform operations.

Arithmetic Operators Relational Operators Assignment Operators Logical Operators Membership Operators Identity Operators Bitwise Operators

17) What is slicing in Python?

90

Slicing is a mechanism used to select a range of items from sequence type like list, tuple, and string. It is beneficial and easy to get elements from a range by using slice way. It requires a : (colon) which separates the start and end index of the field. 18) What is an error in Python? Error caused by not following the proper structure (syntax) of the language is called syntax error or parsing error.

>>> if a < 3 File "<interactive input>", line 1 if a < 3 SyntaxError: invalid syntax

19) What is an exception? Errors can also occur at runtime and these are called exceptions. For example, when a file we try to open does not exist (FileNotFoundError), dividing a number by zero (ZeroDivisionError), module we try to import is not found (ImportError) etc.