0% found this document useful (0 votes)
20 views161 pages

5.teaching Notes

Python is an open-source, high-level, object-oriented programming language created by Guido van Rossum in the early 1990s. It features simplicity, ease of learning, portability, and supports multiple programming paradigms. The document also covers installation steps, basic syntax, variable naming rules, and programming style guidelines.

Uploaded by

hod.csd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views161 pages

5.teaching Notes

Python is an open-source, high-level, object-oriented programming language created by Guido van Rossum in the early 1990s. It features simplicity, ease of learning, portability, and supports multiple programming paradigms. The document also covers installation steps, basic syntax, variable naming rules, and programming style guidelines.

Uploaded by

hod.csd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 161

Introduction to Python| Unit- 1

Introduction to Python
What is Python?
 Python is an open source, object-oriented, general purpose language ,high-level
programming language.
 Developed by Guido van Rossum in the early 1990s. Named after Monty Python
 Python runs on many Unix variants, on the Mac, and on Windows 2000 and later i.e
portable
 Python is multi-paradigm programming language .Paradigm means rules and
regulations for organizing data and instructions such as OO, structured, function
oriented.
History
 The name Python was selected from "Monty Python’s Flying Circus" which was a
British sketch comedy series created by the comedy group Monty Python and
broadcast by the BBC from 1969 to 1974.
 Python was created in the early 1990s by Guido van Rossum at the National Research
Institute for Mathematics and Computer Science in Netherlands.
 Python was created as a successor of a language called ABC (All Basic Code) and
released publicly in1991. Guido remains Python’s principal author, although it
includes many contributions from active user community.
 Between 1991 and 2001 there are several versions released, current stable release is
3.6
 In 2001 the Python Software Foundation (PSF) was formed, a non-profit
organization created specifically to own Python-related Intellectual Property. Zope
Corporation is a sponsoring member of the PSF.

Features of Python
1. Simple :Python is a simple and minimalistic language. Reading a good Python
program feels almost like reading English, although very strict English! This pseudo-
code nature of Python is one of its greatest strengths.
2. Easy to Learn:Python is extremely easy to get started with and has an
extraordinarily simple syntax
3. Free and Open Source :Python is an example of a FLOSS (Free/Libré and Open
Source Software). In simple terms, you can freely distribute copies of this software,
read it's source code, make changes to it, use pieces of it in new free programs, and
that you know you can do these things.
4. High Level: Python is a high level language as it offers high level data-structures that
reduce development time as well as code size, resulting in more readable code.Useful
types like Python's lists (resizeable arrays) and dictionaries (hash tables) are built into
the language.

1|
Introduction to Python| Unit- 1
5. Object Oriented :Python is a full featured object-oriented programming language
with features such as classes,inheritance,objects and overloading. Actually it is not
just OO language like Java or Ruby but a pleasant mix of multiple programming
paradigms Lisp and Haskell.
6. Scalable : Python encourages clean code design, high-level structure, and
"packaging" of multiple components, all of which deliver the flexibility, consistency,
and faster development time required as projects expand in breadth and scope.
7. Extensible :Python is referred as a “glue language” meaning that it is capable to work
in mixed language environment.The python interpreter is easily extended and can add
a new built-in function or modules written in c/c++/Java code. The interface is exactly
the same as for pure modules.
8. Portable : Due to its open-source nature, Python has been ported (i.e. changed to
make it work on) to many platforms. All your Python programs can work on any of
these platforms without requiring any changes at all . Python can be used on Linux,
Windows, FreeBSD, Macintosh, Solaris even PocketPC .
9. Interpreted and (Byte-) Compiled: A program written in a compiled language like C
or C++ is translated from the source language i.e. C/C++ into a language spoken by
your computer (binary code i.e. 0s and 1s) using a compiler with various flags and
options. When you run the program, the linker/loader software just stores the binary
code in the computer's memory and starts executing from the first instruction in the
program. When you use an interpreted language like Python, there is no separate
compilation and execution steps. You just run the program from the source code.
Internally, Python converts the source code into an intermediate form called
bytecodes and then translates this into the native language of your specific computer
and then runs it. All this makes using Python so much easier. You just run your
programs - you never have to worry about linking and loading with libraries, etc.
They are also more portable this way because you can just copy your Python program
into another system of any kind and it just works!

Installing Python
In order to use Python, it must first be installed on your computer. Follow these steps.
Go to the python website www.python.org and click on the 'Download' menu choice.

2|
Introduction to Python| Unit- 1

Step 2) Once the download is complete, run the exe for install Python. Now click on Install Now.

3|
Introduction to Python| Unit- 1

Step 3) You can see Python installing at this point.

Step 4) When it finishes, you can see a screen that says the Setup was successful. Now
click on "Close".

4|
Introduction to Python| Unit- 1

After installed, you should now have a Python menu choice. Start the program by choosing IDLE (Python GUI)

This starts the python shell.

5|
Introduction to Python| Unit- 1

Try typing the following commands

4+4
Print( 'Hello world!')

In order to do more elaborate programs, normally people store all the commands in a file. To open a file to use in this way, go to
File -> New Window.

6|
Introduction to Python| Unit- 1

In this file enter your print command.

Save your file by going to File -> Save

7|
Introduction to Python| Unit- 1

Give the file a name and put the .py suffix on it.

Run your program, by going to Run -> Run Module.

8|
Introduction to Python| Unit- 1

Here is what the output will look like.

Running Python
There are three different ways to start Python :
1)Interactive Interpreter from the Command Line
2)As a Script from the Command Line
3)In an Integrated Development Environment

9|
Introduction to Python| Unit- 1
Getting Started
 In all interactive examples, you will see the Python primary ( >>>) and secondary
( ...) prompts.
 The primary prompt is a way for the interpreter to let you know that it is expecting
the next Python statement
 The secondary prompt indicates that the interpreter is waiting for additional input
to complete the current statement.
 Two primary ways that Python "does things" for you: statements and expressions
 A statement is a body of control which involves using keywords. It is similar to
issuing a command to the interpreter. Statements may or may not lead to a result
or output. For ex.

>>>print('Hello World!')
Hello World!

Expressions, on the other hand, do not use keywords. They can be simple equations that
you use with mathematical operators, or can be functions which are called with
parentheses. They may or may not take input, and they may or may not return a
(meaningful) value. (Functions that do not explicitly
return a value by the programmer automatically return None, Python's equivalent to
NULL.) For ex.

>>>abs(4)
4
>>>abs(-4)
4
Program Output, the printStatement
 To see the contents of a variable, you use theprint statement in your code. However,
from within the interactive interpreter, you can use the print statement to give you the
string representation of a variable, or just dump the variable raw. This is
accomplished by simply giving the name of the variable.
>>>myString = 'Hello World!'
>>> print (myString)
Hello World!
>>>myString
'Hello World!'
 Python's printstatement, paired with the string format operator ( %), supports string
substitution, much like the printf()function in C:

>>> print ( "%s is number %d!" ) % ("Python", 1)


Python is number 1!

10|
Introduction to Python| Unit- 1
Program Input and the raw_input()Built-in Function
The easiest way to obtain user input from the command line is with the raw_input()built-
in function. It reads from standard input and assigns the string value to the variable
>>> user = raw_input('Enter login name: ')
Enter login name: root
>>>print 'Your login is:' user
Your login is: root
You can use the int() built-in function to convert any numeric input string to an integer
representation.
>>> num = raw_input('Now enter a number: ')
Now enter a number: 1024
>>> print 'Doubling your number: %d' % ( int(num) * 2 )
Doubling your number: 2048
The int()function converts the string numto an integer so that the mathematical operation
can be performed.

Ask for help in the interactive interpreter

It is easy to get help on a new function just by calling the help()built-in function and
passing in the name of the function you want help with:
>>> help(raw_input)

Help on built-in function raw_input in module __builtin__:


raw_input(...)
raw_input([prompt]) -> string

