5.teaching Notes
5.teaching Notes
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 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)
5|
Introduction to Python| Unit- 1
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
7|
Introduction to Python| Unit- 1
Give the file a name and put the .py suffix on it.
8|
Introduction to Python| Unit- 1
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:
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.
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)
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.
12|
Introduction to Python| Unit- 1
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
14|
Introduction to Python| Unit- 1
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
as el if or yield
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. >>>
18|
Introduction to Python| Unit- 1
Python Operators
Last update on January 25 2017 11:39:04 (UTC/GMT +8 hours)
// Floor x// y The division of operands where the result is the quotient in which the digits
Division after the decimal point are removed.
19|
Introduction to Python| Unit- 1
> 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
20|
Introduction to Python| Unit- 1
Not (x not y) If a condition is true then Logical not operator will make false.
21|
Introduction to Python| Unit- 1
+= x+=y x=x+y Adds 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.
22|
Introduction to Python| Unit- 1
& And x&y Bits that are set in both x and 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]
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. ^
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
26|
Introduction to Python| Unit- 1
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
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
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!
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.
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
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()
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.
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
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
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
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
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
Left and right shifts of N bits are equivalent to multiplication and division by (2 **N) without
overflow checking.
>>> 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
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
>>>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
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.
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:
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
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
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
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)
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))
6
Python Programming II UNIT
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 strip() method removes any whitespace from the beginning or the end:
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"
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
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:
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
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.
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:
10
Python Programming II UNIT
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:
Append Items
To add an item to the end of the list, use the append() method:
Extend List
To append elements from another list to the current list, use the extend() method.
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']
12
Python Programming II UNIT
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']
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))
myTuple = ("apple",)
print(type(myTuple))
14
Python Programming II UNIT
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.
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:])
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)
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
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")
print(green)
print(tropic)
print(red)
apple
['mango', 'papaya', 'pineapple']
cherry
17
Python Programming II UNIT
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'}
type() From Python's perspective, sets are defined as objects with the data type 'set':
myset = {"apple", "banana", "cherry"}
print(type(myset))
<class 'set'>
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
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'}
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
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()
21
Python Programming II UNIT
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.
Dictionary Length
To determine how many items a dictionary has, use the len() function:
print(len(myDict))
3
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"
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}
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}}
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.
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
Example
def function():
print("IT is Best in AITAM")
Calling a Function
Example
def function(): # Function Definition
print("IT is Best in AITAM ")
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
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:
function("AITAM", "COLLEGE")
AITAM COLLEGE
Example 2
This function expects 3 arguments, and gets 3 arguments:
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)
3
Python Programming UNIT - III
Example 2
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
display()
display(10)
display(10, 20)
display(10, 20, 30)
display(10, 20, 30, 40)
4
Python Programming UNIT - III
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)
my_function(fruits)
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.
x = abs(-7.25)
x = bin(36)
x = complex(3, 5)
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.
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.)
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)
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]
#Output: 128
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.
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
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")
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.
Example-1
f = open("sample.txt", "r")
print(f.read(6))
#Output : Aditya
Example-2
f = open("sample.txt", "r")
print(f.readline())
10
Python Programming UNIT - III
Example-3
f = open("sample.txt", "r")
print(f.readline())
print(f.readline())
Example-4
f = open("sample.txt", "r")
print(f.readlines())
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)
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()
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.
f = open("sample.txt", "a")
f.write("Python is a general purpose programming language")
f.close()
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()
12
Python Programming UNIT - III
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()
f = open("myfile.txt", "x")
Delete a File
To delete a file, you must import the OS module, and run its os.remove() function:
Example
import os
os.remove("sample.txt")
13
Python Programming UNIT - III
To avoid getting an error, you might want to check if the file exists before you try to delete it:
import os
if os.path.exists("sample.txt"):
os.remove("sample.txt")
else:
print("The file does not exist")
Delete Folder
import os
os.rmdir("myfolder")
14
Python Programming Unit - 4
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.
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:
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
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
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
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
import mydata as md
a = md.person1["age"]
print(a)
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
# Output 2.23606797749979
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.
print(math.factorial(5))
print(random.randint(10, 20))
120
18
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.
4
Python Programming Unit - 4
# import only factorial function from math module
from math import factorial
print(factorial(5))
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.
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 *.
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)
There is a built-in function to list all the function names (or variable names) in a module.
The dir() function:
Example
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
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.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
math 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:
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
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']
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])
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
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
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
time module
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?
Code Reusability
Easier Debugging
12/1/2022
Class Fundamentals Object Fundamentals
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
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
12/1/2022 9
Python Classes/Objects
To create a class, use the Now we can use the class named
keyword class: MyClass to create objects
Example Example
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.
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
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.
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
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
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.
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.
12/1/2022 17
Python Classes/Objects
The __str__() Function:
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
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)
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
In single inheritance, a child class inherits from a single-parent class. Here is one child class
and one parent class.
12/1/2022 23
Python Inheritance - Single inheritance
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
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
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
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
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.
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
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:-
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.
12/1/2022 37
Python Database Connectivity
mycursor = mydb.cursor()
12/1/2022 39
Python Database Connectivity
mycursor.close()
Mydb.close()
12/1/2022 40
Python Database Connectivity
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
mycursor = mydb.cursor()
12/1/2022 41
Python Database Connectivity
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
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
import mysql.connector
mydb =
mysql.connector.connect( host="localhost", user="yourusername",
password="yourpassword", database="mydatabase”)
mycursor = mydb.cursor()
12/1/2022 45
Python Programming UNIT - 6
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
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.
2
Python Programming UNIT - 6
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
3
Python Programming UNIT - 6
Quantifier Meaning
Regex flags
All RE module methods accept an optional flags argument used to enable various unique
features and syntax variations.
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
output
AITAM
5
Python Programming UNIT - 6
import re
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
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.
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"
output:
Match Object <re.Match object; span=(10, 18), match='baseball'>
import re
# Target String
target_string = "Gita is a baseball player who was born on June 17, 1993."
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.
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
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)
output:
Found following matches
import re
output:
['AITAM', 'is', 'best', 'engineering', 'college', 'AITAM', 'is', 'located', 'in', 'tekkali']
['AITAM', 'AITAM']
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
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
['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
import re
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
AITAM_is_the_best_college_in_AP
import re
AITAM#is#the#best#college#in#AP
AITAMisthebestcollegeinAP
13