Python_Notes(B.Sc).docx
Python_Notes(B.Sc).docx
Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to
be highly readable. It uses English keywords frequently where as other languages use punctuation, and it has
fewer syntactical constructions than other languages.
● Python is Interpreted − Python is processed at runtime by the interpreter. You do not need to
compile your program before executing it. This is similar to PERL and PHP.
● Python is Interactive − You can actually sit at a Python prompt and interact with the interpreter
directly to write your programs.
● Python is Object-Oriented − Python supports Object-Oriented style or technique of programming
that encapsulates code within objects.
● Python is a Beginner's Language − Python is a great language for the beginner-level programmers
and supports the development of a wide range of applications from simple text processing to WWW
browsers to games.
Python Features
Python's features include −
● Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax. This
allows the student to pick up the language quickly.
● Easy-to-read − Python code is more clearly defined and visible to the eyes.
● Easy-to-maintain − Python's source code is fairly easy-to-maintain.
● A broad standard library − Python's bulk of the library is very portable and cross-platform
compatible on UNIX, Windows, and Macintosh.
● Interactive Mode − Python has support for an interactive mode which allows interactive testing and
debugging of snippets of code.
● Portable − Python can run on a wide variety of hardware platforms and has the same interface on all
platforms.
● Extendable − You can add low-level modules to the Python interpreter. These modules enable
programmers to add to or customize their tools to be more efficient.
● Databases − Python provides interfaces to all major commercial databases.
● GUI Programming − Python supports GUI applications that can be created and ported to many
system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X Window
system of Unix.
● Scalable − Python provides a better structure and support for large programs than shell scripting.
● It supports functional and structured programming methods as well as OOP.
● It can be used as a scripting language or can be compiled to byte-code for building large applications.
● It provides very high-level dynamic data types and supports dynamic type checking.
● IT supports automatic garbage collection.
● It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
$ python
2.4.3(#1,Nov112010,13:34:43)
GCC 4.1.220080704(RedHat4.1.2-48)] on linux2
Type"help","copyright","credits"or"license"for more information.
>>>
Type the following text at the Python prompt and press the Enter −
>>>print"Hello,Python!" #valid
in python 2 and invalid in python 3
If you are running new version of Python, then you would need to use print statement with parenthesis as in
print ("Hello, Python!");. However in Python version 2.4.3, this produces the following result −
Hello, Python!
Let us write a simple Python program in a script. Python files have extension .py. Type the following source
code in a test.py file −
print"Hello, Python!"
We assume that you have Python interpreter set in PATH variable. Now, try to run this program as follows −
$ python test.py
This produces the following result −
Hello, Python!
Let us try another way to execute a Python script. Here is the modified test.py file −
#!/usr/bin/python
print"Hello, Python!"
We assume that you have Python interpreter available in /usr/bin directory. Now, try to run this program as
follows −
$ chmod +x test.py # This is to make file executable
$./test.py
This produces the following result −
Hello, Python!
Python Identifiers
A Python identifier is a name used to identify a variable, function, class, module or other object. An
identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters,
underscores and digits (0 to 9).
Python does not allow punctuation characters such as @, $, and % within identifiers. Python is a case
sensitive programming language. Thus, Manpower and manpower are two different identifiers in Python.
Reserved Words
The following list shows the Python keywords. These are reserved words and you cannot use them as constant
or variable or any other identifier names. All the Python keywords contain lowercase letters only.
ifTrue:
print"Answer"
print"True"
else:
print"Answer"
print"False"
Thus, in Python all the continuous lines indented with same number of spaces would form a block. The
following example has various statement blocks −
Multi-Line Statements
Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation
character (\) to denote that the line should continue. For example −
total = item_one + \
item_two + \
item_three
Statements contained within the [], {}, or () brackets do not need to use the line continuation character. For
example −
Quotation in Python
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as the same
type of quote starts and ends the string.
The triple quotes are used to span the string across multiple lines. For example, all the following are legal −
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and
sentences."""
Comments in Python
A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to the
end of the physical line are part of the comment and the Python interpreter ignores them.
#!/usr/bin/python
# First comment
print"Hello, Python!"# second comment
This produces the following result −
Hello, Python!
You can type a comment on the same line after a statement or expression −
name = "St.Joseph’s" # This is again comment
You can comment multiple lines as follows −
# This is a comment.
# This is a comment,
too. # This is a
comment, too. # I said
that already.
Using Blank Lines
A line containing only whitespace, possibly with a comment, is known as a blank line and Python totally
ignores it.
In an interactive interpreter session, you must enter an empty physical line to terminate a multiline
statement.
Waiting for the User
The following line of the program displays the prompt, the statement saying “Press the enter key to exit”,
and waits for the user to take action −
#!/usr/bin/python
var = input ()
Here, "\n\n" is used to create two new lines before displaying the actual line. Once the user presses the key,
the program ends. This is a nice trick to keep a console window open until the user is done with an
application.
$ python -h
usage: python [option]...[-c cmd |-m mod | file |-][arg]...
Options and arguments (and corresponding environment variables):
-c cmd : program passed in as string(terminates option list)
-d : debug output from parser (also PYTHONDEBUG=x)
-E : ignore environment variables (such as PYTHONPATH)
-h :print this help message and
exit [ etc.]
>>> input()
I am learning at St.Joseph’s #(This is where you type in)
Output:
'I am learning at St.Joseph’s' #(The interpreter showing you how the input is
captured.)
Definitions to remember: An argument is a value you pass to a function when calling it. A value is a letter
or a number. A variable is a name that refers to a value. It begins with a letter. An assignment statement
creates new variables and gives them values.
This syntax is valid in both Python 3.x and Python 2.x. For example, if your data is "Guido," you can put
"Guido" inside the parentheses ( ) after print.
>>>print("Guido")
Guido
Python - Variable
Variables are nothing but reserved memory locations to store values. This means that when you create a
variable you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the
reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals
or characters in these variables.
The operand to the left of the = operator is the name of the variable and the operand to the right of the =
operator is the value stored in the variable. For example −
#!/usr/bin/python
print (counter)
print (miles)
print (name)
Here, 100, 1000.0 and "John" are the values assigned to counter, miles, and name variables, respectively.
This produces the following result −
100
1000.0
John
Multiple Assignment
Python allows you to assign a single value to several variables simultaneously. For example −
a = b = c = 1
Here, an integer object is created with the value 1, and all three variables are assigned to the same memory
location. You can also assign multiple objects to multiple variables. For example −
a,b,c = 1,2,"john"
Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one string
object with the value "john" is assigned to the variable c.
● Numbers
● String
● List
● Tuple
● Dictionary
Python - Numbers
Number data types store numeric values. They are immutable data types, means that changing the value of a
number data type results in a newly allocated object.
Number objects are created when you assign a value to them. For example −
var1 = 1
var2 = 10
You can also delete the reference to a number object by using the del statement. The syntax of the del
statement is −
You can delete a single object or multiple objects by using the del statement. For example −
del var
del var_a, var_b
● int (signed integers) − They are often called just integers or ints, are positive or negative whole
numbers with no decimal point.
● long (long integers ) − Also called longs, they are integers of unlimited size, written like integers
and followed by an uppercase or lowercase L.
● float (floating point real values) − Also called floats, they represent real numbers and are written
with a decimal point dividing the integer and fractional parts. Floats may also be in scientific
notation, with E or e indicating the power of 10 (2.5e2 = 2.5 x 102 = 250).
● complex (complex numbers) − are of the form a + bJ, where a and b are floats and J (or j)
represents the square root of -1 (which is an imaginary number). The real part of the number is a, and
the imaginary part is b. Complex numbers are not used much in Python programming.
Examples
Here are some examples of numbers
● Python allows you to use a lowercase L with long, but it is recommended that you use only an
uppercase L to avoid confusion with the number 1. Python displays long integers with an uppercase
L.
● A complex number consists of an ordered pair of real floating point numbers denoted by a + bj,
where a is the real part and b is the imaginary part of the complex number.
Number Type Conversion
Python converts numbers internally in an expression containing mixed types to a common type for
evaluation. But sometimes, you need to coerce a number explicitly from one type to another to satisfy the
requirements of an operator or function parameter.
● Type int(x) to convert x to a plain integer.
● Type long(x) to convert x to a long integer.
● Type float(x) to convert x to a floating-point number.
● Type complex(x) to convert x to a complex number with real part x and imaginary part zero.
● Type complex(x, y) to convert x and y to a complex number with real part x and imaginary part y. x
and y are numeric expressions
Mathematical Functions
Python includes following functions that perform mathematical calculations.
Trigonometric Functions
Python includes following functions that perform trigonometric calculations.
Mathematical Constants
The module also defines two mathematical constants −
To access substrings, use the square brackets for slicing along with the index or indices to obtain your
substring. For example −
#!/usr/bin/python
var1[0]: H
var2[1:5]: ytho
Updating Strings
You can "update" an existing string by (re)assigning a variable to another string. The new value can be related to
its previous value or to a completely different string altogether. For example −
#!/usr/bin/python
var1 = 'Hello
World!'
print ("Updated String :- ", var1[:6] + 'Python')
Escape Characters
Following table is a list of escape or non-printable characters that can be represented with backslash notation.
An escape character gets interpreted; in a single quoted as well as double quoted strings.
Backslash Hexadecimal
“Description”
notation character
\a 0x07 Bell or alert
\b 0x08 Backspace
\cx Control-x
\C-x Control-x
\e 0x1b Escape
\f 0x0c Formfeed
\M-\C-x Meta-Control-x
\n 0x0a Newline
\nnn Octal notation, where n is in the range 0.7
\r 0x0d Carriage return
\s 0x20 Space
\t 0x09 Tab
\v 0x0b Vertical tab
\x Character x
\xnn Hexadecimal notation, where n is in the range 0.9, a.f, or
A.F
[:] Range Slice - Gives the characters from the a[1:4] will give ell
given range
in Membership - Returns true if a character exists H in a will give 1
in the given string
not in Membership - Returns true if a character does M not in a will give 1
not exist in the given string
r/R Raw String - Suppresses actual meaning of print r'\n' prints \n and print R'\n'prints \n
Escape characters. The syntax for raw strings
is exactly the same as for normal strings with
the exception of the raw string operator, the
letter "r," which precedes the quotation marks.
The "r" can be lowercase (r) or uppercase (R)
and must be placed immediately preceding the
first quote mark.
% Format - Performs String formatting See at next section
#!/usr/bin/python
print ("My name is %s and weight is %d kg!") % ('Zara', 21))
When the above code is executed, it produces the following result −
Here is the list of complete set of symbols which can be used along with % −
Format Symbol Conversion
%c character
%s string conversion via str() prior to formatting
%i signed decimal integer
%d signed decimal integer
%u unsigned decimal integer
%o octal integer
%x hexadecimal integer (lowercase letters)
%X hexadecimal integer (UPPERcase letters)
%e exponential notation (with lowercase 'e')
%E exponential notation (with UPPERcase 'E')
%f floating point real number
%g the shorter of %f and %e
%G the shorter of %f and %E
Other supported symbols and functionality are listed in the following table −
Symbol Functionality
* argument specifies width or precision
- left justification
+ display the sign
<sp> leave a blank space before a positive number
# add the octal leading zero ( '0' ) or hexadecimal leading '0x' or '0X',
depending on whether 'x' or 'X' were used.
0 pad from left with zeros (instead of spaces)
% '%%' leaves you with a single literal '%'
(var) mapping variable (dictionary arguments)
m.n. m is the minimum total width and n is the number of digits to display after
the decimal point (if appl.)
Triple Quotes
Python's triple quotes comes to the rescue by allowing strings to span multiple lines, including verbatim
NEWLINEs, TABs, and any other special characters.
The syntax for triple quotes consists of three consecutive single or double quotes.
#!/usr/bin/python
When the above code is executed, it produces the following result. Note how every single special character
has been converted to its printed form, right down to the last NEWLINE at the end of the string between the
"up." and closing triple quotes. Also note that NEWLINEs occur either with an explicit carriage return at the
end of a line or its escape code (\n) −
Raw strings do not treat the backslash as a special character at all. Every character you put into a raw string
stays the way you wrote it −
#!/usr/bin/python
print 'C:\\nowhere'
C:\nowhere
Now let's make use of raw string. We would put expression in r'expression' as follows −
#!/usr/bin/python
print r'C:\\nowhere'
C:\\nowhere
Unicode String
Normal strings in Python are stored internally as 8-bit ASCII, while Unicode strings are stored as 16-bit
Unicode. This allows for a more varied set of characters, including special characters from most languages in
the world. I'll restrict my treatment of Unicode strings to the following −
#!/usr/bin/python
Hello, world!
As you can see, Unicode strings use the prefix u, just as raw strings use the prefix r.
Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator.
Types of Operator
Python language supports the following types of operators.
● Arithmetic Operators
● Comparison (Relational) Operators
● Assignment Operators
● Logical Operators
● Bitwise Operators
● Membership Operators
● Identity Operators
a = 0011 1100
b = 0000 1101
~a = 1100 0011
Literals
Python Literals
I.String literals:
String literals can be formed by enclosing a text in the quotes. We can use both single as well as double quotes
for a String.
Eg:"Aman" , '12345'
Types of Strings:
a).Single line String- Strings that are terminated within a single line are known as Single line Strings.
Eg:>>> text1='hello'
b).Multi line String- A piece of text that is spread along multiple lines is known as Multiple line String.
Eg:
1. >>> text1='hello\
2. user'
3. >>> text1
4. 'hellouser'
5. >>>
2).Using triple quotation marks:-
Eg:
Numeric Literals are immutable. Numeric literals can belong to following four different numerical types.
III.Boolean literals:
A Boolean literal can have any of the two values: True or False.
List:
● List contain items of different data types. Lists are mutable i.e., modifiable.
● The values stored in List are separated by commas(,) and enclosed within a square brackets([]). We can store
different type of data in a List.
● Value stored in a List can be retrieved using the slice operator([] and [:]).
● The plus sign (+) is the list concatenation and asterisk(*) is the repetition operator.
Eg:
1. >>> list=['aman',678,20.4,'saurav']
2. >>> list1=[456,'rahul']
3. >>> list
4. ['aman', 678, 20.4, 'saurav']
5. >>> list[1:3]
6. [678, 20.4]
7. >>> list+list1
8. ['aman', 678, 20.4, 'saurav', 456, 'rahul']
9. >>> list1*2
10.[456, 'rahul', 456, 'rahul']
11.>>>
Python programming language provides following types of decision making statements. Click
the following links to check their detail.
1 if statements
An if statement consists of a boolean expression followed by one or
more statements.
2 if...else statements
An if statement can be followed by an optional else statement,
which executes when the boolean expression is FALSE.
3 nested if statements
You can use one if or else if statement inside another if or else
ifstatement(s).
Let us go through each decision making briefly −
Single Statement Suites
If the suite of an if clause consists only of a single line, it may go on the same line as the header
statement.
Here is an example of a one-line if clause −
if statements
It is similar to that of other languages. The if statement contains a logical expression using
which data is compared and a decision is made based on the result of the comparison.
Syntax :
If the boolean expression evaluates to TRUE, then the block of statement(s) inside the if
statement is executed. If boolean expression evaluates to FALSE, then the first set of code
after the end of the if statement(s) is executed.
Flow Diagram
Example
if...else statements
Example
nested if statements
There may be a situation when you want to check for another condition after a condition
resolves to true. In such a situation, you can use the nested ifconstruct.
In a nested if construct, you can have an if...elif...else construct
inside anotherif...elif...else construct.
Python - Loops
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.
Programming languages provide various control structures that allow for more
complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple
times. The following diagram illustrates a loop statement −
1 while loop
Repeats a statement or group of statements while a given condition is TRUE. It
tests the condition before executing the loop body.
2 for loop
Executes a sequence of statements multiple times and abbreviates the code that
manages the loop variable.
3 nested loops
You can use one or more loop inside any another while, for or do..while loop.
1 break statement
Terminates the loop statement and transfers execution to the statement
immediately following the loop.
2 continue statement
Causes the loop to skip the remainder of its body and immediately retest
its condition prior to reiterating.
3 pass statement
The pass statement in Python is used when a statement is required
syntactically but you do not want any command or code to execute.
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 −
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
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.
When the above code is executed, it produces the following result −
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 else statement is executed when the
loop has exhausted iterating the list.
● If the else statement is used with a while loop, the else statement 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.
It is better not try above example because it goes into infinite loop and you need to
press CTRL+C keys to exit.
for Loop Statements
It has the ability to iterate over the items of any sequence, such as a list or a string.
Syntax
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
Here, we took the assistance of the len() built-in function, which 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 else statement is executed when the
loop has exhausted iterating the list.
● If the else statement is used with a while loop, the else statement 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.
nested loops :
Python programming language allows to use one loop inside another loop. Following
section shows few examples to illustrate the concept.
Syntax
The syntax for a nested while loop statement in Python programming language is
as follows −
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 −
break statement
It terminates the current loop and resumes execution at the next statement, just like
the traditional break statement in C.
The most common use for break is when some external condition is triggered
requiring a hasty exit from a loop. The break statement can be used in bothwhile
and for loops.
If you are using nested loops, the break statement stops the execution of the
innermost loop and start executing the next line of code after the block.
Syntax :The syntax for a break statement in Python is as follows −
Flow Diagram
Example
continue statement
It returns the control to the beginning of the while loop.. The continuestatement
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 for loops.
Syntax
Flow Diagram
Example
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. Thepass
is also useful in places where your code will eventually go, but has not been written
yet (e.g., in stubs for example) −
Syntax
Example
Unit – I
1. What is Python Programming? Explain the features of Python Programming.
2. Give the Steps for Installing Python.
3. Briefly explain about Strings in Python programming.
4. Define Operators and explain any five Operators with syntax and examples.
5. Explain briefly about Lists. Write about basic functions & methods used in lists.
6. Explain briefly about Tuples. Write about basic functions & methods used in Tuples.
7. Explain briefly about Dictionaries. Write about basic functions & methods used in Dictionaries.
Unit – II
1. Explain Conditional statements in python (if, if-else, elif, nested if).
2. Explain Looping statements in python (while, for & while – else, for - else).
3. Define Functions. Explain about Built-in functions with a syntax and example.
4. What is Function? Explain User defined functions of Python Programming.