Read a string from standard input. The trailing newline is stripped. If the user hits EOF
(Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError. On Unix, GNU readline is used
if enabled. The prompt string, if given, is printed without a
trailing newline before reading.'

Comments
As with most scripting and Unix-shell languages, the hash or pound ( #) sign signals that
a comment begins from the #and continues until the end of the line.
>>> # one comment
... print'Hello World!' # another comment
Hello World!

Python Syntax
Introduction

11|
Introduction to Python| Unit- 1
A Python program is read by a parser. Python was designed to be a highly readable language. The
syntax of the Python programming language is the set of rules which defines how a Python program
will be written.
Python Line Structure
A Python program is divided into a number of logical lines and every logical line is terminated by the
token NEWLINE. A logical line is created from one or more physical lines.
A line contains only spaces, tabs, formfeeds possibly a comment, is known as a blank line, and
Python interpreter ignores it.
A physical line is a sequence of characters terminated by an end-of-line sequence (in windows it is
called CR LF or return followed by a linefeed and in Unix, it is called LF or linefeed). See the
following example.

Comments in Python
A comment begins with a hash character(#) which is not a part of the string literal and ends at the end
of the physical line. All characters after the # character up to the end of the line are part of the
comment and the Python interpreter ignores them. See the following example. It should be noted that
Python has no multi-lines or block comments facility.

Joining two lines


When you want to write a long code in a single line you can break the logical line in two or more
physical lines using backslash character(\). Therefore when a physical line ends with a backslash
characters(\) and not a part of a string literal or comment then it can join another physical line. See
the following example.

12|
Introduction to Python| Unit- 1

Multiple Statements on a Single Line


You can write two separate statements into a single line using a semicolon (;) character between two
line.

Indentation
Python uses whitespace (spaces and tabs) to define program blocks whereas other languages like C,
C++ use braces ({}) to indicate blocks of codes for class, functions or flow control. The number of
whitespaces (spaces and tabs) in the indentation is not fixed, but all statements within the block must
be the indented same amount. In the following program, the block statements have no indentation.

13|
Introduction to Python| Unit- 1

This is a program with single space indentation.

This is a program with single tab indentation.

14|
Introduction to Python| Unit- 1

Here is another program with an indentation of a single space + a single tab.

Python Coding Style


 Use 4 spaces per indentation and no tabs.
 Do not mix tabs and spaces. Tabs create confusion and it is recommended to use only spaces.
 Maximum line length : 79 characters which help users with a small display.
 Use blank lines to separate top-level function and class definitions and single blank line to separate methods definitions inside a
class and larger blocks of code inside functions.
 When possible, put inline comments (should be complete sentences).
 Use spaces around expressions and statements.

Python Reserve words

15|
Introduction to Python| Unit- 1
The following identifiers are used as reserved words of the language, and cannot be used as ordinary
identifiers.
False Class finally is return

None Continue for lambda try

True def from nonlocal while

and del global not with

as el if or yield

assert else import pass

break except In raise

Python Variable
Variable and Value
 A variable is a memory location where a programmer can store a value. Example :roll_no, amount, name etc.
 Value is either string, numeric etc. Example : "Sara", 120, 25.36
 Variables are created when first assigned.
 Variables must be assigned before being referenced.
 The value stored in a variable can be accessed or updated later.
 No declaration required
 The type (string, int, float etc.) of the variable is determined by Python
 The interpreter allocates memory on the basis of the data type of a variable.
Python Variable Name Rules
 Must begin with a letter (a - z, A - B) or underscore (_)
 Other characters can be letters, numbers or _
 Case Sensitive
 Can be any (reasonable) length
 There are some reserved words which you cannot use as a variable name because Python uses them for other things.
Good Variable Name
 Choose meaningful name instead of short name. roll_no is better than rn.
 Maintain the length of a variable name. Roll_no_of_a-student is too long?
 Be consistent; roll_no or orRollNo
 Begin a variable name with an underscore(_) character for a special case.
Python Assignment Statements
The assignment statement creates new variables and gives them values. Basic assignment statement
in Python is :
Syntax
<variable> = <expr>
Where the equal sign (=) is used to assign value (right side) to a variable name (left side). See the
following statements :
1. >>> Item_name = "Computer" #A String
2. >>> Item_qty = 10 #An Integer
3. >>> Item_value = 1000.23 #A floating point

16|
Introduction to Python| Unit- 1
4. >>> print(Item_name)
5. Computer
6. >>> print(Item_qty)
7. 10
8. >>> print(Item_value)
9. 1000.23
10. >>>
One thing is important, assignment statement read right to left only.
Example :
a = 12 is correct, but 12 = a does not make sense to Python, which creates a syntax error. Check it in
Python Shell.
view plaincopy to clipboardprint?
1. >>> a = 12
2. >>> 12 = a
3. SyntaxError: can't assign to literal
4. >>>
Multiple Assignment
The basic assignment statement works for a single variable and a single expression. You can also
assign a single value to more than one variables simultaneously.
Syntax
var1=var2=var3...varn= = <expr>
Example :
x=y=z=1
Now check the individual value in Python Shell.
view plaincopy to clipboardprint?
1. >>> x = y = z = 1
2. >>> print(x)
3. 1
4. >>> print(y)
5. 1
6. >>> print(z)
7. 1
8. >>>
Here is an another assignment statement where the variables assign many values at the same time.
Syntax
<var>, <var>, ..., <var> = <expr>, <expr>, ..., <expr>
Example :
x, y, z = 1, 2, "abcd"
In the above example x, y and z simultaneously get the new values 1, 2 and "abcd".
1. >>> x,y,z = 1,2,"abcd"
2. >>> print(x)
3. 1
4. >>> print(y)
5. 2
6. >>> print(z)
7. abcd
You can reuse variable names by simply assigning a new value to them :
1. >>> x = 100
2. >>> print(x)
3. 100
4. >>> x = "Python"
5. >>> print(x)
6. Python
7. >>>

17|
Introduction to Python| Unit- 1
Swap variables
Python swap values in a single line and this applies to all objects in python.
Syntax
var1, var2 = var2, var1
Example :
1. >>> x = 10
2. >>> y = 20
3. >>> print(x)
4. 10
5. >>> print(y)
6. 20
7. >>> x, y = y, x
8. >>> print(x)
9. 20
10. >>> print(y)
11. 10
12. >>>

Local and global variables in Python


In Python, variables that are only referenced inside a function are implicitly global. If a variable is
assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly
declared as global.
Example :
1. var1 = "Python"
2. def func1():
3. var1 = "PHP"
4. print("In side func1() var1 = ",var1)
5.
6. def func2():
7. print("In side func2() var1 = ",var1)
8. func1()
9. func2()
Output :
In side func1() var1 = PHP
In side func2() var1 = Python
You can use a global variable in other functions by declaring it as global keyword :
Example :
1. def func1():
2. global var1
3. var1 = "PHP"
4. print("In side func1() var1 = ",var1)
5.
6. def func2():
7. print("In side func2() var1 = ",var1)
8. func1()
9. func2()
Output :
In side func1() var1 = PHP
In side func2() var1 = PHP

18|
Introduction to Python| Unit- 1

Python Operators
Last update on January 25 2017 11:39:04 (UTC/GMT +8 hours)

Operators and Operands


In computer programming languages operators are special symbols which represent computations,
conditional matching etc. The values the operator uses are called operands.
c=a+b
Here a and b are called operands and '+' is an operator
Python supports following operators.
 Arithmetic Operators
 Comparison Operators
 Logical Operators
 Assignment Operators
 Bitwise Operator
 Conditional Operators
Python Arithmetic Operators
Operator Name Example Result

+ Addition x+y Sum of x and y.

- Subtraction x-y Difference of x and y.

* Multiplication x*y Product of x and y.

/ Division x/y Quotient of x and y.

% Modulus x%y Remainder of x divided by y.

** Exponent x**y x**y will give x to the power y

// Floor x// y The division of operands where the result is the quotient in which the digits
Division after the decimal point are removed.

See the following statements in Python Shell.

19|
Introduction to Python| Unit- 1

Python Comparison Operators


Operator Name Example Result

== Equal x==y True if x is exactly equal to y.

!= Not x!=y True if x is exactly not equal to y.


equal

> Greater x>y True if x (left-hand argument) is greater than y (right-hand argument).
than

< Less x<y True if x (left-hand argument) is less than y (right-hand argument).
than

>= Greater x>=y True if x (left-hand argument) is greater than or equal to y (left-hand argument).
than or
equal to

<= Less x<=y True if x (left-hand argument) is less than or equal to y (right-hand argument).
than or
equal to

See the following statements in Python Shell.

20|
Introduction to Python| Unit- 1

Python Logical Operators


Operator Example Result

And (x and y) is True if both x and y are true.

Or (x or y) is True if either x or y is true.

Not (x not y) If a condition is true then Logical not operator will make false.

See the following statements in Python Shell.

21|
Introduction to Python| Unit- 1

Python Assignment Operators


Operator Shorthand Expression Description

+= x+=y x=x+y Adds 2 numbers and assigns the result to left operand.

-= x-= y x = x –y Subtracts 2 numbers and assigns the result to left operand.

*= x*= y x = x*y Multiplies 2 numbers and assigns the result to left operand.

/= x/= y x = x/y Divides 2 numbers and assigns the result to left operand.

%= x%= y x = x%y Computes the modulus of 2 numbers and assigns the result to left operand.

**= x**=y x = x**y Performs exponential (power) calculation on operators and assign value to
the equivalent to left operand.

//= x//=y x = x//y Performs floor division on operators and assign value to the left operand.

See the following statements in Python Shell.

22|
Introduction to Python| Unit- 1

Python Bitwise Operators


Operator Shorthand Expression Description

& And x&y Bits that are set in both x and y are set.

| Or x|y Bits that are set in either x or y are set.

^ Xor x^y Bits that are set in x or y but not both are set.

~ Not ~x Bits that are set in x are not set, and vice versa.

<< Shift left x <<y Shift the bits of x, y steps to the left

>> Shift right x >>y Shift the bits of x, y steps to the right.

23|
Introduction to Python| Unit- 1

Conditional Operators
Conditional expressions or ternary operator have the lowest priority of all Python operations. The
expression x if C else y first evaluates the condition, C (not x); if C is true, x is evaluated and its
value is returned; otherwise, y is evaluated and its value is returned.
Syntax :
[on_true] if [expression] else [on_false]

Ex: # Program to demonstrate conditional operator


a, b = 10, 20

# Copy value of a in min if a < b else copy b


min = a if a < b else b

print(min)
Output:
10

Python Identifiers
Identifier is the name given to entities like class, functions, variables etc. in Python. It helps
differentiating one entity from another.
Rules for writing identifiers
1. Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an
underscore (_). Names like myClass, var_1 and print_this_to_screen, all are valid example.
2. An identifier cannot start with a digit. 1variable is invalid, but variable1 is perfectly fine.
3. Keywords cannot be used as identifiers.
4.
5. >>>global=1
6. File"<interactive input>", line 1
7. global=1
8. ^

SyntaxError: invalid syntax


9. We cannot use special symbols like !, @, #, $, % etc. in our identifier.
10.
11. >>> a@ =0
12. File"<interactive input>", line 1
13. a@ =0
14. ^

SyntaxError: invalid syntax


15. Identifier can be of any length.
Things to care about
Python is a case-sensitive language. This means, Variable and variable are not the same. Always name
identifiers that make sense.
While, c = 10 is valid. Writing count = 10 would make more sense and it would be easier to figure out what
it does even when you look at your code after a long gap.
Multiple words can be separated using an underscore, this_is_a_long_variable.

24|
Introduction to Python| Unit- 1
We can also use camel-case style of writing, i.e., capitalize every first letter of the word except the initial
word without any spaces. For example: camelCaseExample
What's the difference between a statement and an expression in
Python?
A statement is a complete line of code that performs some action, while an expression is any section of the code that
evaluates to a value. Expressions can be combined “horizontally” into larger expressions using operators, while
statements can only be combined “vertically” by writing one after another, or with block constructs. Every
expression can be used as a statement (whose effect is to evaluate the expression and ignore the resulting value), but
most statements cannot be used as expressions..

Control Structures:
Conditional execution
The if statement
In order to write useful programs, we almost always need the ability to check conditions and change the
behavior of the program accordingly. Conditional statements give us this ability. The simplest form is
the if statement, which has the genaral form:
ifBOOLEANEXPRESSION:
STATEMENTS
A few important things to note about if statements:
1. The colon (:) is significant and required. It separates the header of the compound statement from
the body.
2. The line after the colon must be indented. It is standard in Python to use four spaces for indenting.
3. All lines indented the same amount after the colon will be executed whenever the
BOOLEAN_EXPRESSION is true.
Here is an example:
food='spam'
iffood=='spam':
print('Ummmm, my favorite!')
print('I feel like saying it 100 times...')
print(100*(food+'! '))
The boolean expression after the if statement is called the condition. If it is true, then all the indented
statements get executed. What happens if the condition is false, and food is not equal to 'spam'? In a
simple if statement like this, nothing happens, and the program continues on to the next statement.
Run this example code and see what happens. Then change the value of food to something other
than 'spam' and run it again, confirming that you don’t get any output.
Flowchart of an if statement

25|
Introduction to Python| Unit- 1
the if statement is a compound statement. Compound statements consist of a header line and a body. The
header line of the if statement begins with the keyword if followed by a boolean expression and ends with a
colon (:).
The indented statements that follow are called a block. The first unindented statement marks the end of the
block. Each statement inside the block must have the same indentation.
The if else statement
It is frequently the case that you want one thing to happen when a condition it true, and something else to
happen when it is false. For that we have the if else statement.
iffood=='spam':
print('Ummmm, my favorite!')
else:
print("No, I won't have it. I want spam!")
Here, the first print statement will execute if food is equal to 'spam', and the print statement indented under
the else clause will get executed when it is not.
Flowchart of a if else statement

The syntax for an if else statement looks like this:


ifBOOLEANEXPRESSION:
STATEMENTS_1# executed if condition evaluates to True
else:
STATEMENTS_2# executed if condition evaluates to False
Each statement inside the if block of an if else statement is executed in order if the boolean expression
evaluates to True. The entire block of statements is skipped if the boolean expression evaluates to False, and
instead all the statements under the else clause are executed.
There is no limit on the number of statements that can appear under the two clauses of an if else statement,
but there has to be at least one statement in each block. Occasionally, it is useful to have a section with no
statements (usually as a place keeper, or scaffolding, for code you haven’t written yet). In that case, you can
use the pass statement, which does nothing except act as a placeholder.
ifTrue:# This is always true

26|
Introduction to Python| Unit- 1

pass# so this is always executed, but it does nothing


else:
pass
Chained conditionals
Sometimes there are more than two possibilities and we need more than two branches. One way to express a
computation like that is a chained conditional:
ifx<y:
STATEMENTS_A
elifx>y:
STATEMENTS_B
else:
STATEMENTS_C
Flowchart of this chained conditional

elif is an abbreviation of else if. Again, exactly one branch will be executed. There is no limit of the number
of elif statements but only a single (and optional) final else statement is allowed and it must be the last
branch in the statement:
ifchoice=='a':
print("You chose 'a'.")
elifchoice=='b':
print("You chose 'b'.")
elifchoice=='c':
print("You chose 'c'.")
else:
print("Invalid choice.")
Each condition is checked in order. If the first is false, the next is checked, and so on. If one of them is true,
the corresponding branch executes, and the statement ends. Even if more than one condition is true, only the
first true branch executes.
Nested conditionals
One conditional can also be nested within another. (It is the same theme of composibility, again!) We could
have written the previous example as follows:
Flowchart of this nested conditional

27|
Introduction to Python| Unit- 1

ifx<y:
STATEMENTS_A
else:
ifx>y:
STATEMENTS_B
else:
STATEMENTS_C
The outer conditional contains two branches. The second branch contains another if statement, which has
two branches of its own. Those two branches could contain conditional statements as well.
Although the indentation of the statements makes the structure apparent, nested conditionals very quickly
become difficult to read. In general, it is a good idea to avoid them when you can.
Logical operators often provide a way to simplify nested conditional statements. For example, we can
rewrite the following code using a single conditional:
if0<x:# assume x is an int here
ifx<10:
print("x is a positive single digit.")
The print function is called only if we make it past both the conditionals, so we can use the and operator:
if0<xandx<10:
print("x is a positive single digit.")
Note
Python actually allows a short hand form for this, so the following will also work:
if0<x<10:
print("x is a positive single digit.")

LOOPS

28|
Introduction to Python| Unit- 1
In general, statements are executed sequentially: The first statement in a function is executed first,
followed by the second, and so on. There may be a situation when you need to execute a block of code
several number of times.
A loop statement allows us to execute a statement or group of statements multiple times. The following
diagram illustrates a loop statement −

Python programming language provides following types of loops to handle looping requirements.
Loop Type Description

while loop Repeats a statement or group of statements while a given


condition is TRUE. It tests the condition before executing the
loop body.

for loop Executes a sequence of statements multiple times and


abbreviates the code that manages the loop variable.

nested loops You can use one or more loop inside any another while, for or
do..while loop.

while loop
A while loop statement in Python programming language repeatedly executes a target statement as long
as a given condition is true.
Syntax
The syntax of a while loop in Python programming language is −
while expression:
statement(s)
Here, statement(s) may be a single statement or a block of statements. The condition may be any
expression, and true is any non-zero value. The loop iterates while the condition is true.
When the condition becomes false, program control passes to the line immediately following the loop.

29|
Introduction to Python| Unit- 1
In Python, all the statements indented by the same number of character spaces after a programming
construct are considered to be part of a single block of code. Python uses indentation as its method of
grouping statements.
Flow Diagram

Here, key point of the while loop is that the loop might not ever run. When the condition is tested and
the result is false, the loop body will be skipped and the first statement after the while loop will be
executed.
Example
#!/usr/bin/python

count =0
while(count <9):
print'The count is:', count
count = count +1

print"Good bye!"
When the above code is executed, it produces the following result −
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8

30|
Introduction to Python| Unit- 1
Good bye!
The block here, consisting of the print and increment statements, is executed repeatedly until count is no
longer less than 9. With each iteration, the current value of the index count is displayed and then
increased by 1.
The Infinite Loop
A loop becomes infinite loop if a condition never becomes FALSE. You must use caution when using
while loops because of the possibility that this condition never resolves to a FALSE value. This results in
a loop that never ends. Such a loop is called an infinite loop.
An infinite loop might be useful in client/server programming where the server needs to run
continuously so that client programs can communicate with it as and when required.
#!/usr/bin/python
var=1
whilevar==1:# This constructs an infinite loop
num =raw_input("Enter a number :")
print"You entered: ", num

print"Good bye!"
When the above code is executed, it produces the following result −
Enter a number :20
You entered: 20
Enter a number :29
You entered: 29
Enter a number :3
You entered: 3
Enter a number between :Traceback (most recent call last):
File "test.py", line 5, in <module>
num = raw_input("Enter a number :")
KeyboardInterrupt
Above example goes in an infinite loop and you need to use CTRL+C to exit the program.
Using else Statement with Loops
Python supports to have an else statement associated with a loop statement.
 If the else statement is used with a for loop, the elsestatement is executed when the loop has
exhausted iterating the list.
 If the else statement is used with a while loop, the elsestatement is executed when the condition
becomes false.
The following example illustrates the combination of an else statement with a while statement that prints
a number as long as it is less than 5, otherwise else statement gets executed.p>
#!/usr/bin/python
count =0
while count <5:
print count," is less than 5"
count = count +1
else:
print count," is not less than 5"
When the above code is executed, it produces the following result −
0 is less than 5
1 is less than 5

31|
Introduction to Python| Unit- 1
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5

Syntax
foriterating_varin sequence:
statements(s)
If a sequence contains an expression list, it is evaluated first. Then, the first item in the sequence is
assigned to the iterating variable iterating_var. Next, the statements block is executed. Each item in the
list is assigned to iterating_var, and the statement(s) block is executed until the entire sequence is
exhausted.
Flow Diagram

Example
#!/usr/bin/python
for letter in'Python':# First Example
print'Current Letter :', letter
fruits =['banana','apple','mango']
for fruit infruits:# Second Example
print'Current fruit :', fruit

print"Good bye!"
When the above code is executed, it produces the following result −
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h

32|
Introduction to Python| Unit- 1
Current Letter : o
Current Letter : n
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!
Iterating by Sequence Index
An alternative way of iterating through each item is by index offset into the sequence itself. Following is
a simple example −
#!/usr/bin/python
fruits =['banana','apple','mango']
for index in range(len(fruits)):
print'Current fruit :', fruits[index]
print"Good bye!"
When the above code is executed, it produces the following result −
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!
The len() built-in function provides the total number of elements in the tuple as well as the range() built-
in function to give us the actual sequence to iterate over.
Using else Statement with Loops
Python supports to have an else statement associated with a loop statement
 If the else statement is used with a for loop, the elsestatement is executed when the loop has
exhausted iterating the list.
 If the else statement is used with a while loop, the elsestatement is executed when the condition
becomes false.
The following example illustrates the combination of an else statement with a for statement that searches
for prime numbers from 10 through 20.
#!/usr/bin/python

for num inrange(10,20):#to iterate between 10 to 20


foriin range(2,num):#to iterate on the factors of the number
ifnum%i==0:#to determine the first factor
j=num/i#to calculate the second factor
print'%d equals %d * %d'%(num,i,j)
break#to move to the next number, the #first FOR
else:# else part of the loop
print num,'is a prime number'
When the above code is executed, it produces the following result −
10 equals 2 * 5
11 is a prime number
12 equals 2 * 6
13 is a prime number
14 equals 2 * 7
15 equals 3 * 5
16 equals 2 * 8

33|
Introduction to Python| Unit- 1
17 is a prime number
18 equals 2 * 9
19 is a prime number

Nested loops
Python programming language allows to use one loop inside another loop. Following section shows few
examples to illustrate the concept.
Syntax
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)
The syntax for a nested while loop statement in Python programming language is as follows −
while expression:
statement(s)
statement(s)
A final note on loop nesting is that you can put any type of loop inside of any other type of loop. For
example a for loop can be inside a while loop or vice versa.
Example
The following program uses a nested for loop to find the prime numbers from 2 to 100 −
#!/usr/bin/python
i=2
while(i< 100):
j=2
while(j <= (i/j)):
if not(i%j): break
j=j+1
if (j >i/j) : print i, " is prime"
i=i+1
print "Good bye!"
When the above code is executed, it produces following result −
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime

34|
Introduction to Python| Unit- 1
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime
Good bye!

Loop Control Statements


Loop control statements change execution from its normal sequence. When execution leaves a scope, all
automatic objects that were created in that scope are destroyed.
Python supports the following control statements. Click the following links to check their detail.
Control Statement Description

break statement Terminates the loop statement and transfers execution to the
statement immediately following the loop.

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

pass statement The pass statement in Python is used when a statement is


required syntactically but you do not want any command or
code to execute.
It terminates the current loop and resumes execution at the next statement just like the traditional break
statement in C.
The most common use for break is when some external condition is triggered requiring a hasty exit from
a loop. The breakstatement can be used in both while and for loops.
If you are using nested loops, the break statement stops the execution of the innermost loop and start
executing the next line of code after the block.
break
The syntax for a break statement in Python is as follows −
break

35|
Introduction to Python| Unit- 1
Flow Diagram

Example
#!/usr/bin/python
for letter in 'Python': # First Example
if letter == 'h':
break
print 'Current Letter :', letter
var = 10 # Second Example
while var > 0:
print 'Current variable value :', var
var = var -1
if var == 5:
break
print "Good bye!"
When the above code is executed, it produces the following result −
Current Letter : P
Current Letter : y
Current Letter : t
Current variable value : 10
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Good bye!
It returns the control to the beginning of the while loop.. The continue statement rejects all the
remaining statements in the current iteration of the loop and moves the control back to the top of the
loop.
The continue statement can be used in both while and forloops.
continue

36|
Introduction to Python| Unit- 1
Flow Diagram

Example
#!/usr/bin/python
for letter in 'Python': # First Example
if letter == 'h':
continue
print 'Current Letter :', letter
var = 10 # Second Example
while var > 0:
var = var -1
if var == 5:
continue
print 'Current variable value :', var
print "Good bye!"
When the above code is executed, it produces the following result −
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Current variable value : 4
Current variable value : 3
Current variable value : 2
Current variable value : 1
Current variable value : 0
Good bye!

37|
Introduction to Python| Unit- 1
pass statement
It is used when a statement is required syntactically but you do not want any command or code to
execute.
The pass statement is a null operation; nothing happens when it executes. The pass is also useful in
places where your code will eventually go, but has not been written yet (e.g., in stubs for example):
Syntax :
pass
Example
#!/usr/bin/python
for letter in 'Python':
if letter == 'h':
pass
print 'This is pass block'
print 'Current Letter :', letter

print "Good bye!"


When the above code is executed, it produces following result −
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!

Statements and Syntax


Some rules and certain symbols are used with regard to statements in Python:

● Hash mark ( # ) indicates Python comments


● NEWLINE ( \n ) is the standard line separator (one statement per line)
● Backslash ( \ ) continues a line
● Semicolon ( ; ) joins two statements on a line
● Colon ( : ) separates a header line from its suite
● Statements (code blocks) grouped as suites
● Suites delimited via indentation
● Python files organized as modules

Comments ( # )

Python comment statements begin with the pound sign or hash symbol (#). A
comment can begin anywhere on a line.

Continuation ( \ )
Single statements can be broken up into multiple lines by use of the backslash. The backslash symbol ( \ )
can be placed before a NEWLINE to continue the current statement onto the next line.

38|
Introduction to Python| Unit- 1
# check conditions
if(weather_is_hot == 1) and\
(shark_warnings == 0):
send_goto_beach_mesg_to_pager()

Multiple Statement Groups as Suites ( : )


Groups of individual statements making up a single code block are called "suites" in Python. Compound
or complex statements, such as if, while, def, and class, are those that require a header line and a suite.
Header lines begin the statement (with the keyword) and terminate with a colon and are followed by one
or more lines that make up the suite.

Suites Delimited via Indentation


The block of code uses indentation to define the scope. all the lines of code in a suite must be indented at
the exact same level (e.g., same number of spaces).

Multiple Statements on a Single Line ( ; )


The semicolon ( ;) allows multiple statements on a single line given that neither statement starts a new
code block.

S=4;print s

Modules
Each Python script is considered a module. Modules have a physical presence as disk files. modules can
contain blocks of code to run, class declarations, function declarations, or any combination of all of those.
Python Data Type
Introduction

Type represents the kind of value and determines how the value can be used. All data values in Python are
encapsulated in relevant object classes. To determine a variable's type in Python you can use the type()
function.

Numbers
Python has several numeric types:
 integers
 long integers,
 Boolean,
 floating point real numbers,
 complex numbers.

How to Create and Assign Numbers (Number Objects)


Creating numbers is as simple as assigning a value to a variable:
anInt = 1
aLong = -9999999999999999L

39|
Introduction to Python| Unit- 1
aFloat = 3.1415926535897932384626433832795
aComplex = 1.23+4.56J
How to Update Numbers
Update an existing number by (re)assigning a variable to another number. The new value can be related to
its previous value or to a completely different number altogether. Because numbers are immutable, you
are just making a new number and reassigning the reference.
anInt += 1
aFloat = 2.718281828

How to Remove Numbers

just use the delstatement. You can no longer use the variable name,once removed, unless you assign it to
a new object; otherwise, you will cause a NameErrorexception to occur.
delanInt
delaLong, aFloat, aComplex

Integers
Python has several types of integers. There is the Boolean type with two possible values. There are the
regular or plain integers.Python also has along integer size.
Boolean
Objects of this type have two possible values, Boolean Trueand False.
Standard (Regular or Plain) Integers
Python's "plain" integers provides a range of -231to 231-1, that is -2, 147,483,648 to 2,147,483,647. If
Python is compiled on a 64-bit system with a 64-bit compiler, then the integers for that system will be 64-
bit.
examples :0101 84 -237 0x80 017 -680 -0X92
Python integers are implemented as (signed) longs in C. Integers are normally represented in base 10
decimal format, but they can also be specified in base 8 or base 16 representation. Octal values have a "0"
prefix, and hexadecimal values have either "0x" or "0X" prefixes.
Long Integers
The first thing we need to say about Python long integers (or longs for short) is notto get them confused
with longs in C or other compiled languagesthese values are typically restricted to 32- or 64-bit sizes,
whereas Python longs are limited only by the amount of (virtual) memory in your machine.
16384L -0x4E8L 017L -2147483648l 052144364L
299792458l 0xDECADEDEADBEEFBADFEEDDEAL -5432101234L
Floating Point Numbers
Floats in Python are implemented as C doubles, double precision floating point real numbers, values that
can be represented in straightforward decimal or scientific notations.
These 8-byte (64-bit) values conform to the IEEE 754 definition (52M/11E/1S) where 52 bits are
allocated to the mantissa, 11 bits to the exponent .Tthe actual degree of precision you will receive (along
with the range and overflow handling) depends completely on the architecture of the machine as well as
the implementation of the compiler that built your Python interpreter.
-777. 1.6 -5.555567119 96e3 * 1.04.3e25 9.384e-23 -2.172818 float(12)

Complex Numbers
A complex number is any ordered pair of floating point real numbers (x, y) denoted by
x +yjwhere xis the real part and yis the imaginary part of a complex number.
Example: 64.375+1j 4.23-8.5j 0.23-8.55j 1.23e-045+6.7e+089j

Complex Number Built-in Attributes

40|
Introduction to Python| Unit- 1
Complex numbers are one example of objects with data attributes and a method attribute.
>>> aComplex = -8.333-1.47j
>>> aComplex
(-8.333-1.47j)
>>>aComplex.real
-8.333
>>>aComplex.imag
-1.47
>>>aComplex.conjugate()
(-8.333+1.47j)
Attribute Description
num.real Real component of complex number num
num.imag Imaginary component of complex number num
num.conjugate() Returns complex conjugate of num

Operators
Mixed-Mode Operations
Mixedmode operations are those which involve two numbers of different types
If both numbers are the same type, no conversion is necessary. Therules of coercion follow from these
two examples: integers move toward float, and all move toward complex.
.
● If either argument is a complex number, the other is converted to complex;
● Otherwise, if either argument is a floating point number, the other is converted to floating point;
● Otherwise, if either argument is a long, the other is converted to long;
● Otherwise, both must be plain integers and no conversion is necessary (in the upcoming
diagram, this describes the rightmost arrow).

The following is an example showing you Python's automatic coercion. In order to add the numbers (one
integer, one float), both need to be converted to the same type. Since float is the superset, the integer is
coerced to a float before the operation happens, leaving the result as a float:
>>> 1 + 4.5

41|
Introduction to Python| Unit- 1
5.5

Numeric Type (Arithmetic) Operators


Classic Division
>>> 1 / 2 # perform integer result (floor)
0
>>> 1.0 / 2.0 # returns actual quotient
0.5

Floor Division
>>> 1 // 2 #floors result, returns integer
0
>>> 1.0 // 2.0 #floors result, returns float
0.0
>>> -1 // 2 #move left on number line
-1
Modulus
 Integer modulo is straightforward integer division remainder.
 For float, it is the difference of the dividend and the product of the divisor and the quotient of the
quantity dividend divided by the divisor rounded down to the closest integer, i.e.,x -
(math.floor(x/y) * y),
 For complex number modulo, take only the real component of the division result, i.e., x -
(math.floor((x/y).real) * y).
Exponentiation
The exponentiation operator has a peculiar precedence rule in its relationship with the unary operators: It
binds more tightly than unary operators to its left, but less tightly than unary operators to its right.
>>> 3 ** 2
9
>>> -3 ** 2 #** binds tighter than - to its left
-9
>>> (-3) ** 2 #group to cause - to bind first
9
>>> 4.0 ** -1.0 #** binds looser than - to its right
0.25

Arithmetic Operator Function


expr1 ** expr2expr1raised to the power of expr2
+expr (unary) exprsign unchanged
-expr (unary) negation of expr
expr1 ** expr2expr1raised to the power of expr2
expr1 * expr2 expr1times expr2
expr1 / expr2 expr1divided by expr2(classic or true division)
expr1 // expr2 expr1divided by expr2(floor division [only])
expr1 % expr2 expr1modulo expr2
expr1 + expr2 expr1plus expr2
expr1 - expr2 expr1minus expr2

Examples:

42|
Introduction to Python| Unit- 1
>>> -442 – 77
-519
>>>
>>> 4 ** 3
64
>>>
>>> 4.2 ** 3.2
98.7183139527
>>> 8 / 3
2
>>> 8.0 / 3.0
2.66666666667
>>> 8 % 3
2
>>> (60. - 32.) * ( 5. / 9. )
15.5555555556
>>> 14 * 0x04
56
>>> 0170 / 4
30
>>> 0x80 + 0777
639
>>> 45L * 22L
990L
>>> 16399L + 0xA94E8L
709879L
>>> -2147483648L - 52147483648L
-54294967296L
>>> 64.375+1j + 4.23-8.5j
(68.605-7.5j)
>>> 0+1j ** 2 # same as 0+(lj**2)
(-1+0j)
>>> 1+1j ** 2 # same as 1+(lj**2)
0j
>>> (1+1j) ** 2
2j

Bit Operators (Integer-Only)

Left and right shifts of N bits are equivalent to multiplication and division by (2 **N) without
overflow checking.

Bitwise Operator Function


~num (unary) I nvert the bits of num, yielding -(num+ 1)
num1 << num2 num1left shifted by num2bits
num1 >> num2 num1right shifted by num2bits
num1 & num2 num1bitwise AND with num2
num1 ^ num2 num1bitwise XOR (exclusive OR) with num2
num1 | num2 num1bitwise OR with num2

>>> 30 & 45

43|
Introduction to Python| Unit- 1
12
>>> 30 | 45
63
>>> 45 & 60
44
>>> 45 | 60
61
>>> ~30
-31
>>> ~45
-46
>>> 45 << 1
90
>>> 60 >> 2
15
>>> 30 ^ 45
51

Conversion Factory Functions

Class (Factory Function) Operation


bool(obj)Returns the Boolean value of obj, e.g., the value of executing obj.__nonzero__()
int(obj, base=10) Returns integer representation of string or
number obj; similar to string.atoi(); optional base
argument
long(obj, base=10) Returns long representation of string or number
obj; similar to string.atol(); optional baseargument
float(obj) Returns floating point representation of string or
number obj; similar to string.atof()
complex(str)
or complex(real, imag=0.0)Returns complex number representation of str, or
builds one given real(and perhaps imaginary)
component(s)
The following are some examples of using these functions:
>>>int(4.25555)
4
>>>long(42)
42L
>>>float(4)
4.0
>>>complex(4)
(4+0j)
>>>
>>>complex(2.4, -8)
(2.4-8j)
>>>
>>>complex(2.3e-10, 45.3e4)
(2.3e-10+453000j)

44|
Introduction to Python| Unit- 1
Numeric Type Operational Built-in Functions
Function Operation
abs(num) Returns the absolute value of num
coerce(num1, num2) Converts num1and num2to the same numeric type and
returns the converted pair as a tuple
divmod(num1, num2) Division-modulo combination returns (num1 / num2,
num1 % num2) as a tuple; for floats and complex, the
quotient is rounded down (complex uses only real
component of quotient)
pow(num1, num2, mod=1) Raises num1to num2power, quantity modulo modif provided
round(flt, ndig=0) (Floats only) takes a float fltand rounds it to ndigdigits, defaulting to
zero if not provided
abs()returns the absolute value of the given argument. If the argument is a complex number, then
math.sqrt(num .real2+ num.imag2) is returned. Here are some examples of using the abs()built-in
function:
>>>abs(-1)
1
>>>abs(10.)
10.0
>>>abs(1.2-2.1j)
2.41867732449
>>>abs(0.23 - 0.78)
0.55

The coerce()function is a way for the programmer to explicitly coerce a pair of numbers rather than
letting the interpreter do it. coerce()just returns a tuple containing the converted pair of numbers.

>>>coerce(1, 2)
(1, 2)
>>>
>>>coerce(1.3, 134L)
(1.3, 134.0)
>>>
>>>coerce(1, 134L)
(1L, 134L)
>>>
>>>coerce(1j, 134L)
(1j, (134+0j))
>>>
>>>coerce(1.23-41j, 134L)
((1.23-41j), (134+0j))

The divmod()built-in function combines division and modulus operations into a single function call that
returns the pair (quotient, remainder) as a tuple.

For floats, the quotient returned is math.floor(num1/num2) and for complex numbers, the quotient is
math.floor((num1/num2).real).

>>>divmod(10,3)
(3, 1)
>>>divmod(3,10)

45|
Introduction to Python| Unit- 1
(0, 3)
>>>divmod(10,2.5)
(4.0, 0.0)
>>>divmod(2.5,10)
(0.0, 2.5)
>>>divmod(2+1j, 0.5-1j)
(0j, (2+1j))

Both pow()and the double star ( **) operator perform exponentiation; however, there are differences
other than the fact that one is an operator and the other is a built-in function.

>>>pow(2,5)
32
>>>s
>>>pow(5,2)
25
>>>pow(3.141592,2)
9.86960029446
>>>
>>>pow(1+1j, 3)
(-2+2j)

The round()built-in function has a syntax of round(flt,ndig=0). It normally rounds a floating point
number to the nearest integral number and returns that result (still) as a float. When the optional
ndigoption is given, round()will round the argument to the specific number of decimal places.
>>>round(3)
3.0
>>>round(3.45)
3.0
>>>round(3.4999999)
3.0
>>>round(3.4999999, 1)
3.5

Integer-Only Functions

Some functions are specific only to integers (plain and long). These functions fall into
two categories,
base presentation : hex()and oct(), and
ASCII conversion : chr()and ord().

Base Representation :

>>>hex(255)
'0xff'
>>> hex(23094823l)
'0x1606627L'
>>>hex(65535*2)

46|
Introduction to Python| Unit- 1
'0x1fffe'

>>>oct(255)
'0377'
>>> oct(23094823l)
'0130063047L'
>>>oct(65535*2)
'0377776'

ASCII Conversion

Each character is mapped to a unique number in a table numbered from 0 to


255.chr()takes a single-byte integer value and returns a one-character string with the
equivalent ASCII character. ord()does the opposite, taking a single ASCII character in the
form of a string of length one and returns the corresponding ASCII value as an integer:

>>>ord('a')
97
>>>ord('A')
65
>>>ord('0')
48
>>>chr(97)
'a'
>>> chr(65L)
'A'
>>>chr(48)
'0'

Function Operation
hex(num) Converts numto hexadecimal and returns as
string
oct(num) Converts numto octal and returns as string
chr(num) Takes ASCII value numand returns ASCII character
as string; 0 <= num<= 255 only
ord(chr) Takes ASCII or Unicode chr(string of length 1) and
returns corresponding ordinal ASCII value or
Unicode code point, respectively

Boolean (bool)

47|
Introduction to Python| Unit- 1
The simplest build-in type in Python is the bool type, it represents the truth values False and True. See the
following statements in Python shell.

48|
Python Programming II UNIT

Mutable and Immutable data Types

Every variable in python holds an instance of an object. There are two types of objects in
python i.e. Mutable and Immutable objects.

Mutable Immutable
Mutable objects can be changed after it is An immutable object can’t be changed after it
created. is created.
Generally provides a method to add or Does not provides a method to add or remove
remove elements elements
Slower to access compared to immutable Faster to access compared to mutable
These are of type list, dict, set These are of in-built types like int, float,
bool, string, unicode, tuple.

Python Data Types

Built-in Data Types: In programming, data type is an important concept. Variables can store
data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:

Text Type: str


Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
None Type: NoneType

Getting the Data Type: You can get the data type of any object by using the type() function:

x=5
print(type(x)) # <class ‘int’>

x = 5.5
print(type(x)) # <class ‘float’>

1
Python Programming II UNIT

Setting the Data Type

In Python, the data type is set when you assign a value to a variable:
Example Data Type
x = "Hello World" str
x = 20 int
x = 20.5 float
x = 1j complex
x = ["apple", "banana", "cherry"] list
x = ("apple", "banana", "cherry") tuple
x = range(6) range
x = {"name" : "John", "age" : 36} dict
x = {"apple", "banana", "cherry"} set
x = frozenset({"apple", "banana", "cherry"}) frozenset
x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
x = None NoneType

Setting the Specific Data Type

If you want to specify the data type, you can use the following constructor functions:
Example Data Type
x = str("Hello World") str
x = int(20) int
x = float(20.5) float
x = complex(1j) complex
x = list(("apple", "banana", "cherry")) list
x = tuple(("apple", "banana", "cherry")) tuple
x = range(6) range
x = dict(name="John", age=36) dict
x = set(("apple", "banana", "cherry")) set
x = frozenset(("apple", "banana", "cherry")) frozenset
x = bool(5) bool
x = bytes(5) bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview

2
Python Programming II UNIT

Python Numbers:
Here are three numeric types in Python:
 int
 float
 complex

Variables of numeric types are created when you assign a value to them:
x=1 # int
y = 2.8 # float
z = 1j # complex

To verify the type of any object in Python, use the type() function:
print(type(x))
print(type(y))
print(type(z))

int :
Int, or integer, is a whole number, positive or negative, without decimals, of unlimited
length.
x=1
y = 35656222554887711
z = -3255522

print(type(x))
print(type(y))
print(type(z))
float :
Float, or "floating point number" is a number, positive or negative, containing one or more
decimals.
x = 1.10
y = 1.0
z = -35.59

print(type(x))
print(type(y))
print(type(z))

Float can also be scientific numbers with an "e" to indicate the power of 10.
x = 35e3
y = 12E4
z = -87.7e100

3
Python Programming II UNIT

print(type(x))
print(type(y))
print(type(z))

Complex:
Complex numbers are written with a "j" as the imaginary part. The first part is called real part
and the second part is called imaginary.
x = 3+5j
y = 5j
z = -5j

print(type(x))
print(type(y))
print(type(z))

Random Number
Python does not have a random() function to make a random number, but Python has a built-
in module called random that can be used to make random numbers:
Import the random module, and display a random number between 1 and 9:

import random

print(random.randrange(1, 10))

Python Casting
Specify a Variable Type
There may be times when you want to specify a type on to a variable. This can be done with
casting. Python is an object-orientated language, and as such it uses classes to define data
types, including its primitive types.
Casting in python is therefore done using constructor functions:
 int() - constructs an integer number from an integer literal, a float literal (by removing
all decimals), or a string literal (providing the string represents a whole number)
 float() - constructs a float number from an integer literal, a float literal or a string
literal (providing the string represents a float or an integer)
 str() - constructs a string from a wide variety of data types, including strings, integer
literals and float literals
Integers
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
Floats
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8

4
Python Programming II UNIT

z = float("3") # z will be 3.0


w = float("4.2") # w will be 4.2

Strings
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'

Python Strings
Strings: Strings in python are surrounded by either single quotation marks, or double
quotation marks.
'AITAM' is the same as "AITAM".
You can display a string literal with the print() function:
print("AITAM")
print(' AITAM ')

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:
a = "Hello"
print(a)

Multiline Strings : You can assign a multiline string to a variable by using three quotes Or
three single quotes:
a = """IT Department is the
BEST department in the AITAM"""
print(a)

a = IT Department is the
BEST department in the AITAM '''
print(a)

Python Booleans : Booleans represent one of two values: True or False.


Boolean Values
 In programming you often need to know if an expression is True or False.
 You can evaluate any expression in Python, and get one of two
answers, True or False.
 When you compare two values, the expression is evaluated and Python returns the
Boolean answer:
print(10 > 9)
print(10 == 9)
print(10 < 9)
When you run a condition in an if statement, Python returns True or False:
a = 200
b = 33

5
Python Programming II UNIT

if b > a:
print("b is greater than a")
else:
print("b is not greater than a")

Evaluate Values and Variables : The bool() function allows you to evaluate any value, and
give you True or False in return,
print(bool("AITAM"))
print(bool(15))
x = "Hello"
y = 15
print(bool(x))
print(bool(y))

Most Values are True


 Almost any value is evaluated to True if it has some sort of content.
 Any string is True, except empty strings.
 Any number is True, except 0.
 Any list, tuple, set, and dictionary are True, except empty ones.

The following will return True:


bool("abc")
bool(123)
bool(["apple", "cherry", "banana"])

Some Values are False


In fact, there are not many values that evaluate to False, except empty values, such
as (), [], {}, "", the number 0, and the value None. And of course the value False evaluates
to False.

The following will return False:


bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({})

6
Python Programming II UNIT

Introduction to Python sequences

A sequence is a positional ordered collection of items. And you can refer to any item in the
sequence by using its index number e.g., s[0] and s[1].
In Python, the sequence index starts at 0, not 1. So the first element is s[0] and the second
element is s[1]. If the sequence s has n items, the last item is s[n-1].
Python supports six different types of sequences. These
are strings, lists, tuples, byte sequences, byte arrays, and range objects.

Python Strings
Strings are a group of characters written inside a single or double-quotes. Python does not
have a character type so a single character inside quotes is also considered as a string.
a = "Hello, AITAM!"
print(a[1])

String Length
To get the length of a string, use the len() function.
a = " Hello, AITAM!"
print(len(a))

Check String
To check if a certain phrase or character is present in a string, we can use the keyword in.
txt = "The best things in life are free!"
print("free" in txt)
txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.")

Slicing
You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return a part of the string.
b = "Hello, AITAM!"
print(b[2:5]) # It prints index from 2 to 4

b = "Hello, AITAM!"
print(b[:5]) # It prints index from 0 to 4
b = "Hello, AITAM!"
print(b[2:]) # It prints index from 2 to last

Negative Indexing
Use negative indexes to start the slice from the end of the string:
b = " Hello, AITAM!"
print(b[-1])
b = " Hello, AITAM!"
print(b[-5:-2])

7
Python Programming II UNIT

The upper() method returns the string in upper case:


a = "Hello, aitam!"
print(a.upper())

The lower() method returns the string in lower case:


a = "Hello, AITAM!"
print(a.lower())

The strip() method removes any whitespace from the beginning or the end:
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"

To concatenate, or combine, two strings you can use the + operator.


a = "Hello"
b = "AITAM"
c=a+b
print(c)
a = "Hello"
b = " AITAM "
c=a+""+b
print(c)

String Format
As we learned in the Python Variables chapter, we cannot combine strings and numbers like
this:
age = 36
txt = "My name is Ramesh, I am " + age
print(txt) # ERROR

The format() method takes the passed arguments, formats them, and places them in the string
where the placeholders {} are:
age = 36
txt = "My name is Ramesh, and I am {}"
print(txt.format(age))

quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} Rupees."
print(myorder.format(quantity, itemno, price))

Escape Character
To insert characters that are illegal in a string, use an escape character.
txt = "We are the so-called \"IT Students\" from the AITAM."

8
Python Programming II UNIT

Check if all the characters in the text are digits:


txt = "50800"

x = txt.isdigit()

print(x)

List
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store collections of data, the other 3
are Tuple, Set, and Dictionary, all with different qualities and usage.
Lists are created using square brackets:

myList1 = ["apple", "banana", "cherry"]


print(myList1)
['apple', 'banana', 'cherry']

myList2 = [10, 20, 30, 40, 50]


print(myList2)
[10, 20, 30, 40, 50]

List Items
List items are ordered, changeable, and allow duplicate values. List items are indexed, the
first item has index [0], the second item has index [1] etc.

Ordered: When we say that lists are ordered, it means that the items have a defined order, and
that order will not change. If you add new items to a list, the new items will be placed at the
end of the list.

Changeable: The list is changeable, meaning that we can change, add, and remove items in a
list after it has been created.
Access List Items
List items are indexed and you can access them by referring to the index number:

9
Python Programming II UNIT

myList = ["apple", "banana", "cherry"]


print(myList)
['apple', 'banana', 'cherry']

print(myList [1])
banana

print(myList [-1])
cherry

Range of Indexes
You can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new list with the specified items.

myList = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


print(myList [2:5])
['cherry', 'orange', 'kiwi']

By leaving out the start value, the range will start at the first item:
myList = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(myList [:4])
['apple', 'banana', 'cherry', 'orange']
By leaving out the end value, the range will go on to the end of the list:

myList = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


print(myList [2:])
['cherry', 'orange', 'kiwi', 'melon', 'mango']

Check if Item Exists


To determine if a specified item is present in a list use the in keyword:
myList = ["apple", "banana", "cherry"]
if "apple" in myList:
print("Yes, 'apple' is in the fruits list")
OR
print("apple" in myList)

Change a Range of Item Values


To change the value of items within a specific range, define a list with the new values, and
refer to the range of index numbers where you want to insert the new values:

myList = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]


myList [1:3] = ["blackcurrant", "watermelon"]
print myList)
['apple', 'blackcurrant', 'watermelon', 'orange', 'kiwi', 'mango']

10
Python Programming II UNIT

myList = ["apple", "banana", "cherry"]


myList[1:3] = ["watermelon"]
print(myList)
['apple', 'watermelon']

Insert Items
To insert a new list item, without replacing any of the existing values, we can use
the insert() method.
The insert() method inserts an item at the specified index:

myList = ["apple", "banana", "cherry"]


myList.insert(2, "watermelon")
print(myList)
['apple', 'banana', 'watermelon', 'cherry']

Append Items
To add an item to the end of the list, use the append() method:

myList = ["apple", "banana", "cherry"]


myList.append("orange")
print(myList)
['apple', 'banana', 'cherry', 'orange']

Extend List
To append elements from another list to the current list, use the extend() method.

myList = ["apple", "banana", "cherry"]


list1 = ["mango", "pineapple", "papaya"]
myList.extend(list1)
print(myList)
['apple', 'banana', 'cherry', 'mango', 'pineapple', 'papaya']

Remove Specified Item


The remove() method removes the specified item.

myList = ["apple", "banana", "cherry"]


myList.remove("banana")
print(myList)
['apple', 'cherry']

Remove Specified Index


The pop() method removes the specified index.
myList = ["apple", "banana", "cherry"]
myList.pop(1)
print(myList)
['apple', 'cherry']

11
Python Programming II UNIT

If you do not specify the index, the pop() method removes the last item.
myList = ["apple", "banana", "cherry"]
myList.pop()
print(myList)
['apple', 'banana']

del: The del keyword also removes the specified index:

myList = ["apple", "banana", "cherry"]


del myList[0]
print(myList)
['banana', 'cherry']

The del keyword can also delete the list completely.

myList = ["apple", "banana", "cherry"]


del myList

Clear the List


The clear() method empties the list.
The list still remains, but it has no content.
myList = ["apple", "banana", "cherry"]
myList.clear()
print(myList)
[]

Loop Through a List


You can loop through the list items by using a for loop:
myList = ["apple", "banana", "cherry"]
for x in myList:
print(x)

Loop Through the Index Numbers


You can also loop through the list items by referring to their index number.
Use the range() and len() functions to create a suitable iterable.
myList = ["apple", "banana", "cherry"]
for i in range(len(myList)):
print(myList[i])

12
Python Programming II UNIT

Sort List Alphanumerically


List objects have a sort() method that will sort the list alphanumerically, ascending, by
default:
myList = ["orange", "mango", "kiwi", "pineapple", "banana"]
myList.sort()
print(myList)
['banana', 'kiwi', 'mango', 'orange', 'pineapple']

myList = [100, 50, 65, 82, 23]


myList.sort()
print(myList)
[23, 50, 65, 82, 100]

Sort Descending
To sort descending, use the keyword argument reverse = True:
myList = ["orange", "mango", "kiwi", "pineapple", "banana"]
myList.sort(reverse = True)
print(myList)

Copy a List
You cannot copy a list simply by typing list2 = list1, because: list2 will only be
a reference to list1, and changes made in list1 will automatically also be made in list2.
There are ways to make a copy, one way is to use the built-in List method copy().
myList = ["apple", "banana", "cherry"]
mylist = myList.copy()
print(mylist)
['apple', 'banana', 'cherry']

Join Two Lists


There are several ways to join, or concatenate, two or more lists in Python.
One of the easiest ways are by using the + operator.
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]

list3 = list1 + list2


print(list3)

['a', 'b', 'c', 1, 2, 3]


list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]

for x in list2:
list1.append(x)

print(list1)

13
Python Programming II UNIT

Tuple
Tuples are used to store multiple items in a single variable.
Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3
are List, Set, and Dictionary, all with different qualities and usage.

A tuple is a collection which is ordered and unchangeable. Tuples are written with round
brackets.
myTuple = ("apple", "banana", "cherry")
print(myTuple)

Tuple Items
Tuple items are ordered, unchangeable, and allow duplicate values. Tuple items are indexed,
the first item has index [0], the second item has index [1] etc.

Ordered: When we say that tuples are ordered, it means that the items have a defined order,
and that order will not change.

Unchangeable: Tuples are unchangeable, meaning that we cannot change, add or remove
items after the tuple has been created.

Allow Duplicates: Since tuples are indexed, they can have items with the same value:
myTuple = ("apple", "banana", "cherry", "apple", "cherry")
print(myTuple)

To determine how many items a tuple has, use the len() function:
myTuple = ("apple", "banana", "cherry")
print(len(myTuple))

Create Tuple With One Item


To create a tuple with only one item, you have to add a comma after the item, otherwise
Python will not recognize it as a tuple.

myTuple = ("apple",)
print(type(myTuple))

# the following is NOT a tuple. It is a string


myTuple = ("apple")
print(type(myTuple))

Tuple Items - Data Types


Tuple items can be of any data type:
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)

14
Python Programming II UNIT

tuple4 = ("abc", 34, True, 40, "male")

The tuple() Constructor


It is also possible to use the tuple() constructor to make a tuple.

myTuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets


print(myTuple)

Access Tuple Items


You can access tuple items by referring to the index number, inside square brackets:

myTuple = ("apple", "banana", "cherry")


print(myTuple[1])

Negative Indexing
Negative indexing means start from the end. -1 refers to the last item, -2 refers to the second
last item etc.
myTuple = ("apple", "banana", "cherry")
print(myTuple[-1])

Range of Indexes
You can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new tuple with the specified items.

myTuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")


print(myTuple[2:5])

By leaving out the end value, the range will go on to the end of the list:
myTuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(myTuple[:4])

This example returns the items from "cherry" and to the end:
myTuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(myTuple[2:])

Check if Item Exists


To determine if a specified item is present in a tuple use the in keyword:
myTuple = ("apple", "banana", "cherry")
if "apple" in myTuple:
print("Yes, 'apple' is in the fruits tuple")
Update Tuples
Tuples are unchangeable, meaning that you cannot change, add, or remove items once the
tuple is created. But there are some workarounds.
Change Tuple Values

15
Python Programming II UNIT

Once a tuple is created, you cannot change its values. Tuples are unchangeable,
or immutable as it also is called. But there is a workaround. You can convert the tuple into a
list, change the list, and convert the list back into a tuple.
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)

print(x)

Add Items
Since tuples are immutable, they do not have a build-in append() met but there are other
ways to add items to a tuple.
1. Convert into a list: Just like the workaround for changing a tuple, you can convert it into
a list, add your item(s), and convert it back into a tuple.
myTuple = ("apple", "banana", "cherry")
y = list(myTuple)
y.append("orange")
myTuple = tuple(y)

2. Add tuple to a tuple. You are allowed to add tuples to tuples, so if you want to add one
item, (or many), create a new tuple with the item(s), and add it to the existing tuple:
myTuple = ("apple", "banana", "cherry")
y = ("orange",)
myTuple += y

print(myTuple)

Remove Items
Tuples are unchangeable, so you cannot remove items from it, but you can use the same
workaround as we used for changing and adding tuple items:
myTuple = ("apple", "banana", "cherry")
y = list(myTuple)
y.remove("apple")
myTuple = tuple(y)

you can delete the tuple completely:


myTuple = ("apple", "banana", "cherry")
del myTuple
print(myTuple) #this will raise an error because the tuple no longer exists

Unpacking a Tuple
When we create a tuple, we normally assign values to it. This is called "packing" a tuple:
fruits = ("apple", "banana", "cherry")
But, in Python, we are also allowed to extract the values back into variables. This is called
"unpacking":

16
Python Programming II UNIT

fruits = ("apple", "banana", "cherry")

(green, yellow, red) = fruits

print(green)
print(yellow)
print(red)
apple
banana
cherry

Using Asterisk*
If the number of variables is less than the number of values, you can add an * to the variable
name and the values will be assigned to the variable as a list:
fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")
(green, yellow, *red) = fruits

print(green)
print(yellow)
print(red)
apple
banana
['cherry', 'strawberry', 'raspberry']

If the asterisk is added to another variable name than the last, Python will assign values to the
variable until the number of values left matches the number of variables left.
fruits = ("apple", "mango", "papaya", "pineapple", "cherry")

(green, *tropic, red) = fruits

print(green)
print(tropic)
print(red)
apple
['mango', 'papaya', 'pineapple']
cherry

Loop Through a Tuple


You can loop through the tuple items by using a for loop.
myTuple = ("apple", "banana", "cherry")
for x in myTuple:
print(x)
apple
banana
cherry

17
Python Programming II UNIT

Loop Through the Index Numbers


You can also loop through the tuple items by referring to their index number. Use
the range() and len() functions to create a suitable iterable.
myTuple = ("apple", "banana", "cherry")
for i in range(len(myTuple)):
print(myTuple[i])

Join Two Tuples


To join two or more tuples you can use the + operator:
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)

tuple3 = tuple1 + tuple2


print(tuple3)
('a', 'b', 'c', 1, 2, 3)

Multiply Tuples
If you want to multiply the content of a tuple a given number of times, you can use
the * operator:
fruits = ("apple", "banana", "cherry")
mytuple = fruits * 2
print(mytuple)
('apple', 'banana', 'cherry', 'apple', 'banana', 'cherry')

Python Sets
Sets are used to store multiple items in a single variable.
Set is one of 4 built-in data types in Python used to store collections of data, the other 3
are List, Tuple, and Dictionary, all with different qualities and usage.
A set is a collection which is unordered, unchangeable*, and unindexed. Sets are written
with curly brackets.
mySet = {"apple", "banana", "cherry"}
print(mySet)
Set Items
Set items are unordered, unchangeable, and do not allow duplicate values.

18
Python Programming II UNIT

Unordered: Unordered means that the items in a set do not have a defined order. Set items
can appear in a different order every time you use them, and cannot be referred to by index or
key.

Unchangeable: Set items are unchangeable, meaning that we cannot change the items after
the set has been created.

Duplicates Not Allowed Sets cannot have two items with the same value.
mySet = {"apple", "banana", "cherry", "apple"}
print(mySet)
{'banana', 'cherry', 'apple'}

Get the Length of a Set


To determine how many items a set has, use the len() function.
mySet = {"apple", "banana", "cherry"}
print(len(mySet))
3

Set Items - Data Types


Set items can be of any data type:
set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}
{'cherry', 'apple', 'banana'}
{1, 3, 5, 7, 9}
{False, True}

A set can contain different data types:


set1 = {"abc", 34, True, 40, "male"}
{True, 34, 40, 'male', 'abc'}

type() From Python's perspective, sets are defined as objects with the data type 'set':
myset = {"apple", "banana", "cherry"}
print(type(myset))
<class 'set'>

The set() Constructor


It is also possible to use the set() constructor to make a set.
mySet = set(("apple", "banana", "cherry")) # note the double round-brackets
print(mySet)
{'banana', 'apple', 'cherry'}

Access Items
You cannot access items in a set by referring to an index or a key. But you can loop through
the set items using a for loop, or ask if a specified value is present in a set, by using
the in keyword.

19
Python Programming II UNIT

mySet = {"apple", "banana", "cherry"}


for x in mySet:
print(x)
banana
apple
cherry
Check if "banana" is present in the set:
mySet = {"apple", "banana", "cherry"}
print("banana" in mySet)
True

Change Items
Once a set is created, you cannot change its items, but you can add new items.

Add Items
To add one item to a set use the add() method.
mySet = {"apple", "banana", "cherry"}
mySet.add("orange")
print(mySet)
{'apple', 'orange', 'cherry', 'banana'}

Add Sets
To add items from another set into the current set, use the update() method.
mySet = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}
mySet.update(tropical)
print(mySet)
{'apple', 'mango', 'cherry', 'pineapple', 'banana', 'papaya'}

Add Any Iterable


The object in the update() method does not have to be a set, it can be any iterable object
(tuples, lists, dictionaries etc.).
mySet = {"apple", "banana", "cherry"}
mylist = ["kiwi", "orange"]
mySet.update(mylist)
print(mySet)
{'banana', 'cherry', 'apple', 'orange', 'kiwi'}

Remove Item
To remove an item in a set, use the remove(), or the discard() method.
mySet = {"apple", "banana", "cherry"}
mySet.remove("banana")
print(mySet)
Note: If the item to remove does not exist, remove() will raise an error.
Remove "banana" by using the discard() method:

20
Python Programming II UNIT

mySet = {"apple", "banana", "cherry"}


mySet.discard("banana")
print(mySet)

Note: If the item to remove does not exist, discard() will NOT raise an error.
You can also use the pop() method to remove an item, but this method will remove
the last item. Remember that sets are unordered, so you will not know what item that gets
removed.
The return value of the pop() method is the removed item.
mySet = {"apple", "banana", "cherry"}
x = mySet.pop()
print(x)
print(mySet)
banana
{'cherry', 'apple'}

Note: Sets are unordered, so when using the pop() met you do not know which item that
gets removed.
The clear() method empties the set:
mySet = {"apple", "banana", "cherry"}
mySet.clear()
print(mySet)
set()

The del keyword will delete the set completely:


mySet = {"apple", "banana", "cherry"}
del mySet
print(mySet)
#this will raise an error because the set no longer exists
Loop Items
You can loop through the set items by using a for loop:
mySet = {"apple", "banana", "cherry"}
for x in mySet:
print(x)
cherry
apple
banana

Join Two Sets


There are several ways to join two or more sets in Python. You can use the union() method
that returns a new set containing all items from both sets, or the update() method that inserts
all the items from one set into another:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)

21
Python Programming II UNIT

{'c', 2, 3, 'a', 1, 'b'}


The update() method inserts the items in set2 into set1:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1)
{2, 3, 'b', 1, 'a', 'c'}

Dictionary

Dictionaries are used to store data values in( key: value) pairs.
A dictionary is a collection which is ordered*, changeable and do not allow duplicates.
Dictionaries are written with curly brackets, and have keys and values:

myDict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(myDict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

Dictionary Items
Dictionary items are ordered, changeable, and does not allow duplicates.
Dictionary items are presented in key:value pairs, and can be referred to by using the key
name.
myDict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(myDict["brand"])
Ford

22
Python Programming II UNIT

Ordered or Unordered
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries
are unordered.
When we say that dictionaries are ordered, it means that the items have a defined order, and
that order will not change.
Unordered means that the items does not have a defined order, you cannot refer to an item by
using an index.

Changeable
Dictionaries are changeable, meaning that we can change, add or remove items after the
dictionary has been created.

Duplicates Not Allowed


Dictionaries cannot have two items with the same key:
myDict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(myDict)

{'brand': 'Ford', 'model': 'Mustang', 'year': 2020}

Dictionary Length
To determine how many items a dictionary has, use the len() function:

print(len(myDict))
3

Dictionary Items - Data Types


The values in dictionary items can be of any data type:
myDict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
{'brand': 'Ford', 'electric': False, 'year': 1964, 'colors': ['red', 'white', 'blue']}

type()
From Python's perspective, dictionaries are defined as objects with the data type 'dict':
<class 'dict'>

23
Python Programming II UNIT

Accessing Items
You can access the items of a dictionary by referring to its key name, inside square brackets:
myDict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = myDict["model"]
print(x)

There is also a method called get() that will give you the same result:
x = myDict.get("model")

The keys() method will return a list of all the keys in the dictionary.
x = myDict.keys()
dict_keys(['brand', 'model', 'year'])

The list of the keys is a view of the dictionary, meaning that any changes done to the
dictionary will be reflected in the keys list.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.keys()
print(x) #before the change
car["color"] = "white"

print(x) #after the change


dict_keys(['brand', 'model', 'year'])
dict_keys(['brand', 'model', 'year', 'color'])

The values() method will return a list of all the values in the dictionary.
x = myDict.values()
dict_values(['Ford', 'Mustang', 1964])

The list of the values is a view of the dictionary, meaning that any changes done to the
dictionary will be reflected in the values list.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
print(x) #before the change

24
Python Programming II UNIT

car["year"] = 2020
print(x) #after the change
dict_values(['Ford', 'Mustang', 1964])
dict_values(['Ford', 'Mustang', 2020])

The items() method will return each item in a dictionary, as tuples in a list.
myDict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = myDict.items()
print(x)
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])

You can change the value of a specific item by referring to its key name:
myDict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
myDict["year"] = 2018
print(myDict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 2018}

The update() method will update the dictionary with the items from the given argument.
The argument must be a dictionary, or an iterable object with key:value pairs.
myDict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
myDict.update({"year": 2020})

print(myDict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 2020}

Removing items
There are several methods to remove items from a dictionary:
The pop() method removes the item with the specified key name:
myDict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

25
Python Programming II UNIT

myDict.pop("model")
print(myDict)
{'brand': 'Ford', 'year': 1964}

Copy a Dictionary
You 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().
myDict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = myDict.copy()
print(mydict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

Another way to make a copy is to use the built-in function dict().


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

Nested Dictionaries
A dictionary can contain dictionaries, this is called nested dictionaries.
mymarks = {
"I Year" : {
"M" : 66,
"PPs" : 84
},
"II Year" : {
"OS" : 67,
"DBMS" : 77
},
"III Year" : {
"CN" : 78,
"WT" : 56
}
}

print(mymarks)

26
Python Programming II UNIT

{'I Year': {'M': 66, 'PPs': 84}, 'II Year': {'OS': 67, 'DBMS': 77}, 'III Year': {'CN': 78, 'WT':
56}}

IYear = {"M" : 66, "PPs" : 84}


IIYear = {"OS" : 67, "DBMS" : 77}
IIIYear = {"CN" : 78, "WT" : 56}

mymarks = {"I Year" : IYear, "II Year" : IIYear, "III Year" : IIIYear}

print(mymarks)
{'I Year': {'M': 66, 'PPs': 84}, 'II Year': {'OS': 67, 'DBMS': 77}, 'III Year': {'CN': 78, 'WT':
56}}

27
Python Programming UNIT - III

Python Functions

A function is a block of code which only runs when it is called. You can pass data, known as
parameters, into a function. A function can return data as a result.

Functions are classified in to 3 types

1. User-defined functions
2. Built-in functions
3. Lambda functions

User-defined functions:
The functions which defined by the programmer according to his requirement are known as user-
defined functions.
Creating a Function

In Python a function is defined using the def keyword:

Example
def function():
print("IT is Best in AITAM")
Calling a Function

To call a function, use the function name followed by parenthesis:

Example
def function(): # Function Definition
print("IT is Best in AITAM ")

function() # Function Call

IT is Best in AITAM
Function Name:
The function name can be any identifier followed by parenthesis.
Arguments:

Arguments are also known as Parameters. Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you want, just separate them with a comma.

1
Python Programming UNIT - III
The following example has a function with one argument (cname). When the function is called,
we pass along a first name, which is used inside the function to print the cname:

Example
def function(cname):
print(cname + " College")

function("AITAM")

AITAM College

Return Values

To let a function return a value, use the return statement. In python the function can return more
than one value simultaneously.

Example 1
def my_function(x):
return x * x

print(my_function(3))
print(my_function(5))
print(my_function(9))

Example 2

def cal(a, b):


return(a+b, a-b, a*b, a/b, a//b, a%b)

x = int(input(‘Enter First Value’))


y = int(input(‘Enter Second Value’))
res = cal(x,y)
print(res)

The above function can return multiple values.


Types of Functions
Based on the passing arguments python functions can be classified in to four types

1. Required Arguments
2. Keyword Arguments
3. Default Arguments
4. Variable-size length Arguments

2
Python Programming UNIT - III

Required Arguments

By default, a function must be called with the correct number of arguments. The function call and
function definition should contains the same type and same number of arguments. Meaning that if
your function expects 2 arguments, you have to call the function with 2 arguments, not more, and
not less.

Example 1
This function expects 2 arguments, and gets 2 arguments:

def function(cname, name):


print(cname + " " + name)

function("AITAM", "COLLEGE")

AITAM COLLEGE

Example 2
This function expects 3 arguments, and gets 3 arguments:

def sumfun(a, b, c):


print(a+b+c)

x = int(input(‘Enter First Value’))


y = int(input(‘Enter Second Value’))
z = int(input(‘Enter Third Value’))
sumfun(x,y,z)

Keyword Arguments

You can also send arguments with the key = value syntax. This way the order of the arguments
does not matter.

Example 1
def function(dept, college):
print("College = " + college)
print("Department = " + college)

function(college = "AITAM", dept = "IT")

3
Python Programming UNIT - III
Example 2

def display(a, b, c, d):


print(b, d, a, c)

display(d =10, c=20, b=30, a=40)


The order of parameters need not be same in keyword arguments. The phrase Keyword
Arguments are often shortened to kwargs in Python documentations.

Default Parameter Value

The following example shows how to use a default parameter value. If we call the function
without argument, it uses the default value:

Example 1
def circle(r, p=3.14):
print(2*p*r)
print(p*r*r)

circle(3)
Example 2

def display(a=0, b=0, c=0, d=0):


print(a, b, c, d)

display()
display(10)
display(10, 20)
display(10, 20, 30)
display(10, 20, 30, 40)

variable-size length Arguments:


Also known as Arbitrary Arguments. If you do not know how many arguments that will be
passed into your function, add a * before the parameter name in the function definition. This way
the function will receive a tuple of arguments, and can access the items accordingly.
Example
def display(*a):
print(a[0], a[1],a[2]c, a[3])

display(10, 20, 30, 40)

4
Python Programming UNIT - III

Passing a List as an Argument

You can send any data types of argument to a function (string, number, list, dictionary etc.), and it
will be treated as the same data type inside the function.

E.g. if you send a List as an argument, it will still be a List when it reaches the function:

Example
def my_function(food):
for x in food:
print(x)

fruits = ["apple", "banana", "cherry"]

my_function(fruits)

The pass Statement

Function definitions cannot be empty, but if you for some reason have a function definition with
no content, put in the pass statement to avoid getting an error.

Example
def myfunction():
pass
Recursion

A function calling itself until the given condition satisfied. The recursion contains two cases.

Base case: The base case is used to terminate the recursive function

Recursive Case: The recursive case is used to call the same function continuously.

Example-1

def rfact(n):
if(n== 0) or (n==1):
return 1
else:
return n*rfact(n-1)

x = int(input(‘Enter Value’))
if x<0:
5
Python Programming UNIT - III
print(‘Enter positive integer’)
else:
print(rfact(x))

Example-2

def rfib(n):
if(n<=1:
return n
else:
return rfib(n-1+rfib(n-2)

x = int(input(‘Enter Value’))
if x<0:
print(‘Enter positive integer’)
else:
for I in range(x):
print(rfact(i))

Built-in functions:

Built-in functions are pre-defined functions.Python provides a lot of built-in functions that eases
the writing of code.

abs(): Return the absolute value of a number:

x = abs(-7.25)

bin():Return the binary version of 36:

x = bin(36)

complex():Convert the number into a complex number:

x = complex(3, 5)

input(): reads value from the input

x = input('Enter your name:')


print('Hello, ' + x)

and also include many other functions from string, list, tuple, set and dictionary

6
Python Programming UNIT - III

Lambda Functions:

 Lambda functions are functions but do not defined using ‘def’ keyword.
 Lambda functions are defined using ‘lambda’ keyword.
 They do not have any name, so they are called ‘Anonymous Functions’
 These are one-line functions
 These functions contain any number of arguments
 These functions contain only one expression
 These functions can return the value of expression
 They cannot access global variables.

Syntax:
lambda arguments : expression

Example-1:
s = lambda a : a+10
print(s(10))
#Output : 20

Example-2:
s = lambda a, b : a*b
print(s(10, 20))
#Output : 200

Example-3:
s = lambda a, b, c : a+b*c
print(s(2,5,10))
#Output : 52

Example-4:
print((lambda a, b : a*b)(5, 6))
#Output : 30

Example-5:
s = lambda x, y=10, z=15 : x+y*z
print(s(10))
#Output : 160

Example-6:
p = lambda *args : sum(args)
print(p(10,20,30,40))
#Output : 100
#here sum() is a built-in function

7
Python Programming UNIT - III

Example-7:
f = lambda x, fun : x+fun(x)
print(f(20, lambda x:x*x))
#Output : 420
# This function is also known as higher order function

Example-8:
print((lambda x: (x%2 and 'ODD' or 'EVEN'))(30))
#Output : EVEN
print((lambda x: (x%2 and 'ODD' or 'EVEN'))(31))
#Output : ODD

Example-9:
s = lambda str : str in 'IT is BEST department in AITAM'
print(s('BEST')) #Output : True
print(s('CSE')) #Output : False

filter():

The filter() method filters the given sequence with the help of a function that tests each element
in the sequence to be true or not.

num = [10, 21, 7, 15, 9, 19, 27, 20]


large = list(filter(lambda num: num<20, num))
print(large)

#Output : [10, 7, 15, 9, 19]

num = [10, 21, 7, 15, 9, 19, 27, 20]


div = list(filter(lambda x: x%3==0, num))
print(div)

#Output : [21, 15, 9, 27]

map():

map() function returns a map object(which is an iterator) of the results after applying the given
function to each item of a given iterable (list, tuple etc.)

num = [10, 21, 7, 15, 9, 19, 27, 20]


double = list(map(lambda x: x*2, num))
print(double)

#Output : [20, 42, 14, 30, 18, 38, 54, 40]

8
Python Programming UNIT - III
num = [10, 21, 7, 15, 9, 19, 27, 20]
ube = list(map(lambda x: pow(x,3), num))
print(cube)

#Output: [1000, 9261, 343, 3375, 729, 6859, 19683, 8000]

reduce():

The reduce(fun,seq) function is used to apply a particular function passed in its argument to
all of the list elements mentioned in the sequence passed along.This function is defined in
“functools” module. [1000, 9261, 343, 3375, 729, 6859, 19683, 8000]

from functools import reduce


num = [10, 21, 7, 15, 9, 19, 27, 20]
s = reduce((lambda x, y: x+y), num)
print(s)

#Output: 128

File Handling Concepts

File is a storage location used to store the data permanently. File handling is an important part of
any web application. Python has several functions for creating, reading, updating, and deleting
files.

File Operations
1. Opening a file
2. Read/write operation
3. Closing a file

Opening a file

The key function for working with files in Python is the open() function. The open() function
takes two parameters; filename, and mode.

File_obj = open(“File_Name”, “Access_Mode”)

The open() function returns a file object, which has a read() method for reading the content of the
file. Here File_Name is the name of the file to be accessed and is literal. There are four different
methods (Access modes) for opening a file:

"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
9
Python Programming UNIT - III

In addition you can specify if the file should be handled as binary or text mode

"t" - Text - Default value. Text mode


"b" - Binary - Binary mode (e.g. images)

Read Operation:

The read() method is used to perform read operationTo open a file for reading it is enough to
specify the name of the file:

f = open("demofile.txt")

The code above is the same as:

f = open("myfile.txt", "rt")
f = open("myfile.txt", "r")

Because "r" for read, and "t" for text are the default values, you do not need to specify them. In
python a file opens in read mode by default.

Create a text file ‘sample.txt’ using text editor with the following data.

Aditya Institute of Technology and Management


Department of Information technology
I am learning Python

To open the file, use the built-in open() function.

Example-1
f = open("sample.txt", "r")
print(f.read(6))

#Output : Aditya

Example-2
f = open("sample.txt", "r")
print(f.readline())

#Output : Aditya Institute of Technology and Management

10
Python Programming UNIT - III

Example-3
f = open("sample.txt", "r")
print(f.readline())
print(f.readline())

#Output : Aditya Institute of Technology and Management


Department of Information technology

Example-4
f = open("sample.txt", "r")
print(f.readlines())

#Output : Aditya Institute of Technology and Management


Department of Information technology
I am learning Python

readlines() method is same as simple read() method. Both will read the entire data of a file.

Example-5

By looping through the lines of the file, we can read the whole file, line by line:

f = open("sample.txt", "r")
for x in f:
print(x)

#Output : Aditya Institute of Technology and Management


Department of Information technology
I am learning Python
Closing a File:

It is a good practice to always close the file when you are done with it.

f = open("sample.txt", "r")
print(f.readlines())
f.close()

#Output : Aditya Institute of Technology and Management


Department of Information technology
I am learning Python

11
Python Programming UNIT - III

Note: You should always close your files, in some cases, due to buffering, changes made to a file
may not show until you close the file.

Write Operation:

The write() method is used to perform both write and append operations. To write to an existing
file, you must add a parameter to the open() function:

"a" - Append - will append to the end of the file, otherwise creates a new file.
"w" - Write - will overwrite any existing content, otherwise creates a new file.

Example -1: Append

Open the file "sample.txt" and append content to the file:

f = open("sample.txt", "a")
f.write("Python is a general purpose programming language")
f.close()

#open and read the file after the appending:


f = open("sample.txt", "r")
print(f.read())

#Output : Aditya Institute of Technology and Management


Department of Information technology
I am learning Python
Python is a general purpose programming language

Example -2: Write

Open the file "sample.txt" and write the content to the file:

f = open("sample.txt", "w")
f.write("Now, Python is very popular programming language")
f.close()

#open and read the file after the appending:


f = open("sample.txt", "r")
print(f.read())

#Output : Now, Python is very popular programming language

12
Python Programming UNIT - III

Example -3: Write

Open the file "sample.txt" and write the content to the file:

f = open("sample.txt", "w")
mylist = [‘apple’, ‘mango’, ‘orange’]
f.write(mylist)
f.close()

#open and read the file after the appending:


f = open("sample.txt", "r")
print(f.read())

#Output : [‘apple’, ‘mango’, ‘orange’]

Create a New File


To create a new file in Python, use the open() met with one of the following parameters:
"x" - Create - will create a file, returns an error if le exist
Example

Create a file called "myfile.txt":

f = open("myfile.txt", "x")

Result: a new empty file is created!

Delete a File

To delete a file, you must import the OS module, and run its os.remove() function:

Example

Remove the file "sample.txt":

import os
os.remove("sample.txt")

13
Python Programming UNIT - III

Check if File exist:

To avoid getting an error, you might want to check if the file exists before you try to delete it:

Check if file exists, then delete it:

import os
if os.path.exists("sample.txt"):
os.remove("sample.txt")
else:
print("The file does not exist")

Delete Folder

To delete an entire folder, use the os.rmdir() method:

Remove the folder "myfolder":

import os
os.rmdir("myfolder")

Note: You can only remove empty folders.

14
Python Programming Unit - 4

Packages vs modules in Python

A Module always corresponds to a single Python file. It contains logic like classes, functions, and
constants. A file containing a set of functions you want to include in your application.

A Package is basically a module that could contain many modules or sub-packages.

Package structure
Packages don't only contain modules, though. They consist of top-level scripts, documentation,
and tests, as well. The following example shows how a basic Python package can be structured:

package_name/
docs/
scripts/
src/
package_a
__init__.py
module_a.py
package_b
__init__.py
module_b.py
tests/
__init__.py
test_module_a.py
test_module_b.py
LICENSE.txt
CHANGES.txt
setup.py
setup.cfg

Let's understand what each file in the tree above is used for:

• package_name: represents the main package.


• docs: includes documentation files on how to use the package.
• scripts/: your top-level scripts.
• src: where your code goes. It contains packages, modules, sub-packages, and so on.
• tests: where you can put unit tests.
• LICENSE.txt: contains the text of the license (for example, MIT).
1
Python Programming Unit - 4
• CHANGES.txt: reports the changes of each release.
• setup.py: contains the build script for your build tools.
• setup.cfg: the configuration files of your build tools.

The __init__.py is a dependency file that helps Python look for the available modules in our
package directory. If we remove this file, Python will fail to import our modules.

Types of modules

In Python, there are two types of modules.

1. Built-in Modules
2. User-defined Modules

User-defined modules

The modules which the user defines or create are called a user-defined module. We can create
our own module, which contains classes, functions, variables, etc., as per our requirements.

Create a Module

To create a module just save the code you want in a file with the file extension .py

Example

#Save this code in a file named fact.py

def factorial(n):
f=1
for x in range(2,n+1):
f = f*x
return(f)

Now we can use the module we just created, by using the import statement:

Import the module named fact, and call the factorial function:

import fact
a = int(input(‘Enter any value’))
f=f act.factorial(a)
print(f)

Note: When using a function from a module, use the syntax: module_name.function_name.

2
Python Programming Unit - 4

Variables in Module

The module can contain functions, but also variables of all types (arrays, dictionaries, objects etc):

Example

Save this code in the file mydata.py

person1 = {
"name": "Vijay",
"age": 36,
"country": "India"
}

Import the module named mydata, and access the person1 dictionary:

import mydata

a = mydata.person1["age"]
print(a)
Naming a Module
You can name the module file whatever you like, but it must have the file extension .py
The module names are identifiers
Re-naming a Module

You can create an alias when you import a module, by using the as keyword:

Example

Create an alias for mydata called md:

import mydata as md

a = md.person1["age"]
print(a)

How to import modules


In Python, the import statement is used to import the whole module. Also, we can import specific
classes and functions from a module.

For example, import module name

When the interpreter finds an import statement, it imports the module presented in a search path.
The module is loaded only once, even we import multiple times.
3
Python Programming Unit - 4
To import modules in Python, we use the Python import keyword. With the help of
the import keyword, both the built-in and user-defined modules are imported.

import math

# use math module functions


print(math.sqrt(5))

# Output 2.23606797749979

Import multiple modules

If we want to use more than one module, then we can import multiple modules. This is the
simplest form of import statement that we already used in the above example.

Syntax of import statement:

import module1[,module2[,.. moduleN]

# Import two modules


import math, random

print(math.factorial(5))

print(random.randint(10, 20))

120

18

Import only specific classes or functions from a module

To import particular classes or functions, we can use the from...import statement. It is an alternate
way to import. Using this way, we can import individual attributes and methods directly into the
program.

In this way, we are not required to use the module name. See the following example.

Syntax of from...import statement:

from <module_name> import <name(s)>

4
Python Programming Unit - 4
# import only factorial function from math module
from math import factorial

print(factorial(5))

Import with renaming a module

If we want to use the module with a different name, we can use from..import…as statement.

It is also possible to import a particular method and use that method with a different name. It is
called aliasing. Afterward, we can use that name in the entire program.

Syntax of from..import ..as keyword:

from <module_name> import <name> as <alternative_name>

import random as rand

print(rand.randrange(10, 20, 2))

Import all names

If we need to import all functions and attributes of a specific module, then instead of writing all
function names and attribute names, we can import all using an asterisk *.

from math import *


print(pow(4,2))
print(factorial(5))
print(pi*3)
print(sqrt(100))

Built-in Modules
Built-in modules come with default Python installation. One of Python’s most significant
advantages is its rich library support that contains lots of built-in modules. Hence, it provides a lot
of reusable code.

Some commonly used Python built-in modules are datetime, os, math, sys, random, etc.

Example
Import and use the platform module:
import platform

5
Python Programming Unit - 4
x = platform.system()
print(x)

Using the dir() Function

There is a built-in function to list all the function names (or variable names) in a module.
The dir() function:

Example

List all the defined names belonging to the platform module:

import platform

x = dir(platform)
print(x)

Note: The dir() function can be used on all modules, also the ones you create yourself.

>>> help('modules')
Resources from other modules are loaded by import statement. The general format of using a
function in any module is like this:

import module

module.function([arguments if any])
The sqrt() function in math module returns square root of a number.
>>> import math
>>> math.sqrt(100)
10.0

os module

This module has functions to perform many tasks of operating system.

mkdir():
We can create a new directory using mkdir() function from os module.
import os
os.mkdir("d:\\tempdir")
A new directory corresponding to path in string argument in the function will be created. If we
open D drive in Windows explorer we should notice tempdir folder created.

chdir():
To change current working directory to use chdir() function.
6
Python Programming Unit - 4
import os
os.chdir("d:\\temp")

getcwd():
This function in returns name off current working directory.
os.getcwd()
'd:\\temp'
Directory paths can also be relative. If current directory is set to D drive and then to temp without
mentioning preceding path, then also current working directory will be changed to d:\temp

rmdir():
The rmdir() function in os module removes a specified directory either with absolute or relative
path. However it should not be the current working directory and it should be empty.
os.chdir("tempdir")
os.getcwd()
'd:\\tempdir'

listdir():
The os module has listdir() function which returns list of all files in specified directory.
os.listdir("c:\\Users")
['acer', 'All Users', 'Default', 'Default User', 'desktop.ini', 'Public']

random module

Python’s standard library contains random module which defines various functions for handling
randomization. Python uses a pseudo-random generator based upon Mersenne Twister algorithm
that produces 53-bit precision floats. Functions in this module depend on pseudo-random number
generator function random() which generates a random float number between 0.0 and 1.0.

random.random(): Returns a random float number between 0.0 to 1.0. The function doesn’t need
any arguments
import random
random.random()
0.755173688207591

random.randint(): Returns a random integer between the specified integers


import random
random.randint(1,100)
58
random.randint(1,100)
91

random.randrange(): Returns a random element from the range created by start, stop and step
arguments. The start , stop and step parameters behave similar to range() function.
random.randrange(1,10)
2
random.randrange(1,10,2)
7
Python Programming Unit - 4
3
random.randrange(0,101,10)
40

random.choice(): Returns a randomly selected element from a sequence object such as string, list
or tuple. An empty sequence as argument raises IndexError
import random
random.choice('computer')
'o'
random.choice([12,23,45,67,65,43])
65
random.choice((12,23,45,67,65,43))
23

random.shuffle(): This functions randomly reorders elements in a list.


numbers=[12,23,45,67,65,43]
random.shuffle(numbers)
numbers
[23, 12, 43, 65, 67, 45]
random.shuffle(numbers)
numbers
[23, 43, 65, 45, 12, 67]

math module

This module presents commonly required mathematical functions.


• trigonometric functions
• representation functions
• logarithmic functions
• angle conversion functions
In addition, two mathematical constants are also defined in this module.

Pie π which is defined as ratio of circumference to diameter of a circle and its value is
3.141592653589793, is available in math module.
import math
math.pi
3.141592653589793

Another mathematical constant in this module is e. It is called Euler’s number and is a base of
natural logarithm. Its value is 2.718281828459045
math.e
2.718281828459045
This module contains functions for calculating various trigonometric ratios for a given angle. The
functions (sin, cos, tan etc.) need angle in radians as argument. We on the other hand are used to
express angle in degrees. The math module presents two angle conversion functions (degrees()
and radians()) to convert angle in degrees to radians and vice versa.

8
Python Programming Unit - 4

Trigonometric functions:

radians(): converts angle in degrees to radians.(Note: π radians is equivalent to 180 degrees)


math.radians(30)
0.5235987755982988
degrees(): converts angle in radians to degree.
math.degrees(math.pi/6)
29.999999999999996
Following statements show sin, cos and tan ratios for angle of 30 degrees (0.5235987755982988
radians)
math.sin(0.5235987755982988)
0.49999999999999994
math.cos(0.5235987755982988)
0.8660254037844387
math.tan(0.5235987755982988)
0.5773502691896257
sin(30) 0.5 0.49999999999999994
cos(30) 3/2 0.8660254037844387)
tan(30) 1/2 0. 5773502691896257
math.log(): returns natural logarithm. Natural logarithm is calculated to the base e.
math.log10(): returns base-10 logarithm or standard logarithm of given number.
math.log10(10)
1.0

math.exp(): returns a float number after raising e (math.e) to given number. exp(x) is equivalent
to e**x
math.log10(10)
1.0
math.e**10
22026.465794806703

math.pow(): This function receives two float arguments, raises first to second and returns the
result. pow(4,4) is equivalent to 4**4
math.pow(4,4)
256.0
4**4
256

math.sqrt(): This function computes square root of given number


math.sqrt(100)
10.0
math.sqrt(3)
1.7320508075688772

9
Python Programming Unit - 4

Representation functions:

The ceil() function approximates given number to smallest integer greater than or equal to given
floating point number. The floor() function returns a largest integer less than or equal to given
number
math.ceil(4.5867)
5
math.floor(4.5687)
4

sys module
This module provides functions and variables used to manipulate different parts of the Python
runtime environment.

sys.argv
This return list of command line arguments passed to a Python script. Item at 0th index of this list
is always the name of the script. Rest of the arguments are stored at subsequent indices.
Here is a Python script (test.py) consuming two arguments from command line.
import sys
print ("My name is {}. I am {} years old".format(sys.argv[1], sys.argv[2]))
This script is executed from command line as follows:
C:\python37>python tmp.py Anil 23
My name is Anil. I am 23 years old

sys.exit
This causes program to end and return to either Python console or command prompt. It is used to
safely exit from program in case of exception.

sys.maxsize
It returns the largest integer a variable can take.
import sys
sys.maxsize
9223372036854775807

sys.path
This is an environment variable that returns search path for all Python modules.
sys.path
['', 'C:\\python37\\Lib\\idlelib', 'C:\\python37\\python36.zip', 'C:\\python37\\DLLs',
'C:\\python37\\lib', 'C:\\python37', 'C:\\Users\\acer\\AppData\\Roaming\\Python\\Python37\\site-
packages', 'C:\\python37\\lib\\site-packages']

sys.stdin, sys.stdout, sys.stderr


These are file objects used by the interpreter for standard input, output and errors. stdin is used for
all interactive input (Python shell). stdout is used for the output of print() and of input(). The
interpreter’s prompts and error messages go to stderr.

10
Python Programming Unit - 4

sys.version
This attribute displays a string containing version number of current Python interpreter.

collections module

This module provides alternatives to built-in container data types such as list, tuple and dict.

namedtuple() function

This function is a factory function that returns object of a tuple subclass with named fields. Any
valid Python identifier may be used for a field name except for names starting with an underscore.
collections.namedtuple(typename, field-list)

The typename parameter is the subclass of tuple. Its object has attributes mentioned in field list.
These field attributes can be accessed by lookup as well as by its index.

Following statement declares a employee namedtuple having name, age and salary as fields
import collections
employee=collections.namedtuple('employee', [name, age, salary])

To create a new object of this namedtuple


e1=employee("Ravi", 251, 20000)

Values of the field can be accessible by attribute lookup


e1.name
'Ravi'
Or by index
e1[0]
'Ravi'

OrderedDict() function

Ordered dictionary is similar to a normal dictionary. However, normal dictionary the order of
insertion of keys in it whereas ordered dictionary object remembers the same. The key-value pairs
in normal dictionary object appear in arbitrary order.
d1={}
d1['A']=20
d1['B']=30
d1['C']=40
d1['D']=50

We then traverse the dictionary by a for loop,


for k,v in d1.items():
print (k,v)

A 20
11
Python Programming Unit - 4
B 30
D 50
C 40
But in case of OrderedDict object:
import collections
d2=collections.OrderedDict()
d2['A']=20
d2['B']=30
d2['C']=40
d2['D']=50
Key-value pairs will appear in the order of their insertion.
for k,v in d2.items():
print (k,v)
A 20
B 30
C 40
D 50

deque() function
A deque object supports append and pop operation from both ends of a list. It is more memory
efficient than a normal list object because in a normal list, removing one of iem causes all items to
its right to be shifted towards left. Hence it is very slow.
>>> q=collections.deque([10,20,30,40])
>>> q.appendleft(110)
>>> q
deque([110, 10, 20, 30, 40])
>>> q.append(41)
>>> q
deque([0, 10, 20, 30, 40, 41])
>>> q.pop()
40
>>> q
deque([0, 10, 20, 30, 40])
>>> q.popleft()
110
>>> q
deque([10, 20, 30, 40])

statistics module

This module provides following statistical functions :

mean() : calculate arithmetic mean of numbers in a list


>>> import statistics
>>> statistics.mean([2,5,6,9])
5.5

12
Python Programming Unit - 4
median() : returns middle value of numeric data in a list. For odd items in list, it returns value at
(n+1)/2 position. For even values, average of values at n/2 and (n/2)+1 positions is returned.
>>> import statistics
>>> statistics.median([1,2,3,8,9])
3
>>> statistics.median([1,2,3,7,8,9])
5.0

mode(): returns most repeated data point in the list.


>>> import statistics
>>> statistics.mode([2,5,3,2,8,3,9,4,2,5,6])
2

stdev() : calculates standard deviation on given sample in the form of list.


>>> import statistics
>>> statistics.stdev([1,1.5,2,2.5,3,3.5,4,4.5,5])
1.3693063937629153

time module

This module has many time related functions.

time():
This function returns current system time in ticks. The ticks is number of seconds elapsed after
epoch time i.e. 12.00 am, January 1, 1970.
>>> time.time()
1544348359.1183174

localtime():
This function translates time in ticks in a time tuple notation.
>>> tk=time.time()
>>> time.localtime(tk)
time.struct_time(tm_year=2018, tm_mon=12, tm_mday=9, tm_hour=15, tm_min=11, tm_sec=25,
tm_wday=6, tm_yday=343, tm_isdst=0)

asctime():
This functions returns a readable format of local time
>>> tk=time.time()
>>> tp=time.localtime(tk)
>>> time.asctime(tp)
'Sun Dec 9 15:11:25 2018'

ctime():
This function returns string representation of system's current time
>>> time.ctime()
'Sun Dec 9 15:17:40 2018'

13
Python Programming Unit - 4

sleep():
This function halts current program execution for a specified duration in seconds.
>>> time.ctime()
'Sun Dec 9 15:19:14 2018'
>>> time.sleep(20)
>>> time.ctime()
'Sun Dec 9 15:19:34 2018'

14
UNIT -5
(Classes in Python)

12/1/2022 1
What is OOP?
Why is OOP?

- A programming paradigm that is


focus on objects and data  Data Abstraction or
Information Hiding

 Code Reusability

 Faster designing and


modeling

 Easier Debugging

12/1/2022
Class Fundamentals Object Fundamentals

 The class defines the shape and  A real world entity


nature of an object.
 An object has both a state and
 Any concept you wish to behavior.
implement in a Object Oriented
program must be encapsulated  The state defines the object , and
within a class.
the behavior defines what the
object does.
 The most important thing to
understand about a class is that it
defines a new data type. Once
defined, this new type can be used
to create objects of that type.

 a class is a template for an


object, and an object is an
instance of a class.
12/1/2022 3
The General Form of a Class
class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;

type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method
}
// ...
type methodnameN(parameter-list) {
// body of method
}
}
12/1/2022 4
1. class Box 18. class BoxDemo
2. { 19. {
3. double width; 20. public static void main(String args[])
4. double height; 21. {
5. double depth; 22. Box b1 = new Box();
6. 23. Box b2 = new Box();
7. double volume() 24. double volume;
8. { 25.
9. return width * height*depth; 26. b1.setDimensions(10,20,15);
10. } 27. b2.setDimensions(3,6,9);
11. void setDimensions (double w, double h, double d) 28.
12. { 29. volume= b1.volume();
13. width=w; 30. System.out.println ("Volume of Box b1 = "+volume);
14. height=h; 31.
15. depth=d; 32. volume= b2.volume();
16. } 33. System.out.println ("Volume of Box b2 = "+volume);
17. } 34. }
12/1/2022 35. } 5
Constructors

 A constructor initializes an object immediately upon creation.

 constructor has the same name as the class in which it resides and is
syntactically similar to a method.

 The Constructor, Once defined, the constructor is automatically called when the
object is created, before the new operator completes.

 Constructors look a little strange because they have no return type, not
even void. This is because the implicit Return type of a class constructor is the
class type itself.

12/1/2022 6
1. /* Constructors */ 19. class BoxDemo
2. class Box 20. {
3. { 21. public static void main(String args[])
4. double width; 22. {
5. double height; 23. Box b1 = new Box();
6. double depth; 24. Box b2 = new Box();
25. double volume;
7. Box() 26.
8. { 27. volume= b1.volume();
9. System.out.println("Constructing a Box"); 28. System.out.println("Volume of Box b1 =
10. width=10; "+volume);
11. height=10; 29.
12. depth=10; 30. volume= b2.volume();
13. } 31. System.out.println("Volume of Box b2
= "+volume);
14. double volume() 32. }
15. { 33. }
16. return width * height * depth;
17. }
12/1/2022 7
18. }
1. /* Parameterized Constructors */ 20. class BoxDemo
2. class Box 21. {
3. { 22. public static void main(String args[])
4. double width; 23. {
5. double height; 24. Box b1 = new Box(10,20,15);
6. double depth; 25. Box b2 = new Box(3,6,9);
7. 26. double volume;
8. Box(double w, double h,double d) 27.
9. { 28. volume= b1.volume();
10. System.out.println("Constructing a Box"); 29. System.out.println("Volume of Box b1 =
11. width=w; "+volume);
30.
12. height=h;
31. volume= b2.volume();
13. depth=d;
14. } 32. System.out.println("Volume of Box b1 =
"+volume);
15. double volume() 33. }
16. { 34. }
17. return width * height * depth;
18. }
19. }
12/1/2022 8
Python Classes/Objects

 Python is an object oriented programming language.

 Almost everything in Python is an object, with its properties and


methods.

 A Class is like an object constructor, or a "blueprint" for creating


objects.

12/1/2022 9
Python Classes/Objects

Create a Class Create Object

To create a class, use the Now we can use the class named
keyword class: MyClass to create objects

Example Example

class MyClass: class MyClass:


x=5 x=5
print(MyClass) p1 = MyClass()
print(p1.x)
Output
Output
<class '__main__.MyClass'>
5

12/1/2022 10
Python Classes/Objects
The __init__() Function:

 The examples above are classes and objects in their simplest form, and
are not really useful in real life applications.

 To understand the meaning of classes we have to understand the built-


in __init__() function.

 All classes have a function called __init__(), which is always executed


when the class is being initiated.

 Use the __init__() function to assign values to object properties, or


other operations that are necessary to do when the object is being
created.
12/1/2022 11
Ramesh 45

Python Classes/Objects
The __init__() Function:
 Create a class named Person, use the __init__() function to assign values for name and
age.

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

p1 = Person("Ramesh", 45)
Output
print(p1.name) Ramesh
print(p1.age) 45

Note: The __init__() function is called automatically every time the class is being used to create a new object.

12/1/2022 12
Ramesh 45

Python Instance Variables/Methods

If we use instance variables inside a met such methods are called instance
methods. The instance method performs a set of actions on the data/value
provided by the instance variables.

 A instance method is bound to the object of the class.


 It can access or modify the object state by changing the value of a instance
variables

When we create a class in Python, instance methods are used regularly.

To work with an instance met we use the self keyword.

We use the self keyword as the first parameter to a method. The self refers to the
current object.

12/1/2022 13
Ramesh 45

Python Instance Variables/Methods

12/1/2022 14
Python Instance Variables/Methods
class Student:
# constructor # create first object
def __init__(self, name, age): print('First Student')
# Instance variable s1 = Student("Jessy", 18)
self.name = name # call instance method
self.age = age s1.show()
# create second object
# instance method access instance variable
print('Second Student')
def show(self):
s2 = Student("Kelly", 19)
print('Name:', self.name, 'Age:', self.age)
# call instance method
s2.show()
First Student
Name: Jessy Age: 18
Second Student
Name: Kelly Age: 19

12/1/2022 15
Ramesh 45

Python Instance Variables/Methods

Inside any instance met we can use self to access any data or
method that reside in our class. We are unable to access it without
a self parameter.

An instance method can freely access attributes and even modify the
value of attributes of an object by using the self parameter.

By Using self.__class__ attribute we can access the class attributes


and change the class state. Therefore instance method gives us control
of changing the object as well as the class state.

12/1/2022 16
Python Instance Variables/Methods
Let’s create the instance method update() method to modify the student age and roll number when
student data details change.

class Student: class Student:


def __init__(self, roll_no, name, age): # create object
# Instance variable print('class I Year')
self.roll_no = roll_no stud = Student(20, “Vijay", 18)
self.name = name # call instance method
self.age = age
stud.show()
# instance method access instance variable
def show(self):
# Modify instance variables
print('Roll Number:', self.roll_no,
'Name:', self.name, 'Age:', self.age) print('class II year')
#instance method to modify instance variable stud.update(35, 19)
def update(self, roll_number, age): stud.show()
self.roll_no = roll_number class I Year Roll Number: 20 Name: Vijay Age: 18
self.age = age class II Year Roll Number: 35 Name: Vijay Age: 19

12/1/2022 17
Python Classes/Objects
The __str__() Function:

1. The __str__() function controls what should be returned when the


class object is represented as a string.
2. If the __str__() function is not set, the string representation of the
object is returned:
The string representation of an object The string representation of an object
WITHOUT the __str__() function WITH the __str__() function

class Person: class Person:


def __init__(self, name, age): def __init__(self, name, age):
self.name = name self.name = name
self.age = age self.age = age Output
Ramesh(45)
p1 = Person(“Ramesh", 45) def __str__(self):
return f"{self.name}({self.age})"
Output
print(p1) <__main__.Person object at 0x15039e602100>
p1 = Person("John", 36)
12/1/2022 print(p1) 18
Python Classes/Objects
Delete Object Properties
You can delete properties on objects by using the del keyword

class Person:
def __init__(self, name, age):
self.name = name Output
self.age = age
Traceback (most recent call last):
def myfunc(self): File "demo_class.py", line 13, in <module>
print("Hello my name is " + print(p1.age)
self.name) AttributeError: 'Person' object has no attribute 'age'

p1 = Person("John", 36)

del p1.age

print(p1.age)
12/1/2022 19
Python Classes/Objects
Delete Object
You can delete the objects by using the del keyword

class Person:
def __init__(self, name, age): The pass Statement
self.name = name class definitions cannot be empty, but if
self.age = age you for some reason have a class definition
with no content, put in the pass statement
def myfunc(self): to avoid getting an error.
print("Hello my name is " +
self.name) class Person:
Output pass
p1 = Person("John", 36)
Traceback (most recent call last):
del p1 File "demo_class.py", line 13, in <module>
print(p1)
print(p1) NameError: 'p1' is not defined
12/1/2022 20
Python Inheritance

Inheritance allows us to define a class that inherits all the methods


and properties from another class.

Parent class is the class being inherited from, also called base
class. (Existing Class, Base Class)

Child class is the class that inherits from another class, also called
derived class. (Sub Class, Derived Class)

The main purpose of inheritance is the reusability of code because


we can use the existing class to create a new class instead of
creating it from scratch.
12/1/2022 21
Python Inheritance

Types Of Inheritance:

In Python, based upon the number of child and parent classes involved,
there are five types of inheritance. The type of inheritance are listed
below:

1. Single inheritance
2. Multiple Inheritance
3. Multilevel inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance
12/1/2022 22
Python Inheritance

Types Of Inheritance: Single inheritance

In single inheritance, a child class inherits from a single-parent class. Here is one child class
and one parent class.

Create a Child Class


Create a Parent Class To create a class that inherits
Any class can be a parent the functionality from another
class, so the syntax is the class, send the parent class as
same as creating any other a parameter when creating the
class child class

12/1/2022 23
Python Inheritance - Single inheritance

Create a Parent Class Create a Child Class

class Person:
class Person: def __init__(self, fname, lname):
def __init__(self, fname, lname): self.firstname = fname
self.firstname = fname self.lastname = lname
self.lastname = lname
def printname(self):
def printname(self): print(self.firstname, self.lastname)
print(self.firstname, self.lastname)
x = Person("John", “Smith") class Student(Person):
pass
x.printname()
x = Student("Mike", "Ted")
x.printname()
Output
John Smith x = Person("John", "Smith")
x.printname() Output
Mike Ted
12/1/2022 John Smith 24
Python Inheritance

Types Of Inheritance: Multiple inheritance

In multiple inheritance, one child class can inherit from multiple parent classes. So here is one
child class and multiple parent classes.

12/1/2022 25
Python Inheritance - Multiple inheritance

# Parent class 1 # Child class


class Employee(Person, Company):
class Person:
def Employee_info(self, salary, skill):
def person_info(self, name, age): print('Inside Employee class')
print('Inside Person class') print('Salary:', salary, 'Skill:', skill)
print('Name:', name, 'Age:', age)
# Create object of Employee
# Parent class 2 emp = Employee()
class Company:
def company_info(self, # access data
company_name, location): emp.person_info('Jessi', 28)
emp.company_info('Google', 'Atlanta')
print('Inside Company class')
emp.Employee_info(12000, 'Machine
print('Name:', company_name, Learning')
'location:', location) Output
Inside Person class
Name: Jessi Age: 28
Inside Company class
Name: Google location: Atlanta
Inside Employee class
12/1/2022 26
Salary: 12000 Skill: Machine Learning
Python Inheritance
Types Of Inheritance: Multilevel inheritance

In multilevel inheritance, a class inherits from a child class or derived class. Suppose three
classes A, B, C. A is the superclass, B is the child class of A, C is the child class of B. In other
words, we can say a chain of classes is called multilevel inheritance.

12/1/2022 27
Python Inheritance - Multilevel inheritance

# Base class # Create object of SportsCar


s_car = SportsCar()
class Vehicle:
def Vehicle_info(self): # access Vehicle's and Car info using
print('Inside Vehicle class') SportsCar object
s_car.Vehicle_info()
# Child class s_car.car_info()
class Car(Vehicle): s_car.sports_car_info()
def car_info(self): Multilevel inheritance
print('Inside Car class')
Output
# Child class Inside Vehicle class
class SportsCar(Car): Inside Car class
def sports_car_info(self): Inside SportsCar class
print('Inside SportsCar class')

12/1/2022 28
Python Inheritance
Types Of Inheritance: Hierarchical Inheritance

In Hierarchical inheritance, more than one child class is derived from a single parent class. In
other words, we can say one parent class and multiple child classes.

12/1/2022 29
Python Inheritance - Hierarchical Inheritance

obj1 = Car()
class Vehicle: obj1.info()
def info(self): obj1.car_info('BMW')
print("This is Vehicle")
obj2 = Truck()
class Car(Vehicle): obj2.info()
def car_info(self, name): obj2.truck_info('Ford')
print("Car name is:", name)
Output
class Truck(Vehicle): This is Vehicle
def truck_info(self, name): Car name is: BMW
print("Truck name is:", name) This is Vehicle
Truck name is: Ford

12/1/2022 30
Python Inheritance
Types Of Inheritance: Hybrid Inheritance

When inheritance is consists of multiple types or a combination of different inheritance is


called hybrid inheritance.

12/1/2022 31
Python Inheritance
Python super() function

When a class inherits all properties and behavior from the parent class is called
inheritance. In such a case, the inherited class is a subclass and the latter class is
the parent class.
In child class, we can refer to parent class by using the super() function. The
super function returns a temporary object of the parent class that allows us to
call a parent class method inside a child class method.

Benefits of using the super() function.


1. We are not required to remember or specify the parent class name to access
its methods.
2. We can use the super() function in both single and multiple inheritances.
3. The super() function support code reusability as there is no need to write the
entire function
12/1/2022 32
Python Inheritance - Python super() function

class Company:
def company_name(self):
return 'Google'

class Employee(Company):
def info(self):
# Calling the superclass method using super()function
c_name = super().company_name()
print("Jessi works at", c_name)
Output
# Creating object of child class Jessi works at Google
emp = Employee()
emp.info()

12/1/2022 33
Python Database Connectivity

In Python, We can use the following modules to communicate with


MySQL.

 MySQL Connector Python


 PyMySQL
 MySQLDB
 MySqlClient
 OurSQL

You can choose any of the above modules as per your requirements.
The way of accessing the MySQL database remains the same.
I recommend you to use any of the following two modules:-

 MySQL Connector Python


PyMySQ
 12/1/2022 34
Python Database Connectivity

Advantages and benefits of MySQL Connector Python: –

 MySQL Connector Python is written in pure Python, and it is self-


sufficient to execute database queries through Python.

 It is an official Oracle-supported driver to work with MySQL and


Python.

 It is Python 3 compatible, actively maintained.

12/1/2022 35
Python Database Connectivity
How to connect MySQL database in Python

12/1/2022 36
Python Database Connectivity

Let’s see how to connect the MySQL database in Python using the ‘MySQL
Connector Python’ module.

Arguments required to connect


You need to know the following detail of the MySQL server to perform the
connection from Python.
Argument Description
Username The username that you use to work with MySQL Server. The default
username for the MySQL database is a root.
Password Password is given by the user at the time of installing the MySQL server. If
you are using root then you won’t need the password.
Host name The server name or Ip address on which MySQL is running. if you are
running on localhost, then you can use localhost or its IP 127.0.0.0
Database name The name of the database to which you want to connect and perform the
operations.

12/1/2022 37
Python Database Connectivity

How to Connect to MySQL Database in Python

1. Install MySQL connector module


Use the pip command to install MySQL connector Python.
Command: pip install mysql-connector-python

2. Import MySQL connector module


Import using a import mysql.connector statement so you can use this
module’s methods to communicate with the MySQL database.

3. Use the connect() method


Use the connect() method of the MySQL Connector class with the required
arguments to connect MySQL. It would return a MySQLConnection object if
the connection established successfully
mydb = mysql.connector.connect( host="localhost",
user="yourusername", password="yourpassword", database="mydatabase”)
12/1/2022 38
Python Database Connectivity

How to Connect to MySQL Database in Python

4. Use the cursor() method


Use the cursor() method of a MySQLConnection object to create a cursor
object to perform various SQL operations.

mycursor = mydb.cursor()

5. Use the execute() method


The execute() methods run the SQL query and return the result.

mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address


VARCHAR(255))“)

12/1/2022 39
Python Database Connectivity

How to Connect to MySQL Database in Python

6. Extract result using fetchall()


Use cursor.fetchall() or fetchone() or fetchmany() to read query result.

mycursor.execute("SELECT * FROM customers")


myresult = mycursor.fetchall()

7. Close cursor and connection objects


use cursor.close() and connection.close() method to close open connections
after your work completes

mycursor.close()
Mydb.close()

12/1/2022 40
Python Database Connectivity

create a database named "mydatabase":

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)

mycursor = mydb.cursor()

mycursor.execute("CREATE DATABASE mydatabase")

12/1/2022 41
Python Database Connectivity

Return a list of your system's databases:


import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)

mycursor = mydb.cursor()

mycursor.execute("SHOW DATABASES")

for x in mycursor:
print(x)
12/1/2022 42
Python Database Connectivity

Create a table named "customers“ and insert data:


import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase”)
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address
VARCHAR(255))")
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)

12/1/2022 43
Python Database Connectivity

Select all records from the "customers" table, and display the result:

import mysql.connector

mydb =
mysql.connector.connect( host="localhost", user="yourusername",
password="yourpassword", database="mydatabase”)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)

12/1/2022 44
Python Database Connectivity

Modify the address column from "Valley 345" to "Canyon 123":

import mysql.connector

mydb =
mysql.connector.connect( host="localhost", user="yourusername",
password="yourpassword", database="mydatabase”)
mycursor = mydb.cursor()

sql = "UPDATE customers SET address = 'Canyon 123' WHERE address =


'Valley 345'“
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) affected")

12/1/2022 45
Python Programming UNIT - 6

Regular Expressions (RegEx)

The Regex or Regular Expression is a way to define a pattern for searching or


manipulating strings. We can use a regular expression to match, search, replace, and
manipulate inside textual data.

Regular expressions are instrumental in extracting information from text such as log files,
spreadsheets, or even textual documents. For example, below are some of the cases
where regular expressions can help you to save a lot of time.
• Searching and replacing text in files
• Validating text input, such as password and email address
• Rename a hundred files at a time. For example, You can change the extension of all
files using a regex pattern

The re module
RE module, a built-in Python module that provides all the required functionality needed
for handling patterns and regular expressions.
import re

Use raw string to define a regex


Always write your regex as a raw string. As you may already know, the backslash has a
special meaning in some cases because it may indicate an escape character or escape
sequence. To avoid that always use a raw string. For example, let's say that in Python we
are defining a string that is actually a path to an exercise folder like this

path = "c:\python\task\new"
print(path)
output:
c:\python ask
ew ask

Now, let's assume you wanted to search this path inside a target string using a regular
expression. let's write code for the same.

path = r"c:\python\task\new"
print(path)
output:
c:\python\task\new ask
The character r denotes the raw string.

1
Python Programming UNIT - 6

RegEx Functions
The re module offers a set of functions that allows us to search a string for a match:
Function Description
match() Try to match the regex pattern at the start of the string
findall() Returns a list containing all matches
search() Returns a Match object if there is a match anywhere in the string
split() Returns a list where the string has been split at each match
sub() Replaces one or many matches with a string

Regex Metacharacters
We can use both the special and ordinary characters inside a regular expression. For
example, Most ordinary characters, like 'A', 'p', are the simplest regular expressions; they
match themselves. You can concatenate ordinary characters, so the AITAM pattern
matches the string 'AITAM'.
Apart from this we also have special characters. For example, characters like '|', '+', or '*',
are special. Special metacharacters don’t match themselves. Instead, they indicate that
some rules. Special characters affect how the regular expressions around them are
interpreted.

Metacharacter Description
. (DOT) Matches any character except a newline.
^ (Caret) Matches pattern only at the start of the string.
$ (Dollar) Matches pattern at the end of the string.
* (asterisk) Matches 0 or more repetitions of the regex.
+ (Plus) Match 1 or more repetitions of the regex.

? (Question mark) Match 0 or 1 repetition of the regex.


[] (Square Used to indicate a set of characters. Matches any single character in
brackets) brackets. For example, [abc] will match either a, or, b, or c character.

| (Pipe) used to specify multiple patterns. For example, P1|P2,


where P1 and P2 are two different regexes.
\ (backslash) Use to escape special characters or signals a special sequence. For
example, If you are searching for one of the special characters you can
use a \ to escape them.
[^...] Matches any single character not in brackets.
(...) Matches whatever regular expression is inside the parentheses. For
example, (abc) will match to substring 'abc'

2
Python Programming UNIT - 6

Regex special sequences

The special sequences consist of '\' and a character from the list below. Each special
sequence has a unique meaning.

The following special sequences have a pre-defined meaning and make specific common
patterns more comfortable to use. For example, you can use \d as a simplified definition
for [0..9] or \w as a simpler version of [a-zA-z].

Special Meaning
Sequence
\A Matches pattern only at the start of the string.
\Z Matches pattern only at the end of the string.
\d Matches to any digit. Short for character classes [0-9].
\D Matches to any non-digit. short for [^0-9].
\s Matches any whitespace character. short for character class [ \t\n\x0b\r\f].
\S Matches any non-whitespace character. Short for [^ \t\n\x0b\r\f].
\w Matches any alphanumeric character. Short for character class [a-zA-Z_0-9].
\W Matches any non-alphanumeric character. Short for [^a-zA-Z_0-9]
\b Matches the empty string, but only at the beginning or end of a word. Matches
a word boundary where a word character is [a-zA-Z0-9_].
\B Opposite of a \b. Matches the empty string, but only when it is not at the
beginning or end of a word

Regex Quantifiers

We use quantifiers to define quantities. A quantifier is a metacharacter that determines


how often a preceding regex can occur. you can use it to specify how many times a regex
can repeat/occur.

For example, We use metacharacter *, +, ? and {} to define quantifiers.

3
Python Programming UNIT - 6

Quantifier Meaning

* Match 0 or more repetitions of the preceding regex.


For example, a* matches any string that contains zero or more occurrences of
'a'.
+ Match 1 or more repetitions of the preceding regex.
For example, a+ matches any string that contains at least one a, i.e., a, aa, aaa,
or any number of a's.
? Match 0 or 1 repetition of the preceding regex.
For example, a? matches any string that contains zero or one occurrence of a.
{2} Matches only 2 copies of the preceding regex.
For example, p{3} matches exactly three 'p' characters, but not four.
{2, 4} Match 2 to 4 repetitions of the preceding regex.
For example, a{2,4} matches any string that contains 3 to 5 'a' characters.
{3,} Matches minimum 3 copies of the preceding regex. It will try to match as
many repetitions as possible.
For example, p{3,} matches a minimum of three 'p' characters.

Regex flags

All RE module methods accept an optional flags argument used to enable various unique
features and syntax variations.

Flag long syntax Meaning


re.A re.ASCII Perform ASCII-only matching instead of full Unicode matching.
re.I re.IGNORECASE Perform case-insensitive matching.
re.M re.MULTILINE This flag is used with metacharacter ^ (caret) and $ (dollar). When this flag is
specified, the metacharacter ^ matches the pattern at beginning of the
string and each newline’s beginning (\n). And the metacharacter $ matches
pattern at the end of the string and the end of each new line (\n)
re.S re.DOTALL Make the DOT (.) special character match any character at all, including a
newline. Without this flag, DOT(.) will match anything except a newline.
re.X re.VERBOSE Allow comment in the regex. This flag is useful to make regex more
readable by allowing comments in the regex.
re.L re.LOCALE Perform case-insensitive matching dependent on the current locale. Use
only with bytes patterns.

4
Python Programming UNIT - 6

match() function

Python re.match() method looks for the regex pattern only at the beginning of the
target string and returns match object if match found; otherwise, it will return None.

The re.match() method will start matching a regex pattern from the very first character of
the text, and if the match found, it will return a re.Match object.

Syntax:
re.match(pattern, string, flags=0)

The regular expression pattern and target string are the mandatory arguments, and flags
are optional.

1. pattern: The regular expression pattern we want to match at the beginning of the
target string. The practice is to write the actual pattern using a raw string.
2. string: The second argument is the variable pointing to the target string in which
we want to look for occurrences of the pattern.
3. flags: Finally, the third argument is optional and by default no flags are applied.
There are many flag values we can use. For example, the re.I is used for
performing case-insensitive searching.

import re

target_string = "AITAM Engg College"


result = re.match(r"\w{5}", target_string) #

# printing the Match object


print(result)

# Extract match value


print(result.group())

output

<re.Match object; span=(0, 5), match='AITAM'>

AITAM

5
Python Programming UNIT - 6

import re

target_string = "AITAM Engg College"


x = re.match('AITAM', target_string)
if (x):
print('Object Matched')
else:
print('Not Matched')

output

Object Matched

The Match object has several methods and attributes to get the information about the
matching string.

Method Description
group() Return the string matched by the regex
start() Return the starting position of the match
end() Return the ending position of the match
span() Return a tuple containing the (start, end) positions of the match.
import re

target_string = "AITAM and IT"

# Match five-letter word


res = re.match(r"\b\w{5}\b", target_string)
# printing entire match object
print(res)
# Extract Matching value
print(res.group())
# Start index of a match
print(res.start())
# End index of a match
print("End index: ", res.end())
# Start and end index of a match
pos = res.span()
print(pos)

output:

6
Python Programming UNIT - 6
<re.Match object; span=(0, 5), match='AITAM'>
AITAM
0
End index: 5
(0, 5)

search() function:

Python regex re.search() method looks for occurrences of the regex pattern inside the
entire target string and returns the corresponding Match Object instance where the
match found.

The re.search() returns only the first match to the pattern from the target string. Use
a re.search() to search pattern anywhere in the string.

Syntax:
re.search(pattern, string, flags=0)

The regular expression pattern and target string are the mandatory arguments, and flags
are optional.

1. pattern:The first argument is the regular expression pattern we want to search


inside the target string.
2. string: The second argument is the variable pointing to the target string in which
we want to look for occurrences of the pattern.
3. flags: Finally, the third argument is optional and by default no flags are applied.
There are many flag values we can use. For example, the re.I is used for
performing case-insensitive searching.

Return value

The re.search() method returns a Match object ( i.e., re.Match). This match object contains
the following two items.

1. The tuple object contains the start and end index of a successful match.
2. Second, it contains an actual matching value that we can retrieve using
a group() method.

If the re.search() method fails to locate the occurrences of the pattern that we want to
find or such a pattern doesn’t exist in a target string it will return a None type.

import re

7
Python Programming UNIT - 6
# Target String
target_string = "Gita is a baseball player who was born on June 17"

# search() for eight-letter word


result = re.search(r"\w{8}", target_string)

# Print match object


print("Match Object", result)

# print the matching word using group() method


print("Matching word: ", result.group())

output:
Match Object <re.Match object; span=(10, 18), match='baseball'>

Matching word: baseball

import re

# Target String
target_string = "Gita is a baseball player who was born on June 17, 1993."

# find substring 'ball'


result = re.search(r"ball", target_string)

# Print matching substring


print(result.group())

# find exact word/substring surrounded by word boundary


result = re.search(r"\bball\b", target_string)
if result:
print(result)

# find word 'player'


result = re.search(r"\bplayer\b", target_string)
print(result.group())

result = re.search(r'(\d{2})', target_string)


print(result.group())

output:
ball

player

17
8
Python Programming UNIT - 6

findall() function:

The RE module’s re.findall() method scans the regex pattern through the entire target
string and returns all the matches that were found in the form of a list.

Syntax:
re.findall(pattern, string, flags=0)

The regular expression pattern and target string are the mandatory arguments, and flags
are optional.

1. pattern:The first argument is the regular expression pattern we want to search


inside the target string.
2. string: The second argument is the variable pointing to the target string in which
we want to look for occurrences of the pattern.
3. flags: Finally, the third argument is optional and by default no flags are applied.
There are many flag values we can use. For example, the re.I is used for
performing case-insensitive searching.

Return Value

The re.findall() scans the target string from left to right as per the regular expression
pattern and returns all matches in the order they were found.

import re

target_string = "AITAM is best engineering college. AITAM is located in Tekkali"


result = re.findall(r"AITAM", target_string)

# print all matches


print("Found following matches")
print(result)

output:
Found following matches

['AITAM', 'AITAM']

import re

9
Python Programming UNIT - 6
target_string = "Gita is a basketball player who was born on June 17, 1993. She played 112
matches with scoring average 26.12 points per game. Her weight is 51 kg."
result = re.findall(r"\d+", target_string)

# print all matches


print("Found following matches")
print(result)

output:
Found following matches

['17', '1993', '112', '26', '12', '51']

import re

target_string = "AITAM is best engineering college. AITAM is located in tekkali."

result = re.findall(r"\w+", target_string)


print(result)

result = re.findall(r"\b[a]\w+\b", target_string, re.I)


print(result)

result = re.findall(r"\b[ab]\w+\b", target_string, re.I)


print(result)

result = re.findall(r"\b[i]\w+\b|\w+[g]\b", target_string)


print(result)

result = re.findall(r"\b\w*[i]\w*\b", target_string)


print(result)

output:
['AITAM', 'is', 'best', 'engineering', 'college', 'AITAM', 'is', 'located', 'in', 'tekkali']

['AITAM', 'AITAM']

['AITAM', 'best', 'AITAM']

['is', 'engineering', 'is', 'in']

['is', 'engineering', 'is', 'in', 'tekkali']

10
Python Programming UNIT - 6

split() function:

The Pythons re module’s re.split() method split the string by the occurrences of the
regex pattern, returning a list containing the resulting substrings.

After reading this article you will be able to perform the following split operations using
regex in Python.

Operation Description

re.split(pattern, str) Split the string by each occurrence of the pattern.


re.split(pattern, str, Split the string by the occurrences of the pattern. Limit the
maxsplit=2) number of splits to 2
re.split(p1|p2, str) Split string by multiple delimiter patterns (p1 and p2).

Syntax:
re.findall(pattern, string, maxsplit=0, flags=0)

• pattern: the regular expression pattern used for splitting the target string.
• string: The variable pointing to the target string (i.e., the string we want to split).
• maxsplit: The number of splits you wanted to perform. If maxsplit is 2, at most two
splits occur, and the remainder of the string is returned as the final element of the
list.
• flags:
By default, no flags are applied. There are many regex flags we can use. For
example, the re.I is used for performing case-insensitive searching.

Return value
It split the target string as per the regular expression pattern, and the matches are
returned in the form of a list.

import re

target_string = "My name is maximums and my luck numbers are 12 45 78"


# split on white-space
word_list = re.split(r"\s+", target_string)
print(word_list)

['My', 'name', 'is', 'maximums', 'and', 'my', 'luck', 'numbers', 'are', '12', '45', '78']

11
Python Programming UNIT - 6

import re

target_string = "12,45,78,85-17-89"
# 2 delimiter - and ,
# use OR (|) operator to combine two pattern
result = re.split(r"-|,", target_string)
print(result)
['12', '45', '78', '85', '17', '89']

import re

target_string = "Python dot.com; is for, Python-developer"


# Pattern to split: [-;,.\s]\s*
result = re.split(r"[-;,.\s]\s*", target_string)
print(result)

['Python', 'dot', 'com', 'is', 'for', 'Python', 'developer']

import re

target_string = "AITAM is the best college in AP"

result = re.split(r"\s", target_string, maxsplit=2)


print(result)

result = re.split(r"\s", target_string, maxsplit=3)


print(result)

['AITAM', 'is', 'the best college in AP']

['AITAM', 'is', 'the', 'best college in AP']

sub() function:

Python regex offers sub() the subn() methods to search and replace patterns in a string.
Using these methods we can replace one or more occurrences of a regex pattern in
the target string with a substitute string.

Syntax:
re.sub(pattern, replacement, string[, count, flags])

12
Python Programming UNIT - 6
• pattern: The regular expression pattern to find inside the target string.
• replacement: The replacement that we are going to insert for each occurrence of a
pattern. The replacement can be a string or function.
• string:The variable pointing to the target string (In which we want to perform the
replacement).
• count:
Maximum number of pattern occurrences to be replaced. The count must
always be a positive integer if specified. .By default, the count is set to zero, which
means the re.sub() method will replace all pattern occurrences in the target string.
• flags: Finally, the last argument is optional and refers to regex flags. By default, no
flags are applied. There are many flag values we can use. For example, the re.I is
used for performing case-insensitive searching and replacing.

import re

target_str = "AITAM is the best college in AP"


res_str = re.sub(r"\s", "_", target_str)
print(res_str)

AITAM_is_the_best_college_in_AP

import re

target_str = "AITAM is the best college in AP"

res_str = re.sub(r"\s", "#", target_str)


print(res_str)

res_str = re.sub(r"\s", "", target_str)


print(res_str)

AITAM#is#the#best#college#in#AP

AITAMisthebestcollegeinAP

13

You might also like