Python Unit I PDF
Python Unit I PDF
The most important thing in the programming language is the name. A language will not
succeed without a good name. I have recently invented a very good name and now I am
looking for a suitable language. — Donald Knuth
INTRODUCTION TO PYTHON
Python is a popular programming language
Created by Guido van Rossum and first released in 1991
Focus on readability and productivity
Python is a general-purpose interpreted
Interactive
High-level programming language
Strongly typed and dynamically typed
Automatic Memory Management
Supports multiple programming paradigms, including object-oriented, imperative,
functional and procedural
FEATURES
Batteries Included
Everything is an object
Interactive Shell
Strong Introspection
Cross Platform
Dynamic Typing
Easy-to-learn
Easy-to-read
Easy-to-maintain
A broad standard library
Interactive Mode
Portable
Extendable
Databases
GUI Programming
Scalable
USES
Web Development (Server-Side)
Mathematics
Embedded Scripting Language
3D Software
GUI Based Desktop Applications
Image Processing and Graphic Design Applications
Scientific and Computational Applications
Games
Enterprises and Business Applications
Operating Systems
Language Development
Prototyping
Network Programming
BitTorrent, YouTube, DropBox, Deluge, Cinema 4D, and Bazaar are a few globally-used
applications based on Python
RELEASES
Created in 1989 by Guido Van Rossum
Python 1.0 released in 1994
Python 2.0 released in 2000
Python 3.0 released in 2008
Python 2.7 is the recommended version in 2010
Python 3.5 released in 2015
LIMITATIONS OF PYTHON
Parallel Processing can be done in Python but not as elegantly as done in some other
languages (like Java Script and Go Lang)
Being on interpreted language, Python is slow as compared to C/C++. So, Python is
not a good choice for those developing a high-graphic 3d games that takes a lot of
CPU
As of now, there are few users of Python as compared to C/C++ or JAVA
Lacks of true Multiprocessor Support
Has very limited commercial support point
Python is slower than C/C++ when it comes to computation of heavy tasks and
desktop applications
It is difficult to pack up a big Python application into a single executable file. This
makes it difficult to distribute Python to non-technical users.
PYTHON INTERPRETER
Python is available on a wide variety of platforms including Windows, Linux and Mac OS
X.
Getting Python
The most up-to-date and current source code, binaries, documentation, news, etc., is
available on the official website of Python [Link]
Installing Python
Python distribution is available for a wide variety of platforms. You need to download only
the binary code applicable for your platform and install Python.
o Unix and Linux Installation
Here are the simple steps to install Python on Unix/Linux machine.
Open a Web browser and go to [Link]
Follow the link to download zipped source code available for Unix/Linux.
Download and extract files.
Editing the Modules/Setup file if you want to customize some options.
run ./configure script
make
make install
This installs Python at standard location /usr/local/bin and its libraries at
/usr/local/lib/pythonXX where XX is the version of Python.
o Windows Installation
Here are the steps to install Python on Windows machine.
Open a Web browser and go to [Link]
Follow the link for the Windows installer [Link] file where XYZ is the
version you need to install.
To use this installer [Link], the Windows system must support Microsoft
Installer 2.0. Save the installer file to your local machine and then run it to find out if
your machine supports MSI.
Run the downloaded file. This brings up the Python install wizard, which is really
easy to use. Just accept the default settings, wait until the install is finished, and you
are done.
o Macintosh Installation
Recent Macs come with Python installed, but it may be several years out of date. See
[Link]
Setting up PATH
The path is stored in an environment variable, which is a named string maintained by the
operating system. This variable contains information available to the command shell and
other programs.
The path variable is named as PATH in Unix or Path in Windows (Unix is case sensitive;
Windows is not).
Variable Description
PYTHONPATH It has a role similar to PATH. This variable tells the Python
interpreter where to locate the module files imported into a program.
It should include the Python source library directory and the
directories containing Python source code. PYTHONPATH is
sometimes preset by the Python installer.
PYTHONSTARTUP It contains the path of an initialization file containing Python source
code. It is executed every time you start the interpreter. It is named
as .[Link] in Unix and it contains commands that load utilities
or modify PYTHONPATH.
PYTHONCASEOK It is used in Windows to instruct Python to find the first case-
insensitive match in an import statement. Set this variable to any
value to activate it.
PYTHONHOME It is an alternative module search path. It is usually embedded in the
PYTHONSTARTUP or PYTHONPATH directories to make
switching module libraries easy.
Running Python
There are three different ways to start Python –
Interactive Interpreter
You can start Python from Unix, DOS, or any other system that provides you a command-
line interpreter or shell window.
Enter python the command line.
Start coding right away in the interactive interpreter.
$python # Unix/Linux
or
python% # Unix/Linux
or
C:> python # Windows/DOS
>>> 50 - 5*6
20
Division (/) always returns a float. To do floor division and get an integer result (discarding
any fractional result) you can use the // operator; to calculate the remainder you can use %
The equal sign (=) is used to assign a value to a variable. Afterwards, no result is displayed
before the next interactive prompt:
>>> width = 20
>>> height = 5 * 9
>>> width * height
900
In interactive mode, the last printed expression is assigned to the variable _. This means that
when you are using Python as a desk calculator, it is somewhat easier to continue
calculations.
For example:
>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06
PYTHON SYNTAX
Python syntax can be executed by writing directly in the Command Line.
Python Indentations
Where in other programming languages the indentation in code is for readability only, in
Python the indentation is very important.
Python provides no braces to indicate blocks of code for class and function definitions or
flow control.
Whitespace at the beginning of the line is called indentation.
All statements inside a block should be at the same indentation level.
Example:
if 5 > 2:
print("Five is greater than two!")
Output:
Example
if 5 > 2:
print("Five is greater than two!")
Note: ^ is a standard symbol that indicates where error has occurred in the program.
Comments in Python
Python has commenting capability for the purpose of in-code documentation.
Comments in Python start with the hash character, #, and extend to the end of the physical
line.
Example:
#This is a comment.
print("Hello, World!")
Inline Comments: You can type a comment on the same line after a statement or expression–
name = "Madisetti" # This is again comment
Examples:
"""
This type of comment spans multiple lines.
These are mostly used for documentation of functions, classes and modules.
"""
Examples:
# this is the first comment
spam = 1 # and this is the second comment
# ... and now a third!
text = "# This is not a comment because it's inside quotes."
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']
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."""
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.
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.
Examples of valid identifier are:
Sum, _my_var, num1, r, var_20, First
Examples of invalid identifier are:
1num, my-var, %check, Basic Sal, H#R&A
Reserved Words
Python keywords 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 exec not
assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield
SEMANTICS
Assigning or Initializing values to variables
In Python, programmers need not explicitly declare variables to reserve memory space.
The declaration is done automatically when a value is assigned to the variable using the equal
sign(=).
The operand on the left side of equal sign is the name of the variable and the operand on its
right side is the value to be stored in that variable.
Example: Program to display data of different types using variables and literal constants.
num = 7
amt = 123.45
code = 'A'
pi = 3.1415926536
population_of_india = 1000000000
msg = "hi"
In Python, you can reassign variables as many times as you want to change the value stored
in them. You may even store value of one data type in a statement and then a value of another
data in a subsequent statement.
Output:
Hello
100
12.34
Example:
>>> x = 5
>>> y =10
>>> print(‗Hello‘)
Hello
>>> print(x+y)
15
Multiple Assignment
Python allows programmers to assign a single value to more than one variables
simultaneously.
For example:
sum = flag = a = b = 0
All four integer variables are assigned a value 0.
Note: Removing a variable means that the reference from the name to the value has been
deleted. However, deleted variables can be again in the code if and only if you reassign them
some value.
For Example:
>>> str = ―Hello‖
>>> num = 10
>>> age = 20
>>> print(str)
Hello
>>> print(num)
10
>>> print(age)
20
>>> del num
>>> print(num)
Traceback (most recent call lat): File ―<pyshell+13‖, line 1, in
<module>
print(num)
NameError: name ‗num ‗ is not defined.
Example:
x = "hello"; print ( x )
Output: hello
Python Numbers
Integers, floating point numbers and complex numbers falls under Python numbers category.
Python supports four different numerical types −
o int (signed integers)
o long (long integers, they can also be represented in octal and hexadecimal)
o float (floating point real values)
o complex (complex numbers)
Example:
Note: The ‗E‘ notation indicates powers 10. In this case, 91.5E-2 means 91.5 * 10-2.
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
x + yj, where x and y are the real numbers and j is the imaginary unit.
We can use the type() function to know which class a variable or a value belongs to and
the isinstance( ) function to check if an object belongs to a particular class.
Example:
a=5
print(a, "is of type", type(a))
a = 2.0
print(a, "is of type", type(a))
a = 1+2j
print(a, "is complex number?", isinstance(1+2j,complex))
Output:
5 is of type <class 'int'>
2.0 is of type <class 'float'>
(1+2j) is complex number? True
o Int
Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
Integers can be of any length, it is only limited by the memory available.
Example:
x=1
y = 35656222554887711
z = -3255522
print(type(x))
print(type(y))
print(type(z))
Output:
<class 'int'>
<class 'int'>
<class 'int'>
o Float
Float, or "floating point number" is a number, positive or negative, containing one or more
decimals.
A floating point number is accurate up to 15 decimal places. Integer and floating points are
separated by decimal points. 1 is integer,1.0 is floating point number.
Example:
x = 1.10
y = 1.0
z = -35.59
print(type(x))
print(type(y))
print(type(z))
Output:
<class 'float'>
<class 'float'>
<class 'float'>
o Complex
Complex numbers are written in the form, x+yj, where x is the real part and y is the
imaginary part.
Complex numbers are written with a "j" as the imaginary part:
Example:
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
Output:
<class 'complex'>
<class 'complex'>
<class 'complex'>
Example:
>>> a = 1234567890123456789
>>> a
1234567890123456789
>>> b = 0.1234567890123456789
>>> b
0.12345678901234568
>>> c = 1+2j
>>> c
(1+2j)
Notice that the float variable b got truncated.
Although floating point numbers are very efficient at handling large numbers, there are
some issues while dealing with then as they may produce following errors:
The Arithmetic Overflow Problem: When you multiply two very large floating
point numbers you may get an arithmetic overflow. Arithmetic Overflow is a
condition that occurs when a calculated result is too large in magnitude (size) to be
represented.
For example:
2.7e200 * 4.3e200
Output: inf
The Arithmetic Underflow Problem: You can get an arithmetic underflow while
doing division of two floating point numbers. Arithmetic underflow is a condition that
occurs when a calculated result is too small in magnitude to be represented.
For example:
3.0e-400/5.0e200
Output: 0.0
Loss of Precision Problem: When you divide 1/3 you know that the result is
.33333333…, where 3 is repeated infinitely.
Output:
1.0
2.8
3.0
4.2
Example: Strings
x = str("s1")
y = str(2)
z = str(3.0)
print(x)
print(y)
print(z)
Output:
s1
2
3.0
The format ( ) function can also be used to format floating point numbers in scientific
notation.
Note: The format ( ) function produces a numeric string of a floating point value rounded to a
specific number of decimal places.
Python Strings
o Strings in Python are identified as a contiguous set of characters represented in the
quotation marks.
o Python allows for either pairs of single or double quotes.
o Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes
starting at 0 in the beginning of the string and working their way from -1 at the end.
o The plus (+) sign is the string concatenation operator and the asterisk (*) is the
repetition operator.
For example –
Output:
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
o The strip() method removes any whitespace from the beginning or the end:
Example:
a = " Hello, World! "
print([Link]())
Output:
Hello, World!
Output:
13
o The lower() method returns the string in lower case:
Example:
a = "Hello, World!"
print([Link]())
Output:
hello, world!
o The upper() method returns the string in upper case:
Example:
a = "Hello, World!"
print([Link]())
Output:
HELLO, WORLD!
o The replace() method replaces a string with another string:
Example:
a = "Hello, World!"
print([Link]("H", "J"))
Output:
Jello, World!
o The split() method splits the string into substrings if it finds instances of the separator:
Example:
a = "Hello, World!"
b = [Link](",")
print(b)
Output:
['Hello', 'World!']
Besides numbers, Python can also manipulate strings, which can be expressed in several
ways. They can be enclosed in single quotes (‗ … ‘) or double quotes ( ― … ―) with the same
result. \ can be used to escape quotes
Example:
>>> 'spam eggs' # single quotes
'spam eggs'
The print() function produces a more readable output, by omitting the enclosing quotes and
by printing escaped and special characters.
If you don‘t want characters prefaced by \ to be interpreted as special characters, you can
use raw strings by adding an r before the first quote:
>>> print('C:\some\name') # here \n means newline!
C:\some
ame
Strings can be concatenated (glued together) with the + operator, and repeated with *:
Example:
>>> # 3 times 'un', followed by 'ium'
>>> 3 * 'un' + 'ium'
'unununium'
Two or more string literals (i.e. the ones enclosed between quotes) next to each other are
automatically concatenated.
Example:
>>> 'Py' 'thon'
'Python'
Strings can be indexed (subscripted), with the first character having index 0. There is no
separate character type; a character is simply a string of size one.
Example:
>>> word = 'Python'
>>> word[0] # character in position 0
'P'
>>> word[5] # character in position 5
'n'
Indices may also be negative numbers, to start counting from the right.
Example:
>>> word[-1] # last character
'n'
>>> word[-2] # second-last character
'o'
>>> word[-6]
'P'
Note that since -0 is the same as 0, negative indices start from -1.
Note how the start is always included, and the end always excluded. This makes sure that s[:i]
+s[i:] is always equal to s.
Example:
>>> word[:2] + word[2:]
'Python'
Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second
index defaults to the size of the string being sliced.
Example:
>>> word[:2] # character from the beginning to position 2 (excluded)
'Py'
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 notation Hexadecimal character Description
\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
Example:
>>> a = [1, 2.2, 'python']
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes
starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is
the list concatenation operator, and the asterisk (*) is the repetition operator. For example −
Example:
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
Output:
['abcd', 786, 2.23, 'john', 70.2]
abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
Example:
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
Output:
apple
banana
cherry
Output:
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 :
['physics', 'chemistry', 2000]
Example:
thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
Output:
Yes, 'apple' is in the fruits list
Add Items
To add an item to the end of the list, use the append() method:
Example:
thislist = ["apple", "banana", "cherry"]
[Link]("orange")
print(thislist)
Output:
['apple', 'banana', 'cherry', 'orange']
To add an item at the specified index, use the insert() method:
Example:
thislist = ["apple", "banana", "cherry"]
[Link](1, "orange")
print(thislist)
Output:
['apple','orange','banana', 'cherry']
List Length
Example:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
Output:
3
Remove Item
Example:
thislist = ["apple", "banana", "cherry"]
[Link]("banana")
print(thislist)
Output:
['apple', 'cherry']
The pop() method removes the specified index, (or the last item if index is not specified):
Example:
thislist = ["apple", "banana", "cherry"]
[Link]()
print(thislist)
Output:
['apple', 'banana']
Output:
['banana', 'cherry']
Output:
[]
List Methods
Python has a set of built-in methods that you can use on lists.
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
Python Tuples
Tuple is an ordered sequences of items same as list.
The only difference is that tuples are immutable. Tuples once created cannot be modified.
Tuples are used to write-protect data and are usually faster than list as it cannot change
dynamically.
It is defined within parentheses () where items are separated by commas.
Example:
>>> t = (5,'program', 1+3j)
We can use the slicing operator [ ] to extract items but we cannot change its value.
The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and
their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and
cannot be updated. Tuples can be thought of as read-only lists. For example –
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
Output:
('abcd', 786, 2.23, 'john', 70.2)
abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')
Output:
3
Output:
('apple', 'banana', 'cherry')
Utility of Tuples
Example:
quo, rem = divmod(100,3)
print("Quotient = ",quo)
print("Rem = ",rem)
Output:
Quotient = 33
Rem = 1
Zip Function
Zip( ) is a function that takes two or more sequences and ―zips‖ them into a list of tuples.
Example:
Tup= (1,2,3,4,5)
List1=['a','b','c','d','e']
print(list((zip(Tup, List1))))
Output:
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')]
Tuple Methods
Method Description
count() Returns the number of times a specified value occurs in a tuple
index() Searches the tuple for a specified value and returns the position of where it
was found
Python Set
A set is a collection which is unordered and unindexed. In Python sets are written with curly
brackets.
Sets are unordered, so the items will appear in a random order and is separated by comma
inside braces { }.
Example:
a = {5,2,3,1,4}
Output:
a = {1, 2, 3, 4, 5}
<class 'set'>
We can perform set operations like union, intersection on two sets. Set have unique values.
They eliminate duplicates.
Example:
>>> a = {1,2,2,3,3,3}
>>> a
{1, 2, 3}
Access Items
You cannot access items in a set by referring to an index, since sets are unordered the items
has no index.
Example:
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
Output:
apple
banana
cherry
print("banana" in thisset)
Output:
True
Since, set are unordered collection, indexing has no meaning. Hence the slicing operator [ ]
does not work.
Example:
>>> a = {1,2,3}
>>> a[1]
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
TypeError: 'set' object does not support indexing
Add Items
To add one item to a set use the add() method.
Example:
thisset = {"apple", "banana", "cherry"}
[Link]("orange")
print(thisset)
Output:
{'cherry', 'banana', 'apple', 'orange'}
To add more than one item to a set use the update() method.
Example:
thisset = {"apple", "banana", "cherry"}
[Link](["orange", "mango", "grapes"])
print(thisset)
Output:
{'apple', 'banana', 'mango', 'cherry', 'grapes', 'orange'}
Get the Length of a Set
To determine how many items a set has, use the len() method.
Example:
thisset = {"apple", "banana", "cherry"}
print(len(thisset))
Output:
3
Remove Item
To remove an item in a set, use the remove(), or the discard() method.
Example:
thisset = {"apple", "banana", "cherry"}
[Link]("banana")
print(thisset)
Output:
{'cherry', 'apple'}
Note: If the item to remove does not exist, remove() will raise an error.
Example:
thisset = {"apple", "banana", "cherry"}
[Link]("banana")
print(thisset)
Output:
{'apple', 'cherry'}
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.
Example:
thisset = {"apple", "banana", "cherry"}
x = [Link]()
print(x)
print(thisset)
Output:
{'cherry', 'apple'}
Note: Sets are unordered, so when using the pop() method, you will not know which item
that gets removed.
The clear() method empties the set:
Example:
thisset = {"apple", "banana", "cherry"}
[Link]()
print(thisset)
Output:
set()
Set Methods
Method Description
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
difference() Returns a set containing the difference between two or more sets
difference_update() Removes the items in this set that are also included in another,
specified set
discard() Remove the specified item
intersection() Returns a set, that is the intersection of two other sets
intersection_update() Removes the items in this set that are not present in other,
specified set(s)
isdisjoint() Returns whether two sets have a intersection or not
issubset() Returns whether another set contains this set or not
issuperset() Returns whether this set contains another set or not
pop() Removes an element from the set
remove() Removes the specified element
symmetric_difference() Returns a set with the symmetric differences of two sets
symmetric_difference_update() inserts the symmetric differences from this set and another
union() Return a set containing the union of sets
update() Update the set with the union of this set and others
Syntax:
[Link](B)
Here, A and B are two sets. The following syntax is equivalent to A-B.
Example:
A = {'a', 'b', 'c', 'd'}
B = {'c', 'f', 'g'}
print([Link](B))
print([Link](A))
Output:{'b', 'a', 'd'}
{'g', 'f'}
You can also find the set difference using - operator in Python.
Example:
A = {'a', 'b', 'c', 'd'}
B = {'c', 'f', 'g'}
print(A-B)
print(B-A)
Python Set intersection()
The intersection() method returns a new set with elements that are common to all sets.
Syntax:
[Link](other sets)
Example:
A = {2, 3, 5, 4}
B = {2, 5, 100}
C = {2, 3, 8, 9, 10}
print([Link](A))
print([Link](C))
print([Link](C))
print([Link](A, B))
Output:
{2, 5}
{2}
{2, 3}
{2}
You can also find the intersection of sets using & operator.
Example:
A = {100, 7, 8}
B = {200, 4, 5}
C = {300, 2, 3, 7}
D = {100, 200, 300}
print(A & C)
print(A & D)
print(A & C & D)
print(A & B & C & D)
Output:
{7}
{100}
set()
set()
In Python, you can also find the symmetric difference using ^ operator.
A = {'a', 'b', 'c', 'd'}
B = {'c', 'd', 'e' }
print(A ^ B)
print(B ^ A)
print(A ^ A)
print(B ^ B)
Output:
{'e', 'a', 'b'}
{'e', 'a', 'b'}
set()
set()
Python Dictionary
A dictionary is a collection which is unordered, changeable and indexed.
Dictionary is an unordered collection of key-value pairs.
In Python, dictionaries are defined within braces {} with each item being a pair in the form
key:value. Key and value can be of any type.
Example:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Accessing Items
Example:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
print(x)
Output:
Mustang
There is also a method called get() that will give you the same result:
Example:
x = [Link]("model")
Change Values
Example:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 2018}
for x in [Link]():
print(x)
Output: Ford
Mustang
1964
Loop through both keys and values, by using the items() function:
Example:
for x, y in [Link]():
print(x, y)
Output:
brand Ford
model Mustang
year 1964
Dictionary Length
To determine how many items (key-value pairs) a dictionary has, use the len() method.
Example:
print(len(thisdict))
Adding Items
Example:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}
Removing Items
The pop() method removes the item with the specified key name:
Example:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]("model")
print(thisdict)
Output:
{'brand': 'Ford', 'year': 1964}
The popitem() method removes the last inserted item (in versions before 3.7, a random item
is removed instead):
Example:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]()
print(thisdict)
Output:
{'brand': 'Ford', 'model': 'Mustang'}
The del keyword removes the item with the specified key name:
Example:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
Output:
{'brand': 'Ford', 'year': 1964}
Dictionary Methods
Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and values
get() Returns the value of the specified key
items() Returns a list containing the a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with
the specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary
Floor Divison: The division of operands where the result is the quotient in which the 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).
Example:
>>> 20/10
2.0
>>> 20//10
2
Example:
x=5
print(x > 3 and x < 10)
Output:
True
Example:
x = ["apple", "banana"]
y = ["apple", "banana"]
z=x
print(x is not z)
print(x is not y)
print(x <> y)
Output: False
True
False
if Statement
An if statement is a selection control statement based on the value of a given expression.
Syntax:
if text_expression:
Statement 1
......
Statement n
Statement x
Example:
a = 33
b = 200
if b > a:
print("b is greater than a")
Output:
b is greater than a
if-else Statement
If and else statements are used to determine which option in a series of possibilities is True.
Syntax:
if text_expression:
Statement block 1
else:
Statement block 2
Statement x
Example:
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
Output:
b is not greater than a
Nested if Statements
If statements can be nested resulting in multi-way selection
Example:
num=int(input("Enter any number"))
if(num>=0 and num<10):
print("Range 0-10")
if(num>=10 and num<20):
print("Range 10-20")
if(num>=20 and num<30):
print("Range 20-30")
Output:
Range 20-30
if-elif-else Statement
The elif statement is a shortcut to if and else statements. A series of if and elif statements have a final
block, which is executed if none of the if or elif expressions is True.
The elif and else parts are optional.
Example:
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
Output:
a and b are equal
Example:
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
Output:
a is greater than b
Short Hand If
Example:
a = 200
b = 33
if a > b: print("a is greater than b")
Output:
a is greater than b
while loop
A while loop statement in Python programming language repeatedly executes a target
statement as long as a given condition is true.
Repeats a statement or group of statements while a given condition is TRUE. It tests the
condition before executing the loop body.
Syntax
while expression:
statement(s)
end specifies the values which have to be printed after the print statement has been executed.
Example:
i=1
while(i<=10):
print(i, end=" ")
i=i+1
Output:
1 2 3 4 5 6 7 8 9 10
If you want to separate the two values printed on the same line using a tab.
i=1
while(i<=10):
print(i, end="\t")
i=i+1
Output:
1 2 3 4 5 6 7 8 9 10
Note: If you use end = “”, then there will be no space between two values. There is no difference
in the way you write the end statement as end = „‟ or end = “”.
for Loop
Executes a sequence of statements multiple times and abbreviates the code that manages the
loop variable.
Syntax:
for iterating_var in sequence:
statements(s)
Nested Loops
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
Output:red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry
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) −
Output:
Enter the value of n= 5
sum 2.283333333333333
Program to calculate the square root.
import math
n=121
x = [Link](n)
print(x)
Output: 11.0
Program using for loop that prints the decimal equivalents of ½, 1/3, ¼, … 1/10.
for i in range (1,10):
print("1/", i,"=%f"% (1.0/i))
Output:1/ 1 =1.000000
1/ 2 =0.500000
1/ 3 =0.333333
1/ 4 =0.250000
1/ 5 =0.200000
1/ 6 =0.166667
1/ 7 =0.142857
1/ 8 =0.125000
1/ 9 =0.111111
iv)
1
12
123
1234
12345
for i in range (1,6):
for j in range(1,i+1):
print(j , end="")
print()
v)
A
BC
DEF
GHIJ
KLMNO
PQRSTU
lastNumber = 6
asciiNumber = 65
for i in range(0, lastNumber):
for j in range(0, i+1):
character = chr(asciiNumber)
print(character, end=' ')
asciiNumber+=1
print(― ‖)
vi)
A
AB
ABC
ABCD
ABCDE
for i in range(1, 6):
for j in range(65, 65+i):
a = chr(j)
print(a,end="")
print("")
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.
Using 'def' statement for defining a function is the corner store of a majority of
programs in Python.
Functions also let programmers compute a result-value and give parameters that serve
as function inputs that may change each time the code runs. Functions prove to be a
useful tool when the operations are coded in it and can be used in a variety of
scenarios.
Functions are an alternative method of cutting-and-pasting codes, rather than typing
redundant copies of the same instruction or operation; which further reduces the
future work for programmers. They are the most basic structure of a program, and so
Python provides this technique for code re-use.
Python gives you many built-in functions like print(), etc. but you can also create your
own functions. These functions are called user-defined functions.
Defining a Function
Rules to define a function in Python:
Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).
A function name to uniquely identify it. Function naming follows the same rules of
writing identifiers in Python.
Any input parameters or arguments should be placed within these parentheses. You
can also define parameters inside these parentheses.
The first statement of a function can be an optional statement - the documentation
string of the function or docstring. Optional documentation string (docstring) to
describe what the function does.
The code block within every function starts with a colon (:) and is indented. A colon
(:) to mark the end of function header.
The statement return [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as return
None. Statements must have same indentation level (usually 4 spaces).
Syntax
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
By default, parameters have a positional behaviour and you need to inform them in the same
order that they were defined.
Advantages of Python Functions
Maximizing code reusability
Minimizing redundancy
Procedural decomposition
Make programs simpler to read and understand
Creating a Function
In Python a function is defined using the def keyword:
Example:
def my_function():
print("Hello from a function")
Calling a Function
To call a function, use the function name followed by parenthesis:
Example:
def my_function():
print("Hello from a function")
my_function()
Parameters
Information can be passed to functions as parameter.
Parameters are specified after the function name, inside the parentheses. You can add
as many parameters as you want, just separate them with a comma.
The following example has a function with one parameter (fname). When the function
is called, we pass along a first name, which is used inside the function to print the full
name:
Example:
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Output:
Example:
def greet(name):
"""This function greets to
the person passed in as
parameter"""
print("Hello, " + name + ". Good morning!")
Call a function:
>>> greet('Paul')
Hello, Paul. Good morning!
The return statement
The return statement is used to exit a function and go back to the place from where it
was called.
Syntax of return
return [expression_list]
This statement can contain expression which gets evaluated and the value is returned. If there
is no expression in the statement or the return statement itself is not present inside a function,
then the function will return the None object.
Example:
>>> print(greet("May"))
Hello, May. Good morning!
None
Example of return
def absolute_value(num):
"""This function returns the absolute
value of the entered number"""
if num >= 0:
return num
else:
return -num
# Output: 2
print(absolute_value(2))
# Output: 4
print(absolute_value(-4))
Output:
2
4
It has to be kept in mind that every function without a return statement does return a value
which is called 'none'; which normally gets suppressed by the interpreter.
Example:
def karlos():
return 1, 2, 3
a, b, c = karlos()
print (a)
print (b)
print (c)
Output:
1
2
3
x = 20
my_func()
print("Value outside function:",x)
Output:
Value inside function: 10
Value outside function: 20
Note: In order to modify the value of variables outside the function, they must be declared as
global variables using the keyword global.
Types of Functions
Python Built-in Function
The Python interpreter has a number of functions that are always available for use. These
functions are called built-in functions. For example, print( ) function prints the given object to
the standard output device (screen) or to the text stream file.
In Python 3.6 (latest version), there are 68 built-in functions.
Method Description
Python abs() returns absolute value of a number
Python all() returns true when all elements in iterable is true
Python any() Checks if any Element of an Iterable is True
Python ascii() Returns String Containing Printable Representation
Python bin() converts integer to binary string
Python bool() Converts a Value to Boolean
Python bytearray() returns array of given byte size
Python bytes() returns immutable bytes object
Python callable() Checks if the Object is Callable
Python chr() Returns a Character (a string) from an Integer
Python classmethod() returns class method for given function
Python compile() Returns a Python code object
Python complex() Creates a Complex Number
Python delattr() Deletes Attribute From the Object
Python dict() Creates a Dictionary
Python dir() Tries to Return Attributes of Object
Python divmod() Returns a Tuple of Quotient and Remainder
Python enumerate() Returns an Enumerate Object
Python eval() Runs Python Code Within Program
Python exec() Executes Dynamically Created Program
Python filter() constructs iterator from elements which are true
Python float() returns floating point number from number, string
Python format() returns formatted representation of a value
Python frozenset() returns immutable frozenset object
Python getattr() returns value of named attribute of an object
Python globals() returns dictionary of current global symbol table
Python hasattr() returns whether object has named attribute
Python hash() returns hash value of an object
Python help() Invokes the built-in Help System
Python hex() Converts to Integer to Hexadecimal
Python id() Returns Identify of an Object
Python input() reads and returns a line of string
Python int() returns integer from a number or string
Python isinstance() Checks if a Object is an Instance of Class
Python issubclass() Checks if a Object is Subclass of a Class
Python iter() returns iterator for an object
Python len() Returns Length of an Object
Python list() Function creates list in Python
Python locals() Returns dictionary of a current local symbol table
Python map() Applies Function and Returns a List
Python max() returns largest element
Python memoryview() returns memory view of an argument
Python min() returns smallest element
Python next() Retrieves Next Element from Iterator
Python object() Creates a Featureless Object
Python oct() converts integer to octal
Python open() Returns a File object
Python ord() returns Unicode code point for Unicode character
Python pow() returns x to the power of y
Python print() Prints the Given Object
Python property() returns a property attribute
Python range() return sequence of integers between start and stop
Python repr() returns printable representation of an object
Python reversed() returns reversed iterator of a sequence
Python round() rounds a floating point number to ndigits places.
Python set() returns a Python set
Python setattr() sets value of an attribute of object
Python slice() creates a slice object specified by range()
Python sorted() returns sorted list from a given iterable
Python staticmethod() creates static method from a function
Python str() returns informal representation of an object
Python sum() Add items of an Iterable
Python super() Allow you to Refer Parent Class by super
Python tuple() Function Creates a Tuple
Python type() Returns Type of an Object
Python vars() Returns __dict__ attribute of a class
Python zip() Returns an Iterator of Tuples
Python __import__() Advanced Function Called by import
Example:
# Program to illustrate
# the use of user-defined functions
def add_numbers(x,y):
sum = x + y
return sum
num1 = 5
num2 = 6
Function Arguments
You can call a function by using the following types of formal arguments −
Required arguments
Keyword arguments
Default arguments
Variable-length arguments
Required arguments
Required arguments are the arguments passed to a function in correct positional order. Here,
the number of arguments in the function call should match exactly with the function
definition.
To call the function printme(), you definitely need to pass one argument, otherwise it gives a
syntax error as follows:
Example:
def printme( str ):
"This prints a passed string into this function"
print str
return;
Output:
Traceback (most recent call last):
File "[Link]", line 11, in <module>
printme();
TypeError: printme() takes exactly 1 argument (0 given)
Keyword arguments
Keyword arguments are related to the function calls. When you use keyword arguments in a
function call, the caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python interpreter
is able to use the keywords provided to match the values with parameters. You can also
make keyword calls to the printme() function in the following ways −
Output:
My string
Example:
# Function definition is here
def printinfo( name, age ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;
Output:
Name: miki
Age 50
Default Argument
If we call the function without parameter, it uses the default value:
Example:
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Output:
I am from Sweden
I am from India
I am from Norway
I am from Brazil
Variable-length arguments
You may need to process a function for more arguments than you specified while defining
the function. These arguments are called variable-length arguments and are not named in the
function definition, unlike required and default arguments.
Syntax for a function with non-keyword variable arguments is this −
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
An asterisk (*) is placed before the variable name that holds the values of all nonkeyword
variable arguments. This tuple remains empty if no additional arguments are specified during
the function call. Following is a simple example –
def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print "Output is: "
print arg1
for var in vartuple:
print var
return;
These functions are called anonymous because they are not declared in the standard manner
by using the def keyword. You can use the lambda keyword to create small anonymous
functions.
Lambda forms can take any number of arguments but return just one value in the
form of an expression. They cannot contain commands or multiple expressions.
An anonymous function cannot be a direct call to print because lambda requires an
expression
Lambda functions have their own local namespace and cannot access variables other
than those in their parameter list and those in the global namespace.
Although it appears that lambda's are a one-line version of a function, they are not
equivalent to inline statements in C or C++, whose purpose is by passing function
stack allocation during invocation for performance reasons.
Lambda functions have no name
Lambda functions can take any number of arguments
Lambda functions can return just one value in the form of an expression
Lambda functions definition does not have an explicit return statement but it always
contains which is returned.
They are a one line version of a function and hence cannot contain multiple
expressions.
They cannot access variables other than those in their parameter list.
Lambda functions cannot even access global variables.
You can pass lambda functions as arguments on other functions.
A lambda function that adds 10 to the number passed in as an argument, and print the result:
Example:
x = lambda a : a + 10
print(x(5))
Output:
15
Lambda functions can take any number of arguments. A lambda function that multiplies
argument a with argument b and print the result:
Example:
x = lambda a, b : a * b
print(x(5, 6))
Output: 30
A lambda function that sums argument a, b, and c and print the result:
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
Output: 13
Why Use Lambda Functions?
The power of lambda is better shown when you use them as an anonymous function inside
another function.
Say you have a function definition that takes one argument, and that argument will be
multiplied with an unknown number:
def myfunc(n):
return lambda a : a * n
Use that function definition to make a function that always doubles the number you send in.
Example:
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
Output:
22
Or, use the same function definition to make a function that always triples the number you
send in:
Example:
def myfunc(n):
return lambda a : a * n
mytripler = myfunc(3)
print(mytripler(11))
Output:
33
Or, use the same function definition to make both functions, in the same program:
Example:
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
Output:
22
33
NOTE:- Use lambda functions when an anonymous function is required for a short period of
time.
Program that uses a lambda function to find the sum of first 10 natural numbers
x=lambda: sum(range(1,11))
print(x())
Output: 55
Advantages of Recursion
1. Recursive functions make the code look clean and elegant.
2. A complex task can be broken down into simpler sub-problems using recursion.
3. Sequence generation is easier with recursion than using some nested iteration.
Disadvantages of Recursion
1. Sometimes the logic behind recursion is hard to follow through.
2. Recursive calls are expensive (inefficient) as they take up a lot of memory and time.
3. Recursive functions are hard to debug.
4.
Program to calculate the factorial of a number recursively
def GCD(x,y):
rem=x%y
if(rem==0):
return y
else:
return GCD(y,rem)