0% found this document useful (0 votes)
2 views

Python_Notes(B.Sc).docx

Python is a high-level, interpreted, interactive, and object-oriented programming language known for its readability and ease of learning. It features a broad standard library, supports various programming paradigms, and allows for interactive and script mode programming. Python uses indentation to define code blocks and has a variety of data types including numbers, strings, lists, tuples, and dictionaries.

Uploaded by

vixohon874
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python_Notes(B.Sc).docx

Python is a high-level, interpreted, interactive, and object-oriented programming language known for its readability and ease of learning. It features a broad standard library, supports various programming paradigms, and allows for interactive and script mode programming. Python uses indentation to define code blocks and has a variety of data types including numbers, strings, lists, tuples, and dictionaries.

Uploaded by

vixohon874
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

UNIT - I

Introduction to PYTHON: (introduced by Guido Van Rossum in early 80s)

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 - Basic Syntax


​ The Python language has many similarities to Perl, C, and Java. However, there are some definite differences
between the languages.

Interactive Mode Programming


Invoking the interpreter without passing a script file as a parameter brings up the following prompt −

$ 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!

Script Mode Programming


Invoking the interpreter with a script parameter begins execution of the script and continues until the script
is finished. When the script is finished, the interpreter is no longer active.

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.

Here are naming conventions for Python identifiers −


●​ Class names start with an uppercase letter. All other identifiers start with a lowercase letter.
●​ Starting an identifier with a single leading underscore indicates that the identifier is private.
●​ Starting an identifier with two leading underscores indicates a strongly private identifier.
●​ If the identifier also ends with two trailing underscores, the identifier is a language-defined special
name.

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.

and del for is raise


assert elif from lambda return
break else global not try
class except if or while
continue exec import pass with
def finally in print yield

Lines and Indentation


Python provides no braces to indicate blocks of code for class and function definitions or flow control. Blocks
of code are denoted by line indentation, which is rigidly enforced.
The number of spaces in the indentation is variable, but all statements within the block must be indented the
same amount. For example −
if True:
print "True"
else:
print "False"

However, the following block generates an error −

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 −

days = ['Monday', 'Tuesday', 'Wednesday','Thursday', 'Friday']

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

raw_input ("\n\n Press the enter key to exit.")

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.

Multiple Statements on a Single Line


The semicolon ( ; ) allows multiple statements on the single line given that neither statement starts a new
code block. Here is a sample snip using the semicolon −

import sys; x ='foo'; sys.stdout.write(x +'\n');

Multiple Statement Groups as Suites


A group of individual statements, which make a single code block are called suites in Python. Compound or
complex statements, such as if, while, def, and class require a header line and a suite.
Header lines begin the statement (with the keyword) and terminate with a colon ( : ) and are followed by one
or more lines which make up the suite. For example −
if expression :
Block of statements
elif expression :
Block of statements
else :
Block of statements
Command Line Arguments
Many programs can be run to provide you with some basic information about how they should be run.
Python enables you to do this with -h –

$ 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 using the input( ) function


A function is defined as a block of organized, reusable code used to perform a single, related action. Python
has many built-in functions; you can also create your own. Python has an input function which lets you ask a
user for some text input. You call this function to tell the program to stop and wait for the user to key in the
data. In Python 2, you have a built-in function raw_input(), whereas in Python 3, you have input().
The program will resume once the user presses the ENTER or RETURN key. Look at this example to get
input from the keyboard using Python 2 in the interactive mode. Your output is displayed in quotes once you
hit the ENTER key.

>>> 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.)

Output using the print() function


To output your data to the screen, use the print() function. You can write print(argument) and this will
print the argument in the next line when you press the ENTER key.

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.

Assigning Values to Variables


Python variables do not need explicit declaration to reserve memory space. The declaration happens
automatically when you assign a value to a variable. The equal sign (=) is used to assign values to 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

counter =100​ # An integer


assignment miles​ =1000.0# A
floating point
name​ ="John"# A string

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.

Standard Data Types


The data stored in memory can be of many types. For example, a person's age is stored as a numeric value
and his or her address is stored as alphanumeric characters. Python has various standard data types that are
used to define the operations possible on them and the storage method for each of them.

Python has five standard data types −

●​ 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 −

Syntax : del var1[,var2[,var3[.​ ,varN]]]]

You can delete a single object or multiple objects by using the del statement. For example −

del var
del var_a, var_b

Python supports four different numerical types −

●​ 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

int long float complex


10 51924361L 0.0 3.14j
100 -0x19323L 15.20 45.j
-786 0122L -21.9 9.322e-36j
080 0xDEFABCECBDAECBFBAEL 32.3+e18 .876j
-0490 535633629843L -90. -.6545+0J
-0x260 -052318172735L -32.54e100 3e+26J
0x69 -4721885298529L 70.2-E12 4.53e-7j

●​ 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.

Sr.No. Function & Returns ( description )


1 abs(x)
The absolute value of x: the (positive) distance between x and zero.
2 ceil(x)
The ceiling of x: the smallest integer not less than x
3 cmp(x, y)
-1 if x < y, 0 if x == y, or 1 if x > y
4 exp(x)
The exponential of x: ex
5 fabs(x)
The absolute value of x.
6 floor(x)
The floor of x: the largest integer not greater than x
7 log(x)
The natural logarithm of x, for x> 0
8 log10(x)
The base-10 logarithm of x for x> 0.
9 max(x1, x2,...)
The largest of its arguments: the value closest to positive infinity
10 min(x1, x2,...)
The smallest of its arguments: the value closest to negative infinity
11 modf(x)
The fractional and integer parts of x in a two-item tuple. Both parts have the same sign as x. The integer part
is returned as a float.
12 pow(x, y)
The value of x**y.
13 round(x [,n])
x rounded to n digits from the decimal point. Python rounds away from zero as a tie-breaker: round(0.5) is
1.0 and round(-0.5) is -1.0.
14 sqrt(x)
The square root of x for x > 0

Random Number Functions


Random numbers are used for games, simulations, testing, security, and privacy applications. Python includes
following functions that are commonly used.

Sr.No. Function & Description


1 choice(seq)
A random item from a list, tuple, or string.
2 randrange ([start,] stop [,step])
A randomly selected element from range(start, stop, step)
3 random()
A random float r, such that 0 is less than or equal to r and r is less than 1
4 seed([x])
Sets the integer starting value used in generating random numbers. Call this function before calling any
other random module function. Returns None.
5 shuffle(lst)
Randomizes the items of a list in place. Returns None.
6 uniform(x, y)
A random float r, such that x is less than or equal to r and r is less than y

Trigonometric Functions
Python includes following functions that perform trigonometric calculations.

Sr.No. Function & Description


1 acos(x)
Return the arc cosine of x, in radians.
2 asin(x)
Return the arc sine of x, in radians.
3 atan(x)
Return the arc tangent of x, in radians.
4 atan2(y, x)
Return atan(y / x), in radians.
5 cos(x)
Return the cosine of x radians.
6 hypot(x, y)
Return the Euclidean norm, sqrt(x*x + y*y).
7 sin(x)
Return the sine of x radians.
8 tan(x)
Return the tangent of x radians.
9 degrees(x)
Converts angle x from radians to degrees.
10 radians(x)
Converts angle x from degrees to radians.

Mathematical Constants
The module also defines two mathematical constants −

Sr.No. Constants & Description


1 pi
The mathematical constant pi.
2 e
The mathematical constant e.
Python - Strings
​ ​Strings are amongst the most popular types in Python. We can create them simply
by enclosing characters in quotes. Python treats single quotes the same as double quotes.
Creating strings is as simple as assigning a value to a variable. For example −
var1 = 'Hello World!'
var2 = "Python Programming"

Accessing Values in Strings


Python does not support a character type; these are treated as strings of length one, thus also considered a
substring.

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 = 'Hello World!'


var2 = "Python Programming"

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

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')

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


Updated String :-​ Hello 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

String Special Operators


Assume string variable a holds 'Hello' and variable b holds 'Python', then −

Operator Description Example


+ Concatenation - Adds values on either side of a + b will give HelloPython
the operator
* Repetition - Creates new strings, concatenating a*3 will give -HelloHelloHello
multiple copies of the same string
[] Slice - Gives the character from the given index a[1] will give e

[:] 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

String Formatting Operator


One of Python's coolest features is the string format operator %. This operator is unique to strings and makes
up for the pack of having functions from C's printf() family. Following is a simple example −

#!/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 −

My name is Zara and weight is 21 kg!

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

para_str = """this is a long string that is made up


of several lines and non-printable characters such
as
TAB ( \t ) and they will show up that way when
displayed. NEWLINEs within the string, whether
explicitly given like this within the brackets [ \n ],
or just a NEWLINE within the variable assignment will
also show up.
"""
print para_str

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) −

this is a long string that is made up of


several lines and non-printable characters such as
TAB ( ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given
like this within the brackets [
], or just a NEWLINE within
the variable assignment will also show up.

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'

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

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'

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

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

print (u'Hello, world!')

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

Hello, world!

As you can see, Unicode strings use the prefix u, just as raw strings use the prefix r.

Built-in String Methods


Python includes the following built-in methods to manipulate strings −

Sr.No. Methods with Description


1 capitalize()
Capitalizes first letter of string
2 center(width, fillchar)
Returns a space-padded string with the original string centered to a total of width columns.
3 count(str, beg= 0,end=len(string))
Counts how many times str occurs in string or in a substring of string if starting index beg and
ending index end are given.
4 decode(encoding='UTF-8',errors='strict')
Decodes the string using the codec registered for encoding. encoding defaults to the default string
encoding.
5 encode(encoding='UTF-8',errors='strict')
Returns encoded string version of string; on error, default is to raise a ValueError unless errors is
given with 'ignore' or 'replace'.
6 endswith(suffix, beg=0, end=len(string))
Determines if string or a substring of string (if starting index beg and ending index end are given)
ends with suffix; returns true if so and false otherwise.
7 expandtabs(tabsize=8)
Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not provided.
8 find(str, beg=0 end=len(string))
Determine if str occurs in string or in a substring of string if starting index beg and ending index
end are given returns index if found and -1 otherwise.
9 index(str, beg=0, end=len(string))
Same as find(), but raises an exception if str not found.
10 isalnum()
Returns true if string has at least 1 character and all characters are alphanumeric and false
otherwise.
11 isalpha()
Returns true if string has at least 1 character and all characters are alphabetic and false otherwise.
12 isdigit()
Returns true if string contains only digits and false otherwise.
13 islower()
Returns true if string has at least 1 cased character and all cased characters are in lowercase and
false otherwise.
14 isnumeric()
Returns true if a unicode string contains only numeric characters and false otherwise.
15 isspace()
Returns true if string contains only whitespace characters and false otherwise.
16 istitle()
Returns true if string is properly "titlecased" and false otherwise.
17 isupper()
Returns true if string has at least one cased character and all cased characters are in uppercase and
false otherwise.
18 join(seq)
Merges (concatenates) the string representations of elements in sequence seq into a string, with
separator string.
19 len(string)
Returns the length of the string
20 ljust(width[, fillchar])
Returns a space-padded string with the original string left-justified to a total of width columns.
21 lower()
Converts all uppercase letters in string to lowercase.
22 lstrip()
Removes all leading whitespace in string.
23 maketrans()
Returns a translation table to be used in translate function.
24 max(str)
Returns the max alphabetical character from the string str.
25 min(str)
Returns the min alphabetical character from the string str.
26 replace(old, new [, max])
Replaces all occurrences of old in string with new or at most max occurrences if max given.
27 rfind(str, beg=0,end=len(string))
Same as find(), but search backwards in string.
28 rindex( str, beg=0, end=len(string))
Same as index(), but search backwards in string.
29 rjust(width,[, fillchar])
Returns a space-padded string with the original string right-justified to a total of width columns.
30 rstrip()
Removes all trailing whitespace of string.
31 split(str="", num=string.count(str))
Splits string according to delimiter str (space if not provided) and returns list of substrings; split
into at most num substrings if given.
32 splitlines( num=string.count('\n'))
Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs removed.
33 startswith(str, beg=0,end=len(string))
Determines if string or a substring of string (if starting index beg and ending index end are given)
starts with substring str; returns true if so and false otherwise.
34 strip([chars])
Performs both lstrip() and rstrip() on string.
35 swapcase()
Inverts case for all letters in string.
36 title()
Returns "titlecased" version of string, that is, all words begin with uppercase and the rest are
lowercase.
37 translate(table, deletechars="")
Translates string according to translation table str(256 chars), removing those in the del string.
38 upper()
Converts lowercase letters in string to uppercase.
39 zfill (width)
Returns original string leftpadded with zeros to a total of width characters; intended for numbers,
zfill() retains any sign given (less one zero).
40 isdecimal()
Returns true if a unicode string contains only decimal characters and false otherwise.

Python - Basic Operators

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

Let us have a look on all operators one by one.

Python Arithmetic Operators


Assume variable a holds 10 and variable b holds 20, then −

Operator Description Example


+ Addition Adds values on either side of the operator. a + b = 30
- Subtraction Subtracts right hand operand from left hand a – b = -10
operand.
* Multiplies values on either side of the a * b = 200
Multiplication operator
/ Division Divides left hand operand by right hand b/a=2
operand
% Modulus Divides left hand operand by right hand b%a=0
operand and returns remainder
** Exponent Performs exponential (power) calculation on a**b =10 to the power 20
operators
// Floor Division - The division of operands 9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4, -
where the result is the quotient in which the 11.0//3 = -4.0
digits after the decimal point are removed.
But if one of the operands is negative, the
result is floored, i.e., rounded away from
zero (towards negative infinity) −

Python Comparison Operators


These operators compare the values on either sides of them and decide the relation among them. They are
also called Relational operators.

Assume variable a holds 10 and variable b holds 20, then −

Operator Description Example


== If the values of two operands are equal, then (a == b) is not true.
the condition becomes true.
!= If values of two operands are not equal, then (a != b) is true.
condition becomes true.
<> If values of two operands are not equal, then (a <> b) is true. This is similar to != operator.
condition becomes true.
> If the value of left operand is greater than the (a > b) is not true.
value​ of​ right​ operand,​ then​ condition
becomes true.
< If the value of left operand is less than the (a < b) is true.
value of right operand, then condition
becomes true.
>= If the value of left operand is greater than or (a >= b) is not true.
equal to the value of right operand, then
condition becomes true.
<= If the value of left operand is less than or (a <= b) is true.
equal to the value of right operand, then
condition becomes true.

Python Assignment Operators


Assume variable a holds 10 and variable b holds 20, then −

Operator Description Example


= Assigns values from right side operands to left c = a + b assigns value of a + b into c
side operand
+=​ It adds right operand to the left operand and c += a is equivalent to c = c + a
Add assign the result to left operand
AND
-= It subtracts right operand from the left c -= a is equivalent to c = c - a
Subtrac operand and assign the result to left operand
t AND
*= It multiplies right operand with the left c *= a is equivalent to c = c * a
Multipl operand and assign the result to left operand
y AND
/= Divide It divides left operand with the right operand c /= a is equivalent to c = c / ac /= a is
AND and assign the result to left operand equivalent to c = c / a
%= It takes modulus using two operands and c %= a is equivalent to c = c % a
Modulus assign the result to left operand
AND
**= Performs exponential (power) calculation on c **= a is equivalent to c = c ** a
Exponen operators and assign value to the left operand
t AND
//= Floor It performs floor division on operators and c //= a is equivalent to c = c // a
Division assign value to the left operand

Python Bitwise Operators


Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b = 13; Now in binary
format they will be as follows −

a = 0011 1100

b = 0000 1101

a&b = 0000 1100


a|b = 0011 1101
a^b = 0011 0001

~a = 1100 0011

There are following Bitwise operators supported by Python language

Operator Description Example


&​ Binary Operator copies a bit to the result if it exists (a & b) (means 0000 1100)
AND in both operands
| Binary OR It copies a bit if it exists in either operand. (a | b) = 61 (means 0011 1101)
^​ Binary It copies the bit if it is set in one operand but (a ^ b) = 49 (means 0011 0001)
XOR not both.
~​ Binary It is unary and has the effect of 'flipping' bits.
(~a ) = -61 (means 1100 0011 in 2's
Ones complement form due to a signed binary
Complement number.
<<​ Binary The left operands value is moved left by the a << 2 = 240 (means 1111 0000)
Left Shift number of bits specified by the right
operand.
>>​ Binary The left operands value is moved right by a >> 2 = 15 (means 0000 1111)
Right Shift the number of bits specified by the right
operand.

Python Logical Operators


There are following logical operators supported by Python language. Assume variable a holds 10 and variable b
holds 20 then

Used to reverse the logical state of its operand.

Python Membership Operators


Python’s membership operators test for membership in a sequence, such as strings, lists, or tuples. There are
two membership operators as explained below −

Operator Description Example


in Evaluates to true if it finds a variable in the x in y, here in results in a 1 if x is a member of
specified sequence and false otherwise. sequence y.
not in Evaluates to true if it does not finds a variable x not in y, here not in results in a 1 if x is not a
in the specified sequence and false otherwise. member of sequence y.

Python Identity Operators


Identity operators compare the memory locations of two objects. There are two Identity operators explained
below −

Operator Description Example


is Evaluates to true if the variables on either side x is y, here is results in 1 if id(x) equals id(y).
of the operator point to the same object and
false otherwise.
is not Evaluates to false if the variables on either side x is not y, here is not results in 1 if id(x) is not
of the operator point to the same object and equal to id(y).
true otherwise.
Python Operators Precedence
The following table lists all operators from highest precedence to lowest.

Sr.No. Operator & Description


1 **
Exponentiation (raise to the power)
2 ~+-
Complement, unary plus and minus (method names for the last two are +@ and -@)
3 * / % //
Multiply, divide, modulo and floor division
4 +-
Addition and subtraction
5 >><<
Right and left bitwise shift
6 &
Bitwise 'AND'
7 ^|
Bitwise exclusive `OR' and regular `OR'
8 <= <>>=
Comparison operators
9 <> == !=
Equality operators
10 = %= /= //= -= += *= **=
Assignment operators
11 is is not
Identity operators
12 in not in
Membership operators
13 not or and
Logical operators

Literals

Python Literals

Literals can be defined as a data that is given in a variable or constant.

Python support the following 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:

There are two types of Strings supported in Python:

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.

There are two ways to create Multiline Strings:

1).​Adding black slash at the end of each line.

Eg:
1.​ >>> text1='hello\
2.​ user'
3.​ >>> text1
4.​ 'hellouser'
5.​ >>>
2).Using triple quotation marks:-

Eg:

1.​ >>> str2='''''welcome


2.​ to
3.​ SSSIT'''
4.​ >>> print str2
5.​ welcome
6.​ to
7.​ SSSIT
8.​ >>>

II.​ Numeric literals:

Numeric Literals are immutable. Numeric literals can belong to following four different numerical types.

Int(signed integers) Long(long integers) float(floating point) Complex(complex)


Numbers( can be both Integers of unlimited size Real numbers with In the form of a+bj where a forms the
positive and negative) followed by lowercase or both integer and real part and b forms the imaginary
with no fractional uppercase L eg: fractional part eg: - part of complex number. eg: 3.14j
part.eg: 100 87032845L 26.2

III.​Boolean literals:

A Boolean literal can have any of the two values: True or False.

IV.​ Special literals.


Python contains one special literal i.e., None.
None is used to specify to that field that is not created. It is also used for end of lists in Python.

Eg: 1.​ >>> val1=10


2.​ >>> val2=None
3.​ >>> val1
4.​ 10
5.​ >>> val2
6.​ >>> print val2
7.​ None
8.​ >>>
V.​Literal Collections.

Collections such as tuples, lists and Dictionary are used in Python.

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 - Decision Making


Decision making is anticipation of conditions occurring while execution of the program and
specifying actions taken according to the conditions.
Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome.
You need to determine which action to take and which statements to execute if outcome is
TRUE or FALSE otherwise.
Following is the general form of a typical decision making structure found in most of the
programming languages –
Python programming language assumes any non-zero and non-null values as TRUE, and if
it is either zero or null, then it is assumed as FALSE value.

Python programming language provides following types of decision making statements. Click
the following links to check their detail.

Sr.No. Statement & Description

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

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

3 nested if statements
You can use one if or else if statement inside another if or else
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 −

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

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

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

if...else statements

An else statement can be combined with an if statement. An else statement


contains the block of code that executes if the conditional expression in the if
statement resolves to 0 or a FALSE value.
The else statement is an optional statement and there could be at most only one
else statement following if.
Syntax : The syntax of the if...else statement is −
Flow Diagram

Example

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

The elif Statement


The elif statement allows you to check multiple expressions for TRUE and execute a
block of code as soon as one of the conditions evaluates to TRUE.
Similar to the else, the elif statement is optional. However, unlike else, for which
there can be at most one statement, there can be an arbitrary number ofelif
statements following an if.
syntax
Core Python does not provide switch or case statements as in other languages, but
we can use if..elif...statements to simulate switch case as follows −
Example

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

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.

Syntax:The syntax of the nested if...elif...else construct may be −


Example

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

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 −

Python programming language provides following types of loops to handle looping


requirements.

Sr.No. Loop Type & Description

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.

Loop Control Statements


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

Sr.No. Control Statement & Description

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

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

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.

Let us go through the loop control statements briefly

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 −

Here, statement(s) may be a single statement or a block of statements.


Thecondition 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.
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

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

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.

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

Single Statement Suites


Similar to the if statement syntax, if your while clause consists only of a single
statement, it may be placed on the same line as the while header.
Here is the syntax and example of a one-line while clause −

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

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

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 –
When the above code is executed, it produces the following result −

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.

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

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 −

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

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

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

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

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


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. 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

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


Python Programming.
SAQ’s
UNIT – I

1.​ Briefly explain about Python programming.


2.​ Explain the Structure of Python program.
3.​ Write short notes on Input and Output Statements.
4.​ Write short notes on python numbers.
5.​ Discuss about Python Literals.
6.​ Explain Comments in python programming.
UNIT – II

1.​ Write a short note on Control flow statements.


2.​ Write a short note to demonstrate break, continue and pass statements.
3.​ Define Functions.
4.​ Explain Anonymous functions in python programming.
5.​ Explain call by value and call by reference.
UNIT – III
LAQ’s

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.

You might also like