Unit
–I Introduction
1. Explain History of Python?
v
Python laid its foundation in the late 1980s.
v
The implementation of Python was started in December 1989 by Guido
Van Rossum at CWI in Netherland.
v
In February 1991, Guido
Van Rossum published the code (labeled version 0.9.0) to
alt.sources.
v
In 1994, Python 1.0 was released with new features like lambda,
map, filter, and reduce.
v
Python 2.0 added new features such as list comprehensions, garbage
collection systems.
v
On December 3, 2008, Python 3.0 (also called "Py3K") was
released. It was designed to rectify the fundamental flaw of the language.
v
ABC programming language is said to
be the predecessor of Python language, which was capable of Exception Handling
and interfacing with the Amoeba Operating System.
v
The following programming languages influence Python:
o
ABC language.
o
Modula-3
Why the Name
Python?
There is a fact behind choosing the
name Python
. Guido van Rossum was
reading the script of a popular BBC comedy series "Monty Python's
Flying Circus". It was late on-air 1970s.
Van Rossum wanted to select a name
which unique, sort, and little-bit mysterious. So he decided to select naming
Python after the "Monty Python's Flying Circus" for
their newly created programming language.
Python is also versatile and widely
used in every technical field, such as Machine Learning
v Web
Development, Mobile
Application
v Desktop
Application, Scientific Calculation, etc.
v
Latest
Version of Python is Python 3.8 in
October 14, 2019.
2. What is the Difference
Between Python and C Language?
Python vs C Language
|
|
Python is a multi-paradigm. It mainly supports
Object-oriented programming, Procedural programming, Functional programming. |
C is a Structured programming language. |
Language
Type |
|
Python is an interpreter based language. The
interpreter reads the code line by line. |
C is a compiled language. The complete source code
is converted into machine language. |
Memory
Management |
|
Python use automatic garbage collector for memory
management. |
In C, Programmer has to do memory management on his
own. |
Applications |
|
Python is a General-Purpose programming language. |
C is mainly used for hardware related applications. |
Speed |
|
Python is slow. |
C is fast. |
Variable
Declaration |
|
In Python, no need to declare variable type. |
In C, it is compulsory to declare variable type. |
Complexity |
|
Python programs are easier to learn, write and read. |
C program syntax is harder than Python. |
Testing and Debugging |
|
Testing and debugging is easier in Python. |
Testing and debugging is harder in C. |
1.
Differences
Between Java vs Python
A. programming language is a language that
describes a set of rules that can be used to give various types
of output. Python, Java,
C, C++, Fortran, Perl all are high-level languages. Java
is high level, an object-oriented programming language developed by Sun
Microsystem in 1995. Java runs on many platforms like Windows, Mac OS, Linux. Java is object-oriented, platform independent,
simple, secure, Robust, interpreted, multithread, high performance and dynamic.
Python is an object-oriented, high-level and all in one programming language.
It was developed by Guido Van Rossum during 1985- 1990. Python is highly
readable and easily understandable. python uses simple English keywords very
often whereas other languages use punctuation. Python is easy to learn, easy to
read, interactive mode, portable, extendable, databases, scalable.
Below are the lists of points, describe the
comparisons Between Java vs Python:
Basis for
Comparison |
Java |
Python |
Code |
Longer
lines of code as compared to Python public
class EduCba { public
static void main (String [] args) { System.out.println(“Hello
EduCBA”); } } |
print
(“Hello EduCBA”) |
Syntax |
At the end of the statement if you miss
semicolon it throws an error. In
Java you must define particular block using curly braces without it code
won’t work. |
In
python, statement do not need a semicolon to end. In
python, you have never seen a sight of curly braces but indentation is
mandatory in python. Indentation also improves readability of code. |
Dynamic |
In java you must declare type of the data. class
Example { public
static void main (String [] args) { int
x=10; System.out.println(x); } } |
Python codes are dynamic typed. This means that
you don’t need to declare a type of the variable this is known as duck
typing. X
= 45 site
= “educba.com” |
Speed |
In
terms of speed, Java is faster. Whenever in projects speed matters the java
is best. |
It
is slower because python is an interpreter and also it determines the type of
data at runtime. |
portability |
Due
to the high popularity of Java, JVM (Java Virtual Machine) is available
almost everywhere. |
Python
is also portable but in front of java, python is not popular. |
Databases |
(JDBC)Java
Database Connectivity is most popular and widely used to connect with
database. |
Python’s
database access layers are weaker than Java’s JDBC. This is why it rarely
used in enterprises. |
Easy
to use |
Java
is not easy to use as compared to python because there is no dynamic
programming concept and codes are longer than python. |
Python
codes are shorter than java. python follows dynamic programming python codes
not only easy to use but also easy to understand because of indentation. |
Practical
Dexterity |
Java
enjoys more undeviating refactoring support than python thanks to its static
type system and universality of IDE’s in development. |
Python
has always had an existence in the talent space and has the popularity for
many reasons including Data Science and DevOps movement. |
Legacy |
Java’s
history in the enterprise and its slightly more verbose coding style mean
that Java legacy systems are typically larger and more numerous than
python’s. |
Python
has less legacy problem so organization finds difficulty for the script to
copy and paste codes. |
2. Explain Python? What are the features
of Python?
A. Python is an interpreted, object-oriented programming language similar to PERL,
that has gained popularity because of its clear syntax and
readability. Python is said to be relatively easy to learn and portable,
meaning is statements can be interpreted in a number of operating systems, including UNIX-based systems, Mac OS, MS-DOS, OS/2,
and various versions of Microsoft Windows 98. Python was created by Guido van Rossum, a former resident of
the Netherlands, whose favorite comedy group at the time was Monty Python's
Flying Circus. The source code is freely available and open for
modification and reuse. Python has a significant number of users.
A notable feature of Python is its
indenting of source statements to make the code easier toread. Pythonoffers
dynamic data type,
ready-made class, and
interfaces to many system calls and libraries. It can be extended, using
the C or C++ language.Python
can be used as the script in Microsoft's Active Server Page (ASP) technology.
The scoreboard system for the Melbourne (Australia) Cricket Ground is written
in Python. Z Object Publishing Environment, a popular Web application server, is also written in the Python language.Python
is a multiparadigm, general-purpose, interpreted, high-level programming
language.Python allows programmers to use different programming styles to
create simple or complex programs, get quicker results and write code almost as
if speaking in a human language. Some of the popular systems and applications
that have employed Python during development include Google Search, YouTube,
BitTorrent, Google App Engine, Eve Online, Maya and iRobot machines.
Python Features: Python provides lots of features that are
listed below.
1) Easy
to Learn and Use: Python is easy to learn and use. It is developer-friendly
and high level programming language.
2) Expressive
Language: Python language is more expressive means that it is more understandable
and readable.
3) Interpreted
Language: Python is an interpreted language i.e. interpreter executes the
code line by line at a time. This makes debugging easy and thus suitable for
beginners.
4) Cross-platform
Language: Python can run equally on different platforms such as Windows,
Linux, Unix and Macintosh etc. So, we can say that Python is a portable
language.
5) Free
and Open Source: Python language is freely available at offical
web address.The
source-code is also available. Therefore it is open source.
6) Object-Oriented
Language: Python supports object oriented language and concepts of classes
and objects come into existence.
7) Extensible:
It implies that other languages such as C/C++ can be used to compile the
code and thus it can be used further in our python code.
8) Large
Standard Library: Python has a large and broad library and provides rich
set of module and functions for rapid application development.
9) GUI
Programming Support: Graphical user interfaces can be developed using
Python.
10) Integrated: It can be easily integrated with languages like C, C++,
JAVA etc.
3. How to Working with Python?
A. Python is a cross-platform
programming language, which means that it can run on multiple platforms like
Windows, macOS, Linux, and has even been ported to the Java and .NET virtual
machines. It is free and open-source.
Even though most of today's Linux and
Mac have Python pre-installed in it, the version might be out-of-date. So, it
is always a good idea to install the most current version.
The Easiest Way to Run
Python:
The easiest way to run Python is by
using Thonny
IDE.
The Thonny IDE comes with the latest
version of Python bundled in it. So you don't have to install Python
separately.
Follow the following steps to run
Python on your computer.
v Download Thonny
IDE.
v
Run
the installer to install Thonny on your computer.
v
Go
to: File > New. Then
save the file with .py
extension.
v For example, hello.py
, example.py
,
etc.
You can give any name to the file. However, the file name should end with .py
Write Python code in the file and save it.
4. Explain Basic Fundamentals in Python?
A. This section contains the basic fundamentals of Python
like :
i)Tokens
and their types.
ii)
Comments
a)Tokens:
v Tokens
can be defined as a punctuator mark, reserved words and each individual word in
a statement.
v Token
is the smallest unit inside the given program.
There are following tokens in Python:
- Keywords.
- Identifiers.
- Literals.
- Operators.
1. Keywords:
v Keywords are the reserved words in Python.
v We cannot use a keyword as a variable name, function name
or any other identifier. They are used to define the syntax and structure of
the Python language.
v In Python, keywords are case sensitive.
v There are 33 keywords in Python 3.7. This number can vary
slightly in the course of time.
v All the keywords except True, False and None are
in lowercase and they must be written as it is. The list of all the keywords is
given below:
false,
class, finally, is, return, none, continue, for, lambda, try, true, while etc.
2. Identifiers:
An identifier is a name given to
entities like class, functions, variables, etc. It helps to differentiate one
entity from another.
Rules for writing identifiers:
1.
Identifiers can be a combination of
letters in lowercase (a
to z) or uppercase (A to Z) or digits (0 to 9) or an
underscore _. Names like myClass, var_1 and print_this_to_screen, all are valid example.
2.
An identifier cannot start with a
digit. 1variable is invalid, but variable1 is perfectly fine.
3.
Keywords cannot be used as
identifiers.
4.
We cannot use special symbols
like !, @, #, $, % etc. in our identifier.
5.
Identifier can be of any length.
3. Literals:
Literal is a raw data given in a variable or constant.
In Python, there are various types of literals they are as follows:
v Numeric Literals:
Numeric Literals are immutable (unchangeable). Numeric
literals can belong to 3 different numerical types Integer, Float and Complex.
Example :
a = 0b1010 #Binary
Literals
b = 100 #Decimal
Literal
c = 0o310 #Octal
Literal
d = 0x12c
#Hexadecimal Literal
#Float Literal
float_1 = 10.5
float_2=13.5
#Complex Literal
x = 3.14j
print(a, b, c, d)
print(float_1,
float_2)
print(x, x.imag,
x.real)
v String literals:
A string literal is a sequence of characters
surrounded by quotes. We can use both single, double or triple quotes for a
string. And, a character literal is a single character surrounded by single or
double quotes.
Example:
strings
= "This is Python"
char
= "C"
multiline_str
= """This is a multiline string with more than one line
code."""
unicode
= u"\u00dcnic\u00f6de"
raw_str
= r"raw \n string"
print(strings)
print(char)
print(multiline_str)
print(unicode)
print(raw_str)
v Boolean
literals:
A Boolean literal
can have any of the two values: True
or False
.
Example:
x
= (1 == True)
y =
(1 == False)
a =
True + 4
b =
False + 10
print("x
is", x)
print("y
is", y)
print("a:",
a)
print("b:",
b)
v Literal Collections:
There are four
different literal collections List literals, Tuple literals, Dict literals, and
Set literals.
Example :
fruits
= ["apple", "mango", "orange"] #list
numbers
= (1, 2, 3) #tuple
alphabets
= {'a':'apple', 'b':'ball', 'c':'cat'} #dictionary
vowels
= {'a', 'e', 'i' , 'o', 'u'} #set
print(fruits)
print(numbers)
print(alphabets)
print(vowels)
4. Operators:
The
operator can be defined as a symbol which is responsible for a particular
operation between two operands. Operators are the pillars of a program on which
the logic is built in a particular programming language. Python provides a
variety of operators described as follows.
v Arithmetic
operators
v Comparison
operators
v Assignment
Operators
v Logical Operators
v Bitwise Operators
v Membership
Operators
v Identity Operators
ii) Comments: Comments
in Python can be used to explain any program code. It can also be used to hide
the code as well.
Comments are the most
helpful stuff of any program. It enables us to understand the way, a program
works. In python, any statement written along with # symbol is known as a
comment. The interpreter does not interpret the comment.
Comment is not a part of
the program, but it enhances the interactivity of the program and makes the
program readable.
Python supports two
types of comments:
1) Single Line
Comment:
In case user wants to
specify a single line comment, then comment must start with ?#?
Eg:
1.
# This is single line comment.
2.
print ("Hello Python")
Output:
Hello Python
2) Multi Line
Comment:
Multi lined comment can
be given inside triple quotes.
Example: ''''' This
Is
Multipline comment'''
Example:#single line comment
print "Hello Python" #Hello Python
'''''This is
multiline comment'''
5. Explain Python
Variables?
A. Variable is a name which is used to refer memory location. Variable also
known as identifier and used to hold value.In Python, we don't need to specify
the type of variable because Python is a type infer language and smart enough
to get variable type.
Variable names can be a group of both letters and digits,
but they have to begin with a letter or an underscore.It is recomended to use
lowercase letters for variable name. Rahul and rahul both are two different
variables.
Identifier Naming:Variables are the example of identifiers. An
Identifier is used to identify the literals used in the program. The rules to
name an identifier are given below.
v The
first character of the variable must be an alphabet or underscore ( _ ).
v All
the characters except the first character may be an alphabet of
lower-case(a-z), upper-case (A-Z), underscore or digit (0-9).
v Identifier
name must not contain any white-space, or special character (!, @, #, %, ^,
&, *).
v Identifier
name must not be similar to any keyword defined in the language.
v Identifier
names are case sensitive for example my name, and MyName is not the same.
v Examples
of valid identifiers : a123, _n, n_9, etc.
v Examples
of invalid identifiers: 1a, n%4, n 9, etc.
Declaring Variable and Assigning Values:
Python does not bound us to declare variable before using
in the application. It allows us to create variable at required time.
We don't need to declare explicitly variable in Python.
When we assign any value to the variable that variable is declared
automatically.
The equal (=) operator is used to assign value to a
variable.
Eg: a=10
print(a) #10
a=”ravi”
print(a) #ravi
a=20000.67
print(a) #20000.67
Multiple Assignment
Python allows us to assign a value to multiple variables in
a single statement which is also known as multiple assignment.
We can apply multiple assignments in two ways either by
assigning a single value to multiple variables or assigning multiple values to
multiple variables. Lets see given examples.
1. Assigning single value to multiple variables
Eg: x=y=z=50
print x #50
print y #50
print z #50
2.Assigning multiple values to multiple variables:
Eg: a,b,c=5,10,15
print a #5
print b #10
print c #15
The values will be assigned in the
order in which variables appears.
6. What are the datatypes in Python?
A. Python Data Types: Variables can hold values of different data types. Python is a
dynamically typed language hence we need not define the type of the variable
while declaring it. The interpreter implicitly binds the value with its type.
Python enables us to check the type of the variable used in
the program. Python provides us
the type() function which returns the type of the variable
passed.Consider the following example to define the values of different data
types and checking its type.
A=10
b="Hi Python"
c = 10.5
print(type(a)); #<type 'int'>
print(type(b)); #<type 'str'>
print(type(c)); #<type 'float'>
Standard data types:A
variable can hold different types of values. For example, a person?s name must
be stored as a string whereas its id must be stored as an integer.
Python provides various standard data types that define the
storage method on each of them. The data types defined in Python are given
below.
- Numbers
- String
- List
- Tuple
- Dictionary
- Set
1. Numbers:Number stores numeric values. Python creates Number
objects when a number is assigned to a variable. For example;
a = 3 , b = 5 #a and b are number objects
Python supports 4 types of numeric data.
1. int(signed integers like 10, 2,
29, etc.)
2. long(long integers used for
a higher range of values like 908090800L, -0x1929292L, etc.)
3. float(float is used to store
floating point numbers like 1.9, 9.902, 15.2, etc.)
4. complex (complex numbers like
2.14j, 2.0 + 2.3j, etc.)
Python allows us to use a lower-case L to be used with long
integers. However, we must always use an upper-case L to avoid confusion.
A complex number contains an ordered pair, i.e., x + iy
where x and y denote the real and imaginary parts respectively).
2. String:
The string can be defined as the sequence of characters
represented in the quotation marks. In python, we can use single, double, or
triple quotes to define a string.
String handling in python is a straightforward task since
there are various inbuilt functions and operators provided.
In the case of string handling, the operator + is used to
concatenate two strings as the operation "hello"+"
python" returns "hello python".
The operator * is known as repetition operator as the
operation "Python " *2 returns "Python Python ".The
following example illustrates the string handling in python.
str1 = 'hello javatpoint' #string str1
str2 = ' how are you' #string str2
print (str1[0:2]) #printing first two character using slice operator
print (str1[4]) #printing 4th character of the string
print (str1*2) #printing the string twice
print (str1 + str2) #printing the concatenation of str1 and str2
Output:
he
o
hellojavatpointhellojavatpoint
hellojavatpoint how are you
3.List:
Lists are similar to arrays in C. However; the
list can contain data of different types. The items stored in the list are
separated with a comma (,) and enclosed within square brackets [].
We can use slice [:] operators to access the data of the
list. The concatenation operator (+) and repetition operator (*) works with the
list in the same way as they were working with the strings.
Consider the following example.
l = [1, "hi", "python", 2]
print (l[3:]);
print (l[0:2]);
print (l);
print (l + l);
print (l * 3);
Output:
[2]
[1, 'hi']
[1, 'hi', 'python', 2]
[1, 'hi', 'python', 2, 1, 'hi', 'python', 2]
[1, 'hi', 'python', 2, 1, 'hi', 'python', 2, 1, 'hi', 'python', 2]
4. Tuple:
Ø Tuple
is another form of collection where different type of data can be stored.
Ø It is
similar to list where data is separated by commas. Only the difference is that
list uses square bracket and tuple uses parenthesis.
Ø Tuples
are enclosed in parenthesis and cannot be changed.
Ø A
tuple is a read-only data structure as we can't modify the size and value of
the items of a tuple.
Let's see a simple example of the tuple.
t = ("hi", "python", 2)
print (t[1:]);
print (t[0:1]);
print (t);
print (t + t);
print (t * 3);
print (type(t))
t[2] = "hi";
Output:
('python', 2)
('hi',)
('hi', 'python', 2)
('hi', 'python', 2, 'hi', 'python', 2)
('hi', 'python', 2, 'hi', 'python', 2, 'hi', 'python', 2)
<type 'tuple'>
TypeError: 'tuple' object does not support item assignment
>>> tuple=('rahul',100,60.4,'deepak')
>>> tuple1=('sanjay',10)
>>> tuple
('rahul', 100, 60.4, 'deepak')
>>> tuple[2:]
(60.4, 'deepak')
>>> tuple1[0]
'sanjay'
>>> tuple+tuple1
('rahul', 100, 60.4, 'deepak', 'sanjay', 10)
5. Dictionary:
Ø Dictionary
is a collection which works on a key-value pair.
Ø It
works like an associated array where no two keys can be same.
Ø Dictionaries
are enclosed by curly braces ({}) and values can be retrieved by square
bracket([]).
Ø It is like an associative array or a hash table where each
key stores a specific value. Key can hold any primitive data type whereas value
is an arbitrary Python object.
Consider the
following example.
d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'};
print("1st name is "+d[1]);
print("2nd name is "+ d[4]);
print (d);
print (d.keys());
print (d.values());
Output:
1st name is Jimmy
2nd name is mike
{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}
[1, 2, 3, 4]
['Jimmy', 'Alex', 'john', 'mike']
6. Set:
It is an unordered collection of unique
items. Set is defined by values separated by comma inside braces { }. Items in
a set are not ordered.
a =
{5,2,3,1,4}
#
printing set variable
print("a
= ", a)
#
data type of variable a
print(type(a))
7. What is an Operator?
Explain different types of Operators?
A. Python Operators: The
operator can be defined as a symbol which is responsible for a particular
operation between two operands. Operators are the pillars of a program on which
the logic is built in a particular programming language. Python provides a
variety of operators described as follows.
v Arithmetic
operators
v Comparison
operators
v Assignment
Operators
v Logical Operators
v Bitwise Operators
v Membership
Operators
v Identity Operators
1. Arithmetic operators: Arithmetic
operators are used to perform arithmetic operations between two operands. It
includes +(addition), - (subtraction), *(multiplication), /(divide),
%(reminder), //(floor division), and exponent (**).
Operator |
Meaning |
Example |
+ |
Add two operands or unary plus |
x + y |
- |
Subtract right operand from the
left or unary minus |
x - y |
* |
Multiply two operands |
x * y |
/ |
Divide left operand by the right
one (always results into float) |
x / y |
% |
Modulus - remainder of the
division of left operand by the right |
x % y |
// |
Floor division - division that
results into whole number adjusted to the left in the number line |
x // y |
** |
Exponent - left operand raised to
the power of right |
x**y (x to the power y) |
Example
#1: Arithmetic operators in Python
x = 15
y = 4
# Output: x + y = 19
print('x + y =',x+y)
# Output: x - y = 11
print('x - y =',x-y)
# Output: x * y = 60
print('x * y =',x*y)
# Output: x / y = 3.75
print('x / y =',x/y)
# Output: x // y = 3
print('x // y =',x//y)
# Output: x ** y = 50625
print('x ** y =',x**y)
2. Comparison operator: (Relational Operator):
Comparison
operators are used to comparing the value of the two operands and returns
boolean true or false accordingly. The comparison operators are described in
the following table.
Operator |
Meaning |
Example |
> |
Greater that - True if left
operand is greater than the right |
x > y |
< |
Less that - True if left operand
is less than the right |
x < y |
== |
Equal to - True if both operands
are equal |
x == y |
!= or <> |
Not equal to - True if operands
are not equal |
x != y x<>y |
>= |
Greater than or equal to - True if
left operand is greater than or equal to the right |
x >= y |
<= |
Less than or equal to - True if
left operand is less than or equal to the right |
x <= y |
Example
#2: Comparison operators in Python
x
= 10
y
= 12
#
Output: x > y is False
print('x > y is',x>y)
#
Output: x < y is True
print('x < y is',x<y)
#
Output: x == y is False
print('x == y is',x==y)
#
Output: x != y is True
print('x != y is',x!=y)
#
Output: x >= y is False
print('x >= y is',x>=y)
#
Output: x <= y is true
print('x <= y is',x<=y)
3. Assignment operators:
The assignment
operators are used to assign the value of the right expression to the left
operand. The assignment operators are described in the following table.
Operator |
Example |
Equivatent to |
= |
x = 5 |
x = 5 |
+= |
x += 5 |
x = x + 5 |
-= |
x -= 5 |
x = x – 5 |
*= |
x *= 5 |
x = x * 5 |
/= |
x /= 5 |
x = x / 5 |
%= |
x %= 5 |
x = x % 5 |
//= |
x //= 5 |
x = x // 5 |
**= |
x **= 5 |
x = x ** 5 |
&= |
x &= 5 |
x = x & 5 |
|= |
x |= 5 |
x = x | 5 |
^= |
x ^= 5 |
x = x ^ 5 |
>>= |
x >>= 5 |
x = x >> 5 |
<<= |
x <<= 5 |
x = x << 5 |
4. Bitwise operator:
The bitwise
operators perform bit by bit operation on the values of the two operands.
For example, 2 is 10 in
binary and 7 is 111.
In
the table below: Let x =
10 (0000 1010 in binary) and y =
4 (0000 0100 in binary)
Bitwise
operators in Python |
||
Operator |
Meaning |
Example |
& |
Bitwise AND |
x& y = 0 (0000 0000) |
| |
Bitwise OR |
x | y = 14 (0000 1110) |
~ |
Bitwise NOT |
~x = -11 (1111 0101) |
^ |
Bitwise XOR |
x ^ y = 14 (0000 1110) |
>> |
Bitwise right shift |
x>> 2 = 2 (0000 0010) |
<< |
Bitwise left shift |
x<< 2 = 40 (0010 1000) |
5. Logical Operators:
The logical
operators are used primarily in the expression evaluation to make a decision.
Python supports the following logical operators.
Operator |
Meaning |
Example |
and |
True if both the operands are true |
x and y |
or |
True if either of the operands is
true |
x or y |
not |
True if operand is false
(complements the operand) |
not x |
Example
#3: Logical Operators in Python
x
= True
y
= False
#
Output: x and y is False
print('x and y is',xand y)
#
Output: x or y is True
print('x or y is',xor y)
#
Output: not x is False
print('not x is',not x)
6. Membership Operators:
Python membership
operators are used to check the membership of value inside a data structure. If
the value is present in the data structure, then the resulting value is true
otherwise it returns false.
Operator |
Meaning |
Example |
in |
True if value/variable is found in
the sequence |
5 in x |
not in |
True if value/variable is not
found in the sequence |
5 not in x |
Example
: Membership operators in Python
x
= 'Hello world'
y
= {1:'a',2:'b'}
#
Output: True
print('H'
in x)
#
Output: True
print('hello' notin x)
#
Output: True
print(1 in y)
#
Output: False
print('a' in y)
Here, 'H' is
in x but 'hello' is not present in x (remember,
Python is case sensitive). Similary, 1 is key and 'a' is
the value in dictionary y. Hence, 'a' in y returns False.
7. Identity Operators:
Operator |
Description |
is |
It is evaluated
to be true if the reference present at both sides point to the same object. |
is not |
It is evaluated
to be true if the reference present at both side do not point to the same
object. |
Example:
Identity operators in Python
x1
= 5
y1
= 5
x2
= 'Hello'
y2=’Hello’
x3
= [1,2,3]
y3
= [1,2,3]
#
Output: False
print(x1 isnot y1)
#
Output: True
print(x2 is y2)
#
Output: True
print(x3
is y3)
8. Explain Decision Control Statements? (Or)
Explain Branching Statements.
satisfied.
if
test expression:
statement(s)
Here, the program
evaluates the test expression and will execute statement(s) only if the
text expression is True.If the text expression is False, the
statement(s) is not executed.
In Python, the body of
the if statement is indicated by the indentation. Body starts with an
indentation and the first unindented line marks the end.
Python interprets
non-zero values as True. None and 0 are interpreted
as False.
Example:If the
number is positive, we print an appropriate message
num = 3
ifnum> 0:
print(num, "is a positive
number.")
print("This is always
printed.")
num = -1
ifnum< 0:
print(num, "is a negative
number.")
print("This is also always
printed.")
When you run the program, the output will be:
This is always printed
This is also always printed.
Body of if
else:
Body of else
The if..else statement
evaluates test expression and will execute body of ifonly when
test condition is True.
If the condition
is False, body of else is executed. Indentation is used to
separate the blocks.
Example: Program checks if the number is positive or
negative and displays an appropriate message
num = 3
# num = 0
ifnum>= 0:
print("Positive or Zero")
else:
c. Python if...elif...else
Statement
Body of if
elif test expression:
Body of elif
else:
Body of else
The elif is
short for else if. It allows us to check for multiple expressions.
If the condition
for if is False, it checks the condition of the
next elif block and so on.
Example:To
check number is positive or negative or
zero and display an appropriate message
num = 3.4
# Try these two variations as well:
# num = 0
# num = -4.5
ifnum> 0:
print("Positive number")
elifnum == 0:
print("Zero")
else:
print("Negative number")
Output:
When
variable num is positive, Positive number is printed.
If num is
equal to 0, Zero is printed.
If num is
negative, Negative number is printed
d.Nestedif statements: We can have
a if...elif...else statementinsideanother if...elif...elsestatement.
This is called nesting in computer programming.
Any number of these statements can be nested inside one another.
Indentation is the only way to figure out the level of nesting. This can get
confusing, so must be avoided if we can.
Example:input a number check if the number is positive or negative
or zero and display an appropriate message
num
= float(input("Enter a number: "))
ifnum>=
0:
ifnum
== 0:
print("Zero")
else:
print("Positive
number")
else:
print("Negative
number")
Output 1
Enter a number: 5
Positive number
Output 2
Enter a number: -1
Negative number
Output 3
Enter a number: 0
Zero
9.Explain
Looping Statements?
A. Looping Statements is also called
as Iterative Control Statements or Repetitive Control statements in Python it
can be divided into six types.
1. for loop in
Python: The for loop in Python
is used to iterate over a sequence (list, tuple, string) or other iterable objects. Iterating over a sequence is called
traversal.
forval
in sequence:
Body of for
Here, val is
the variable that takes the value of the item inside the sequence on each
iteration.
Loop continues until
we reach the last item in the sequence. The body of for loop is separated from
the rest of the code using indentation.
Example:
# Program to find the sum of all
numbers stored in a list
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4,
11]
sum = 0
forval in numbers:
sum = sum+val
print("The sum is", sum)
when you run the program, the output
will be:
The sum is 48
2. while loop in Python: The while loop in Python is used to iterate over a block of
code as long as the test expression (condition) is true.
We generally use this loop when we
don't know beforehand, the number of times to iterate.
Syntax of while Loop in Python
whiletest_expression:
Body of while
In while loop, test expression is
checked first. The body of the loop is entered only if
the test_expression evaluates to True. After one iteration, the
test expression is checked again. This process continues until
the test_expressionevaluates to False.
Flowchart of while Loop
# Program to add natural numbersupto
# sum = 1+2+3+...+n To take input
from the user,
# n = int(input("Enter n:
"))
n = 10
# initialize sum and counter
sum = 0
i = 1
while i <= n:
sum = sum + i
i = i+1 # update counter
# print the sum
print("The sum is", sum)
When you run the program, the output
will be:
Enter n: 10
The sum is 55
3. The infinite loop: We can create an infinite loop using while statement. If the
condition of while loop is always True, we get an infinite loop.
Example: # Infinite loop using while
# An example of infinite loop press Ctrl + c to exit from
the loop
while True:
num = int(input("Enter an integer: "))
print("The double of",num,"is",2 * num)
Enter an integer: 3
The double of 3 is 6
Enter an integer: 5
The double of 5 is 10
Enter an integer: 6
The double of 6 is 12
Enter an integer:
Traceback (most recent call last):
4. Loop with condition at the top:This is a normal while loop without break statements. The
condition of the while loop is at the top and the loop terminates when this
condition is False.
Example: # Loop with condition at
the top
# Program to illustrate a loop with
condition at the top
# Try different numbers
n = 10
# Uncomment to get user input
#n = int(input("Enter n:
"))
# initialize sum and counter
sum = 0
i = 1
while i <= n:
sum = sum + i
i = i+1 # update counter
# print the sum
print("The sum is",sum)
When you run the program, the output
will be:
The sum is 55
Flowchart of Loop with Condition in
Middle
Example #3: Loop with condition in
the middle
# Program to illustrate a loop with condition in the middle.
# Take input from the user untill a vowel is entered
vowels = "aeiouAEIOU"
# infinite loop
vowels = "aeiouAEIOU"
while True:
v =
input("Enter a vowel: ")
# condition in the
middle
if v in vowels:
break
print("That is not a vowel. Try again!")
print("Thank you!")
Output
That is not a vowel. Try again!
Enter a vowel: 6
That is not a vowel. Try again!
Enter a vowel: ,
That is not a vowel. Try again!
Enter a vowel: u
Thank you!
6. Loop with condition at the
bottom: This kind of loop ensures that the
body of the loop is executed at least once. It can be implemented using an
infinite loop along with a conditional break at the end. This is similar to the
do...while loop in C.
Example : #Loop with condition at
the bottom
# Python program to illustrate a loop with condition at the
bottom Roll a dice untill user chooses to exit
import random
while True:
input("Press enter to roll the dice")
num = random.randint(1,6)
print("You got",num)
option = input("Roll again?(y/n) ")
if option == 'n':
break
Output
Press enter to roll the dice
You got 1
Roll again?(y/n) y
Press enter to roll the dice
You got 5
Roll again?(y/n) n
10. What
is the use of break and continue in Python?
A. In Python, break and continue
statements can alter the flow of a normal loop.Loops iterate over a block of
code until test expression is false, but sometimes we wish to terminate the
current iteration or even the whole loop without checking test expression.
1. Python break statement: The break statement terminates the loop containing it.
Control of the program flows to the statement immediately after the body of the
loop.
If
break statement is inside a nested loop (loop inside another loop), break will
terminate the innermost loop. Flowchart
of break
break
# Use of break statement inside loop
forval in "string":
ifval == "i":
break
print(val)
print("The end")
Output
s
t
r
The end
In this program, we iterate through the "string" sequence.
We check if the letter is "i", upon which we break from the
loop. Hence, we see in our output that all the letters up
till "i" gets printed. After that, the loop terminates.
2.
Python continue statement: The continue
statement is used to skip the rest of the code inside a loop for the current
iteration only. Loop does not terminate but continues on with the next
iteration. Flowchart
of continue
continue
The working of continue statement in
for and while loop is shown below.
# Program to show the use of
continue statement inside loops
forval in "string":
ifval == "i":
continue
print(val)
print("The end")
Output
s
t
r
n
g
The end
11. What is pass statement in
Python?
In Python programming, pass is
a null statement. The difference between a comment and
pass statement in Python is
that, while the interpreter ignores a comment entirely, pass is not
ignored.However, nothing happens when pass is executed. It results into no
operation (NOP).
Syntax of pass:
pass
We generally use it as a
placeholder.
Suppose we have a loop or a function that is not implemented yet, but we want to implement
it in the future. They cannot have an empty body. The interpreter would
complain. So, we use the pass statement to construct a body that does
nothing.
Example: pass Statement
# pass is just a placeholder for
# functionality to be added later.
sequence = {'p', 'a', 's', 's'}
forval in sequence:
pass
We can do the same thing in an empty
function or class as
well.
def function(args):
pass
class example:
pass
12. Explain Input & Output Statements in Python.
A.Input Statement:Up till now, our programs
were static. The value of variables were defined or hard coded into the source
code.
To
allow flexibility we might want to take the input from the user. In Python, we
have the input() function to allow this. The syntax
for input() is
input([prompt])
where prompt is
the string we wish to display on the screen. It is optional.
>>>num = input('Enter a number: ')
Enter a number: 10
>>>num
'10'
Output Statement:We use the print()
function
to output data to the standard output device (screen).We can also output
data to a file, but
this will be discussed later. An example use is given below.
print('This sentence is output to the screen')
# Output: This sentence is output to the
screen
a = 5
print('The value of a is', a)
# Output: The value of a is 5
print(1,2,3,4)
# Output: 1 2 3 4
print (1,2,3,4,sep='*')
# Output: 1*2*3*4
print(1,2,3,4,sep='#',end='&')
# Output: 1#2#3#4&
We can even use keyword arguments to
format the string.
>>>print('Hello {name}, {greeting}'.format(greeting ='Goodmorning', name ='John'))
HelloJohn,Goodmorning
We can even format strings like the
old sprintf()
style
used in C
programming language.
We use the %
operator
to accomplish this.
>>> x =12.3456789
>>>print('The value of x is %3.2f'%x)
The value of x is12.35
>>>print('The value of x is %3.4f'%x)
The value of x is12.3457
13. What is a
String? How to Access and its operqations by using Strings?
A. Strings: Strings in python are surrounded by either single quotation
marks, or double quotation marks. 'hello' is the same
as "hello". You can display a string literal with
the print() function:
Example:
print("Hello")
print('Hello')
v Assign String to a Variable: Assigning a string to a variable
is done with the variable name followed by an equal sign and the string:
Example:
a
= "Hello"
print(a)
v Multiline Strings: You can assign a multiline string to a variable by
using three quotes:
Example:
a
= """Loremipsumdolor sit
amet, consecteturadipiscingelit, sed do eiusmodtemporincididuntutlabore et
dolore magna aliqua."""
print(a)
v Strings
are Arrays: Like many other
popular programming languages, strings in Python are arrays of bytes
representing unicode characters. However, Python does not have a character data
type, a single character is simply a string with a length of 1.
Example:
a
= "Hello, World!"
print(a[1])
v Looping
Through a String: Since strings
are arrays, we can loop through the characters in a string, with a for
loop.
Example:
for x in "banana":
print(x)
v String Length:To get the length of a string, use the len()
function.
a
= "Hello, World!"
print(len(a))
v Check
String: To check if a
certain phrase or character is present in a string, we can use the
keyword in
.
txt = "The best things in life are free!"
print("free" in txt)
v Check
if NOT: To check if a
certain phrase or character is NOT present in a string, we can use the
keyword not in
.
txt = "The best things in life are free!"
print("expensive" not in txt)
v Slicing:You can return a range of
characters by using the slice syntax.
Specify the start
index and the end index, separated by a colon, to return a part of the string.
Example:Get the characters from position
2 to position 5 (not included):
b
= "Hello, World!"
print(b[2:5])
Example:
Get the
characters from the start to position 5 (not included):
b
= "Hello, World!"
print(b[:5])
Example:Get the characters from position
2, and all the way to the end:
b
= "Hello, World!"
print(b[2:])
Example:
Get the
characters:
From:
"o" in "World!" (position -5)
To, but not
included: "d" in "World!" (position -2):
b
= "Hello, World!"
print(b[-5:-2])
v Upper Case: The upper()
method
returns the string in upper case:
Example:
a
= "Hello, World!"
print(a.upper())
v Lower Case:The lower()
method
returns the string in lower case:
a
= "Hello, World!"
print(a.lower())
v Replace String:The replace()
method
replaces a string with another string:
a
= "Hello, World!"
print(a.replace("H", "J"))
v Split
String: The split()
method
returns a list where the text between the specified separator becomes the list
items.
Example: The split()
method
splits the string into substrings if it finds instances of the separator:
a
= "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
v String
Concatenation: To concatenate,
or combine, two strings you can use the + operator.
Example:Merge variable a
with
variable b
into variable c
:
a = "Hello"
b = "World"
c = a + b
print(c)
Example:To add a space between them, add
a " "
:
a = "Hello"
b = "World"
c = a
+ " " + b
print(c)
v String
Format: As we learned in
the Python Variables chapter, we cannot combine strings and numbers like this:
Example:
age = 36
txt = "My name is John, I am " + age
print(txt)
Example:
Use the format()
method
to insert numbers into strings:
age = 36
txt = "My
name is John, and I am {}"
print(txt.format(age))
Example:
quantity = 3
itemno = 567
price = 49.95
myorder = "I
want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno,
price))
Python Lists
The list is a most versatile datatype
available in Python which can be written as a list of comma-separated values
(items) between square brackets. Important thing about a list is that items in
a list need not be of the same type.
Creating a list is as simple as
putting different comma-separated values between square brackets. For Example:
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"]
Similar to string indices, list
indices start at 0, and lists can be sliced, concatenated and so on.
Accessing Values in Lists:
To access values in lists, use the
square brackets for slicing along with the index or indices to obtain value
available at that index. For Example:
list1 =['physics','chemistry',1997,2000];
list2 =[1,2,3,4,5,6,7];
print"list1[0]: ", list1[0]
print"list2[1:5]: ", list2[1:5]
When the above code is executed, it
produces the following result −
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]
Updating Lists:
You can update single or multiple
elements of lists by giving the slice on the left-hand side of the assignment
operator, and you can add to elements in a list with the append() method. For Example:
list =['physics','chemistry',1997,2000];
print"Value available at index 2 : "
print list[2]
list[2]=2001;
print"New value available at index 2 : "
print list[2]
Note − append() method is
discussed in subsequent section.
When the above code is executed, it
produces the following result:
Value available at index 2 :
1997
New value available at index 2 :
2001
Delete List Elements:
To remove a list element, you can use
either the del statement if you know exactly which element(s) you are deleting
or the remove() method if you do not know. For Example:
list1 =['physics','chemistry',1997,2000];
print list1
del list1[2];
print"After deleting value at index 2 : "
print list1
When the above code is executed, it
produces following result:
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 :
['physics', 'chemistry', 2000]
Note − remove() method is
discussed in subsequent section.
Basic List Operations:
Lists respond to the + and *
operators much like strings; they mean concatenation and repetition here too,
except that the result is a new list, not a string.
In fact, lists respond to all of the
general sequence operations we used on strings in the prior chapter.
Python Expression |
Results |
Description |
len([1, 2, 3]) |
3 |
Length |
[1, 2, 3] + [4, 5, 6] |
[1, 2, 3, 4, 5, 6] |
Concatenation |
['Hi!'] * 4 |
['Hi!', 'Hi!', 'Hi!', 'Hi!'] |
Repetition |
3 in [1, 2, 3] |
True |
Membership |
for x in [1, 2, 3]: print x, |
1 2 3 |
Iteration |
Indexing, Slicing, and Matrixes:
Because lists are sequences, indexing
and slicing work the same way for lists as they do for strings.
Assuming following input: L = ['spam', 'Spam', 'SPAM!']
Python Expression |
Results |
Description |
L[2] |
SPAM! |
Offsets start at zero |
L[-2] |
Spam |
Negative: count from the right |
L[1:] |
['Spam', 'SPAM!'] |
Slicing fetches sections |
Built-in List Functions & Methods
Functions:
Python includes the following list functions −
SNo |
Function
with Description |
1 |
Compares elements of both
lists. Example: list1, list2 =[123,'xyz'],[456,'abc'] print cmp(list1, list2) print cmp(list2, list1) list3 = list2 +[786]; print cmp(list2, list3) Output: -1 1 -1 |
2 |
Gives the total length of the
list. Example: list1, list2 =[123,'xyz','zara'],[456,'abc'] print"First list length : ", len(list1) print"Second list length : ", len(list2) Output: First list length : 3 Second list length : 2 |
3 |
Returns item from the list
with max value. Example: list1 =[123,'xyz','zara','abc'] list2 =[456,700,200] print"Max value element : ", max(list1) print"Max value element : ", max(list2) Output: Max value element : zara Max value element : 700 |
4 |
Returns item from the list
with min value. Example: list1 =[123,'xyz','zara','abc'] list2 = [456,700,200] print"min value element : ", min(list1) print"min value element : ", min(list2) Output: min value element : 123 min value element : 200 |
5 |
Converts a tuple into list. Example: aTuple =(123,'xyz','zara','abc'); aList = list(aTuple) print"List elements : ", aList Output: List elements : [123, 'xyz', 'zara', 'abc'] |
Methods:
Python includes following list methods
SNo |
Methods
with Description |
1 |
Appends object obj to list Example: aList =[123,'xyz','zara','abc']; aList.append(2009); print"Updated List : ", aList Output: Updated List : [123, 'xyz', 'zara', 'abc', 2009] |
2 |
Returns count of how many
times obj occurs in list Example: aList =[123,'xyz','zara','abc',123]; print"Count for 123 : ", aList.count(123) print"Count for zara : ", aList.count('zara') Output: Count for 123 : 2 Count for zara : 1 |
3 |
Appends the contents of seq
to list Example: aList =[123,'xyz','zara','abc',123]; bList =[2009,'manni']; aList.extend(bList) print"Extended List : ", aList Output: Extended List : [123, 'xyz', 'zara', 'abc', 123, 2009, 'manni'] |
4 |
Returns the lowest index in
list that obj appears Example: aList =[123,'xyz','zara','abc']; print"Index for xyz : ", aList.index('xyz') print"Index for zara : ", aList.index('zara') Output: Index for xyz : 1 Index for zara : 2 |
5 |
Inserts object obj into list
at offset index Example: aList =[123,'xyz','zara','abc'] aList.insert(3,2009) print"Final List : ", aList Output: Final List : [123, 'xyz', 'zara', 2009, 'abc'] |
6 |
Removes and returns last
object or obj from list Example: aList =[123,'xyz','zara','abc']; print"A List : ", aList.pop() print"B List : ", aList.pop(2) Output: A List : abc B List : zara |
7 |
Removes object obj from list aList =[123,'xyz','zara','abc','xyz']; aList.remove('xyz'); print"List : ", aList aList.remove('abc'); print"List : ", aList Output: List : [123, 'zara', 'abc', 'xyz'] List : [123, 'zara', 'xyz'] |
8 |
Reverses objects of list in
place Example: aList =[123,'xyz','zara','abc','xyz']; aList.reverse(); print"List : ", aList Output: List : ['xyz', 'abc', 'zara', 'xyz', 123] |
9 |
Sorts objects of list, use
compare func if given Example: aList =[123,'xyz','zara','abc','xyz']; aList.sort(); print"List : ", aList Output: List : [123, 'abc', 'xyz', 'xyz', 'zara'] |
Python - Tuples
A tuple is a collection of objects
which ordered and immutable. Tuples are sequences, just like lists. The
differences between tuples and lists are, the tuples cannot be changed unlike
lists and tuples use parentheses, whereas lists use square brackets.
Creating a tuple is as simple as
putting different comma-separated values. Optionally you can put these
comma-separated values between parentheses also. For example:
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";
The empty tuple is written as two
parentheses containing nothing:
tup1 = ();
To write a tuple containing a single
value you have to include a comma, even though there is only one value:
tup1 = (50,);
Like string indices, tuple indices
start at 0, and they can be sliced, concatenated, and so on.
Accessing
Values in Tuples:
To access values in tuple, use the
square brackets for slicing along with the index or indices to obtain value
available at that index. For example −
tup1 =('physics','chemistry',1997,2000);
tup2 =(1,2,3,4,5,6,7);
print"tup1[0]: ", tup1[0];
print"tup2[1:5]: ", tup2[1:5];
When the above code is executed, it
produces the following result −
tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]
Updating Tuples:
Tuples are immutable which means you
cannot update or change the values of tuple elements. You are able to take
portions of existing tuples to create new tuples as the following example
demonstrates −
tup1 =(12,34.56);
tup2 =('abc','xyz');
# Following action is not valid for tuples
# tup1[0] = 100;
# So let's create a new tuple as follows
tup3 = tup1 + tup2;
print tup3;
When the above code is executed, it
produces the following result −
(12, 34.56, 'abc', 'xyz')
Delete Tuple Elements:
Removing individual tuple elements is
not possible. There is, of course, nothing wrong with putting together another
tuple with the undesired elements discarded.
To explicitly remove an entire tuple,
just use the del statement. For example −
tup =('physics','chemistry',1997,2000);
print tup;
del tup;
print"After deleting tup : ";
print tup;
This produces the following result.
Note an exception raised, this is because after del tup tuple
does not exist any more −
('physics', 'chemistry', 1997, 2000)
After deleting tup :
Traceback (most recent call last):
File "test.py", line 9, in <module>
print tup;
NameError: name 'tup' is not defined
Basic Tuples Operations:
Tuples respond to the + and *
operators much like strings; they mean concatenation and repetition here too,
except that the result is a new tuple, not a string.
In fact, tuples respond to all of the
general sequence operations we used on strings in the prior:
Python Expression |
Results |
Description |
len((1, 2, 3)) |
3 |
Length |
(1, 2, 3) + (4, 5, 6) |
(1, 2, 3, 4, 5, 6) |
Concatenation |
('Hi!',) * 4 |
('Hi!', 'Hi!', 'Hi!', 'Hi!') |
Repetition |
3 in (1, 2, 3) |
True |
Membership |
for x in (1, 2, 3): print x, |
1 2 3 |
Iteration |
Indexing, Slicing, and Matrixes:
Because tuples are sequences,
indexing and slicing work the same way for tuples as they do for strings.
Assuming following input −
L =('spam','Spam','SPAM!')
Python
Expression |
Results |
Description |
L[2] |
'SPAM!' |
Offsets start at zero |
L[-2] |
'Spam' |
Negative: count from the right |
L[1:] |
['Spam', 'SPAM!'] |
Slicing fetches sections |
No Enclosing Delimiters:
Any set of multiple objects,
comma-separated, written without identifying symbols, i.e., brackets for lists,
parentheses for tuples, etc., default to tuples, as indicated in these short
examples:
print'abc',-4.24e93,18+6.6j,'xyz';
x, y =1,2;
print"Value of x , y : ", x,y;
When the above code is executed, it
produces the following result −
abc -4.24e+93 (18+6.6j) xyz
Value of x , y : 1 2
Built-in Tuple Functions:
Python includes the following tuple
functions :
SNo |
Function with Description |
1 |
Compares elements of both
tuples. Example: tuple1, tuple2 =(123,'xyz'),(456,'abc') print cmp(tuple1, tuple2) print cmp(tuple2, tuple1) tuple3 = tuple2 +(786,); print cmp(tuple2, tuple3) Output: -1 1 -1 |
2 |
Gives the total length of the
tuple. Example: tuple1, tuple2 =(123,'xyz','zara'),(456,'abc') print"First tuple length : ", len(tuple1) print"Second tuple length : ", len(tuple2) Output: First tuple length : 3 Second tuple length : 2 |
3 |
Returns item from the tuple
with max value. Example: tuple1 =(123,'xyz','zara','abc') tuple2 = (456,700, 200) print"Max value element : ", max(tuple1) print"Max value element : ", max(tuple2) Output: Max value element : zara Max value element : 700 |
4 |
Returns item from the tuple
with min value. Example: tuple1 =(123,'xyz','zara','abc') tuple2 = (456,700, 200) print"min value element : ", min(tuple1) print"min value element : ", min(tuple2) Output: min value element : 123 min value element : 200 |
5 |
Converts a list into tuple. Example: aList =[123,'xyz','zara','abc'] aTuple = tuple(aList) print"Tuple elements : ", aTuple Output: Tuple elements : (123, 'xyz', 'zara', 'abc') |
Python
– Dictionary
Each key is
separated from its value by a colon (:), the items are separated by commas, and
the whole thing is enclosed in curly braces. An empty dictionary without any
items is written with just two curly braces, like this: {}.
Keys are
unique within a dictionary while values may not be. The values of a dictionary
can be of any type, but the keys must be of an immutable data type such as
strings, numbers, or tuples.
Accessing
Values in Dictionary:
To access
dictionary elements, you can use the familiar square brackets along with the
key to obtain its value. Following is a simple example −
dict ={'Name':'Zara','Age':7,'Class':'First'}
print"dict['Name']: ", dict['Name']
print"dict['Age']: ", dict['Age']
When the
above code is executed, it produces the following result:
dict['Name']: Zara
dict['Age']: 7
If we
attempt to access a data item with a key, which is not part of the dictionary,
we get an error as follows −
dict ={'Name':'Zara','Age':7,'Class':'First'}
print"dict['Alice']: ", dict['Alice']
When the
above code is executed, it produces the following result:
dict['Alice']:
Traceback (most recent call last):
File "test.py", line 4, in <module>
print "dict['Alice']: ", dict['Alice'];
KeyError: 'Alice'
Updating Dictionary:
You can
update a dictionary by adding a new entry or a key-value pair, modifying an
existing entry, or deleting an existing entry as shown below in the simple
example −
dict ={'Name':'Zara','Age':7,'Class':'First'}
dict['Age']=8;# update existing entry
dict['School']="DPS School";# Add new entry
print"dict['Age']: ", dict['Age']
print"dict['School']: ", dict['School']
When the
above code is executed, it produces the following result:
dict['Age']: 8
dict['School']: DPS School
Delete Dictionary Elements:
You can
either remove individual dictionary elements or clear the entire contents of a
dictionary. You can also delete entire dictionary in a single operation.
To
explicitly remove an entire dictionary, just use the del statement.
Following is a simple Example :
dict ={'Name':'Zara','Age':7,'Class':'First'}
del dict['Name'];# remove entry with key 'Name'
dict.clear();# remove all entries in dict
del dict ;# delete entire dictionary
print"dict['Age']: ", dict['Age']
print"dict['School']: ", dict['School']
This
produces the following result. Note that an exception is raised because
after del dict dictionary does not exist any more:
dict['Age']:
Traceback (most recent call last):
File "test.py", line 8, in <module>
print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable
Note − del() method is discussed in subsequent section.
Properties of Dictionary Keys:
Dictionary
values have no restrictions. They can be any arbitrary Python object, either
standard objects or user-defined objects. However, same is not true for the
keys.
There are
two important points to remember about dictionary keys −
(a) More than one entry per key not allowed. Which means
no duplicate key is allowed. When duplicate keys encountered during assignment,
the last assignment wins. For Example:
dict ={'Name':'Zara','Age':7,'Name':'Manni'}
print"dict['Name']: ", dict['Name']
When the
above code is executed, it produces the following result −
dict['Name']: Manni
(b) Keys must be immutable. Which means you can use
strings, numbers or tuples as dictionary keys but something like ['key'] is not
allowed. Following is a simple Example:
dict ={['Name']:'Zara','Age':7}
print"dict['Name']: ", dict['Name']
When the
above code is executed, it produces the following result −
Traceback (most recent call last):
File "test.py", line 3, in <module>
dict = {['Name']: 'Zara', 'Age': 7};
TypeError: unhashable type: 'list'
Built-in Dictionary Functions & Methods
Python
includes the following dictionary functions:
Sr.No. |
Function with Description |
1 |
Compares elements of both
dict. Example: dict1 = {'Name': 'Zara', 'Age': 7}; dict2 = {'Name': 'Mahnaz', 'Age': 27}; dict3 = {'Name': 'Abid', 'Age': 27}; dict4 = {'Name': 'Zara', 'Age': 7}; print "Return Value : %d" % cmp (dict1, dict2) print "Return Value : %d" % cmp (dict2, dict3) print "Return Value : %d" % cmp (dict1, dict4) Output: Return Value : -1 Return Value : 1 Return Value : 0 |
2 |
Gives the total length of the
dictionary. This would be equal to the number of items in the dictionary. Example: dict = {'Name': 'Zara', 'Age': 7}; print "Length : %d" % len (dict) Output: Length : 2 |
3 |
Produces a printable string
representation of a dictionary Example: dict = {'Name': 'Zara', 'Age': 7}; print "Equivalent String : %s" % str (dict) Output: Equivalent String : {'Age': 7, 'Name': 'Zara'} |
4 |
Returns the type of the
passed variable. If passed variable is dictionary, then it would return a
dictionary type. Example: dict = {'Name': 'Zara', 'Age': 7}; print "Variable Type : %s" % type (dict) Output: Variable Type : <type 'dict'> |
Methods:
Python
includes following dictionary methods −
Sr.No. |
Methods with Description |
1 |
Removes
all elements of dictionary dict Example: dict = {'Name': 'Zara', 'Age': 7}; print "Start Len : %d" % len(dict) dict.clear() print "End Len : %d" % len(dict) Output: Start Len : 2 End Len : 0 |
2 |
Returns
a shallow copy of dictionary dict Example: dict1 = {'Name': 'Zara', 'Age': 7}; dict2 = dict1.copy() print "New Dictionary : %s" % str(dict2) Output: New Dictionary : {'Age': 7, 'Name': 'Zara'} |
3 |
Create
a new dictionary with keys from seq and values set to value. Example: seq = ('name', 'age', 'Gen') dict = dict.fromkeys(seq) print "New Dictionary : %s" % str(dict) dict = dict.fromkeys(seq, 10) print "New Dictionary : %s" % str(dict) Output: New Dictionary : {'age': None, 'name': None, 'Gen': None} New Dictionary : {'age': 10, 'name': 10, 'Gen': 10} |
4 |
For key key,
returns value or default if key not in dictionary Example: dict = {'Name': 'Zabra', 'Age': 7} print "Value : %s" % dict.get('Age') print "Value : %s" % dict.get('Education', "Never") Output: Value : 7 Value : Never |
5 |
Returns true if
key in dictionary dict, false otherwise Example: dict = {'Name': 'Zara', 'Age': 7} print "Value : %s" % dict.has_key('Age') print "Value : %s" % dict.has_key('Gen') Output: Value : True Value : False |
6 |
Returns
a list of dict's (key, value) tuple pairs Example: dict = {'Name': 'Zara', 'Age': 7} print "Value : %s" % dict.items() Output: Value : [('Age', 7), ('Name', 'Zara')] |
7 |
Returns
list of dictionary dict's keys Example: dict = {'Name': 'Zara', 'Age': 7} print "Value : %s" % dict.keys() Output: Value : ['Age', 'Name'] |
8 |
dict.setdefault(key, default=None) Similar
to get(), but will set dict[key]=default if key is not
already in dict Example: dict = {'Name': 'Zara', 'Age': 7} print "Value : %s" % dict.setdefault('Age', None) print "Value : %s" % dict.setdefault('Gen', None) Output: Value : 7 Value : None |
9 |
Adds
dictionary dict2's key-values pairs to dict Example: dict = {'Name': 'Zara', 'Age': 7} dict2 = {'Gen': 'female' } dict.update(dict2) print "Value : %s" % dict Output: Value : {'Age': 7, 'Name': 'Zara', 'Sex': 'female'} |
10 |
Returns
list of dictionary dict's values Example: dict = {'Name': 'Zara', 'Age': 7} print "Value : %s" % dict.values() Output: Value : [7, 'Zara'] |
Unit
- III
Functions,
Modules & Packages
1. What is a function in Python?
A. In Python, function is a group of related statements that
perform a specific task. Functions help break our program into smaller and
modular chunks. As our program grows larger and larger, functions make it more
organized and manageable. Furthermore, it avoids repetition and makes code
reusable.
Uses
of Functions:
1. Code re-usability:
Lets say we are writing an application in Python where we need to perform a
specific task in several places of our code, assume that we need to write 10
lines of code to do that specific task. It would be better to write those 10
lines of code in a function and just call the function wherever needed, because
writing those 10 lines every time you perform that task is tedious, it would
make your code lengthy, less-readable and increase the chances of human errors.
2. Improves Readability:
By using functions for frequent tasks you make your code structured and
readable. It would be easier for anyone to look at the code and be able to
understand the flow and purpose of the code.
3. Avoid redundancy:
When you no longer repeat the same lines of code throughout the code and use
functions in places of those, you actually avoiding the redundancy that you may
have created by not using functions.
Advantage
of Functions in Python: There are the following
advantages of Python functions.
v Using functions,
we can avoid rewriting the same logic/code again and again in a program.
v We can call Python
functions multiple times in a program and anywhere in a program.
v We can track a
large Python program easily when it is divided into multiple functions.
v Reusability is the
main achievement of Python functions.
v However, Function
calling is always overhead in a Python program.
Types
of functions:There are two types of functions in
Python:
v User-define functions -
The user-defined functions are those define by the user to
perform the specific task.
v Built-in functions -
The built-in functions are those functions that are pre-defined in
Python.
Syntax of functions in Python:
Function declaration:
def
function_name(function_parameters):
function_body # Set of Python
statements
return # optional return statement
Calling the function:
#
when function doesn't return anything
function_name(parameters)
OR
#
when function returns something
#
variable is to store the returned value
variable
= function_name(parameters)
How Function works in Python?
Python Function Example:
Here we have a function add() that adds two
numbers passed to it as parameters. Later after function declaration we are
calling the function twice in our program to perform the addition.
def
add(num1, num2):
return num1 + num2
sum1
= add(100, 200)
sum2
= add(8, 9)
print(sum1) #300
print(sum2) #17
Default
arguments in Function: Now that we
know how to declare and call a function, lets see how can we use the default
arguments. By using default arguments we can avoid the errors that may
arise while calling a function without passing all the parameters. Lets take an
example to understand this:
In this example we have provided the
default argument for the second parameter, this default argument would be used
when we do not provide the second parameter while calling this function.
#
default argument for second parameter
def
add(num1, num2=1):
return num1 + num2
sum1
= add(100, 200)
sum2
= add(8) # used default argument for
second param
sum3
= add(100) # used default argument for
second param
print(sum1) #300
print(sum2) #9
print(sum3) #101
The return statement
The return statement is used to exit a function
and go back to the place from where it was called.
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 Noneobject.
For example:
print(greet("May"))
Hello,
May. Good morning!
None
Here, None is the returned value.
Example of return
def absolute_value(num):
"""This function returns the absolutevalue of the entered
number"""
if num >= 0:
return num
else:
return -num
# Output: 2
print(absolute_value(2))
# Output: 4
print(absolute_value(-4))
2. Explain
types of User defined Functions in Python?
A. Types of User Defined Functions
in Python:
In real-time, a Python function may
define with or without parameters, and a function may or may not return a
value. It entirely depends upon the user requirement. In this article, we
explain to you the types of functions in Python Programming language with
examples.
In Python programming, as per our
requirement, We can define the User defined functions in multiple ways. The
following are the list of available types of functions in Python.
- Function without argument and without
return value
- Function without argument and
with return value
- Function with argument and without
return value
- Function with argument and with
return value
1. Function without argument
and without return value:In this type of
function in Python, while defining, declaring, or calling the function, We
won’t pass any arguments to the function. This type of Python function won’t
return any value when we call the function.
# Function without argument and without return value
def Adding(): #Called Function
a = 20
b = 30
print("Sum of Two Nums:", a+b)
Adding() #Calling Function
Output: Sum of Two
Nums: 50
2.Function without argument and with return value:In this type of function in the
Python
program, we are going to calculate the multiplication of 2 integer values using
the user defined function without arguments and return keyword.
# Function without argument and with return value
def Multiplication():
a = 10
b = 25
return a*b
print("Product of Two Nums: ", Multiplication())
Output: Product of Two Nums: 250
3. Function with argument
and without return value: If you observe the above 2 types of functions, No matter how many times
you executive, Python gives the same output. We don’t have any control over the
variable values (a, b) because they are fixed values. In real-time, we mostly
deal with dynamic data means we have to allow the user to enter his own values
rather than fixed ones.
This type of function in Python allows us to
pass the arguments to the function while calling the function. But, This type
of function in Python won’t return any value when we call the function.
# Function with argument and without return value
def Multiplications(a, b):
print("Product of Two Nums:", a*b)
Multiplications(10, 20)
Output: Product of Two Nums: 200
4. Function with
argument and with return value:This type of python function allows us to
pass the arguments to the function while calling the function. This type of
functions in Python returns some value when we call the function. This type of
user defined function called a fully dynamic function means it provides maximum
control to the end-user.
# Function with argument and with return value
def Addition(a, b):
Sum = a + b
return Sum
print("Sum of Two Nums:", Addition(25, 45))
Output: Sum of Two Nums:
70
3. Write an example for all User Defined Functions Examples?
A. Example: All User Defined Functions to Shows as follows:
def add(a, b): #fun
with arg with return value
return a + b
def mul(): #fun
without arg without return value
a=int(input("Enter A Value:"))
b=int(input("Enter B Value:"))
print("Product of Two Nums:",a*b)
def subt(x,y): #fun
with arg without return value
print("Subtract of two Nums:",x-y)
def div(): #fun
without arg without return value
a=int(input("Enter A Value:"))
b=int(input("Enter B Value:"))
return
a/b
print("Addition of Two Nums:",add(100,
200));#Calling Functions
mul()
m=int(input("Enter M Value:"))
n=int(input("Enter N Value:"))
subt(m,n)
print("Division of Two
Nums:",div())
4. Explain Anonymous/Lambda Function in Python?
A. The anonymous function, also known as lambda functions.
You'll learn what they are, their syntax and how to use them (with examples).
What are lambda functions in Python?
In Python, an anonymous
function is a function that
is defined without a name.
While normal functions
are defined using the def
keyword
in Python, anonymous functions are defined using the lambda
keyword.Hence, anonymous functions are
also called lambda functions.
Syntax of Lambda
Function in python
lambda arguments: expression
Lambda functions can
have any number of arguments but only one expression. The
expression is evaluated
and returned. Lambda functions can be used wherever function
objects are required.
Example of Lambda
Function in python
Here is an example of
lambda function that doubles the input value.
#Program
to show the use of lambda functions:
double=lambda
x: x*2
print(double(5))
Output:10
In the above
program, lambda x: x * 2
is the
lambda function. Here x is the
argument and x * 2
is the
expression that gets evaluated and returned.
This function has no
name. It returns a function object which is assigned to the identifier double
. We can now call it as a normal function. The
statement
double = lambda x: x * 2
is nearly the same as:
def double(x):
return x * 2
Use of Lambda Function in python
We use lambda functions
when we require a nameless function for a short period of time.
In Python, we generally
use it as an argument to a higher-order function (a function that takes in
other functions as arguments).
Lambda functions are used along with built-in functions like filter()
, map()
etc.
v
Example use with filter(): The filter()
function
in Python takes in a function and a
list as arguments.The function is called with all
the items in the list and a new list is returned which contains items for which
the function evaluates to True
.
Here is an example use
of filter()
function to filter
out only even numbers from a list.
#Program
to filter out only the even items from a list
my_list=[1,5,4,6,8,11,3,12]
new_list=list(filter(lambda(
x: (x%2==0), my_list))
print(new_list)
Output:
[4, 6, 8, 12]
v
Example use with map(): The map()
function
in Python takes in a function and a
list. The function is called with all the items in
the list and a new list is returned which contains items returned by that
function for each item.
Here is an example use
of map()
function to double
all the items in a list.
#Program
to double each item in a list using map()
my_list=[1,5,4,6,8,11,3,12];
new_list=list(map(lambda
x: x*2, my_list))
print(new_list)
Output:
[2, 10, 8, 12, 16, 22, 6, 24]
5. Explain Scope and Lifetime of variables
A. Scope of a variable is the portion of a program where the
variable is recognized. Parameters and variables defined inside a function is
not visible from outside. Hence, they have a local scope.
Lifetime
of a variable is the period throughout which the variable exits in the memory.
The lifetime of variables inside a function is as long as the function
executes.
They
are destroyed once we return from the function. Hence, a function does not
remember the value of a variable from its previous calls.
Here
is an example to illustrate the scope of a variable inside a function.
def my_func(): #called function
x = 10
print("Value inside function:",x)
x
= 20
my_func() #calling function
print("Value
outside function:",x)
Output:
Value
inside function: 10
Value
outside function: 20
6. Explain Recursive Function?
A. A function is
said to be a recursive if it
calls itself. For example, lets say we have a function abc()
and in the body of abc()
there is a call to
the abc()
.
In this example we are
defining a user-defined function factorial()
. This function
finds the factorial of a number by calling itself repeatedly until the base
case is reached.
We use base case in
recursive function so that the function stops calling itself when the base case
is reached. Without the base case, the function would keep calling itself
indefinitely.
Why use
recursion in programming?
We use recursion to break a big problem in small problems and
those small problems into further smaller problems and so on. At the end the
solutions of all the smaller subproblems are collectively helps in finding the
solution of the big main problem.
Advantages of recursion:
1. Easier to
write.
2. Readable – Code is easier to read and understand.
3. Reduce the lines of code – It takes less lines of code to solve a problem
using recursion.
Disadvantages of recursion
1. Not all problems can be solved using recursion.
2. If you don’t define the base case then the code would run indefinitely.
3. Debugging is difficult in recursive functions as the function is calling
itself in a loop and it is hard to understand which call is causing the issue.
4. Memory overhead – Call to the recursive function is not memory efficient.
# Example for recursion function to find the factorial of a given number
def factorial(num):
if num ==0:
return1
else:
return(num * factorial(num -1))
num =int(input(“Enter N Value:”))
print("Factorial of", num,"is: ", factorial(num))
Output:
Factorial of 5is:120
Lets see what happens
in the above example:
factorial(5) returns 5* factorial(5-1)
i.e.5* factorial(4)
|__5*4*factorial(3)
|__5*4*3*factorial(2)
|__5*4*3*2*factorial(1)
#Example for Recursive function to calculate sum of N series
defsum(num):
if num ==0:
return0
else:
return(num +sum(num -1))
num =int(input(“Enter N Value:”))
print("Sum of N Series:",sum(num))
Output:
Enter N Value: 5
Sum of N Series:15
7. What are Python modules?
Modules can be either:
Benefits of modules in Python:
There are a couple of key benefits of creating and using a
module in Python:
Ø Structured
Code
- Code is
logically organized by being grouped into one Python file which makes
development easier and less error-prone.
- Code is
easier to understand and use.
Ø Reusability
Functionality defined in a single module can be easily reused
by other parts of the application. This eliminates the need to recreate
duplicate code.
Modules can be divided
into two types namely:
1. Built in Module
2. User-defined Module
1. Built-in Modules
There are several built-in modules in Python, which you
can import
whenever
you like.
Call a built-in Module
To call a built-in Module and use the function of that module
write:
import moduleName #call a module
moduleName.function()#use module function
import math
print("The value of cosine is", math.cos(30))
print("The value of sine is", math.sin(45))
print("The value of tangent is", math.tan(90))
print("The SquareRoot
Value is", math.sqrt(25))
print("The
Power of a given value is", math.pow(2,4))
print("The value of pi is", math.pi)
2. User-defined Modules
Create a Module
To create a module, create a Python file with a .py
extension.
Call a Module
Modules created with a .py extension can be used in another
Python source file, using the import
statement.
To call this Python module myModule.py, create another
Python file callModule.py file and use the import statement.
import myModule.py
myModule.myFunction(“Python Programming”)
When the above code is executed, the following output is
produced:
callModule.py
myModule.py
def myFunction( parameter ): #define a function in myModule.py
print("Course : ", parameter)
Example for User defined Module:
module1.py #save as module1.py
filename
def
add(num1, num2): #fun with arg with
return value
return num1 + num2
def
mul(): #fun without arg without return
value
a=int(input("Enter A Value:"))
b=int(input("Enter B Value:"))
print("Product of Two Nums:",a*b)
def subt(x,y): #fun
with arg without return value
print("Subtract of two Nums:",x-y)
def div(): #fun
without arg without return value
a=int(input("Enter A Value:"))
b=int(input("Enter B Value:"))
return a/b
import
module1
print("Addition of Two Nums:",module1.add(100,
200));
module1.mul()
m=int(input("Enter M Value:"))
n=int(input("Enter N Value:"))
module1.subt(m,n)
print("Division of Two Nums:",module1.div())
Output:
Addition of Two Nums: 300
Enter A Value:5
Enter B Value:6
Product of Two Nums: 30
Enter M Value:7
Enter N Value:8
Subtract of two Nums: -1
Enter A Value:2
Enter B Value:1
Division of Two Nums: 2.0
8. Explain how to
importing Built in modules and its usage?
A.Python module is
a Python file containing a set of functions and variables to be used in an application.
The variables can be of any type (arrays, dictionaries, objects, etc.)
Modules can be either:
To import modules either may be User defined or System
defined by using import statement.
import
modulename.functionname
(or)
import modulename.*
Build in modules like:
1. Python
- OS Module: It is possible to
automatically perform many operating system tasks. The OS module in Python
provides functions for creating and removing a directory (folder), fetching its
contents, changing and identifying the current directory, etc.
Getting Current Working Directory
v
The getcwd()
:
function confirms returns the current working directory.
Example: Get Current Working Directory
importos
os
.getcwd
()
v Creating a Directory:We can create a new directory using the os.mkdir()
function,
as shown below.Example: Create a Physical Directory
importos
os
.mkdir
("C:\MyPython")
v Changing the Current Working Directory: We must first change the current
working directory to a
newly created one before doing any operations in it. This is done using
the chdir()
function.
The following change current working directory to C:\MyPython
.Example: Change Working Directory
importos
os
.chdir
("C:\MyPython")# changing current working directory
os
.getcwd
()
Example: Change Directory to Drive
os
.chdir
("C:\\")
os
.getcwd
() #'C:\\'
In order to set the
current directory to the parent directory use ".."
as the argument in the chdir()
function.
Example: Change CWD to Parent
os
.chdir
("C:\\MyPython")
os
.getcwd
() #'C:\\MyPython'
os
.chdir
("..")
os
.getcwd
() #'C:\\'
v Removing a Directory: The rmdir()
function
in the OS module removes the
specified directory either
with an absolute or relative path. Note that, for a directory to be removed, it
should be empty.Example: Remove Directory
importos
os
.rmdir
("C:\\MyPython")
However, you can not
remove the current working directory. To remove it, you must change the current
working directory, as shown below.
v List Files and Sub-directories: The listdir()
function returns the list of all files and
directories in the
specified directory.Example: List Directories
importos
os
.listdir
("c:\python37")
If we don't specify any
directory, then list of files and directories in the current working directory
will be returned.
2. Python - Math Module:Some of the most popular mathematical functions are defined in the math
module. These include trigonometric functions, representation functions,
logarithmic functions, angle conversion functions, etc. In addition, two
mathematical constants are also defined in this module.
v
Piand eis a well-known mathematical constant, which is defined as the ratio of
thecircumference to the
diameter of a circle and its value is 3.141592653589793.e is
called Euler's number and it is a base of the natural logarithm. Its value is
2.718281828459045.
Example: Getting Pi Value and e Value
import math
math
.pi
math
.e
v
The math
module contains functions for calculating various trigonometric ratios for
a given angle. The
functions (sin, cos, tan, etc.) need the angle in radians as an argument.
Examples:
import math
math
.radians
(30)
math
.degrees
(math
.pi
/6)
math
.sin
(0.5235987755982988)
math
.cos
(0.5235987755982988)
math
.tan
(0.5235987755982988)
math
.log
(10)
math
.exp
(10)
math
.pow(2,4)
math
.sqrt
(100)
math
.ceil
(4.5867)
math
.floor
(4.5687)
3. Python - Statistics Module:The statistics module provides functions to mathematical statistics of numeric data. The following popular statistical functions are defined in this module.
v Mean: It calculates the
arithmetic mean of the numbers in a list.Example:
import statistics
statistics
.mean
([2,5,6,9]) #5.5
v Median: It returns
the middle value of numeric data in a list.Example:
import statistics
statistics
.median
([1,2,3,8,9]) #3
statistics
.median
([1,2,3,7,8,9]) #5.0
v Mode: It returns the most common
data point in the list.Example:
import statistics
statistics
.mode
([2,5,3,2,8,3,9,4,2,5,6]) #2
v Standard Deviation: The stdev()
method
calculates the standard deviation on a given sample in the form of a list.Example:
import statistics
statistics
.stdev
([1,1.5,2,2.5,3,3.5,4,4.5,5])
1.3693063937629153
4.Python - Random Module: The random
module is a
built-in module to generate the pseudo-random variables. It can be used perform
some action randomly such as to get a random number, selecting a random elements
from a list, shuffle elements randomly, etc.
Generate Random Floats
v
The random.random()
method returns a random float number between
0.0 to 1.0.
The function doesn't need
any arguments.Example:
random()
import random
random
.random
() #0.645173684807533
v Generate Random Integers: It returns a randominteger between the specified
integers.Example: randint()
import random
random
.randint
(1,100) #95
random
.randint
(1,100) #49
v
Generate Random Numbers within Range: It returns a randomly selected
element
from the range created by
the start, stop and step arguments. The value of start is 0 by default.
Similarly, the value of step is 1 by default.Example:
random
.randrange
(1,10) #2
random
.randrange
(1,10,2) #5
v Select Random Elements: It returns a randomly selected element from a non-
empty sequence. An empty
sequence as argument raises an IndexError.Example:
import random
random
.choice
('computer') #'t'
random
.choice
([12,23,45,67,65,43]) #45
random
.choice
((12,23,45,67,65,43)) #67
Shuffle Elements Randomly:It randomly reorders the elements in a list.Example:
numbers
=[12,23,45,67,65,43]
random
.shuffle
(numbers
)
numbers #
[23,12,43,65,67,45]
random
.shuffle
(numbers
)
numbers #
[23,43,65,45,12,67]
9. What is a Package? Explain its usage in python.
A. Create and Access a
Python Package: Packages are a way
of structuring many packages and modules which helps in a well-organized
hierarchy of data set, making the directories and modules easy to access. Just
like there are different drives and folders in an OS to help us store files,
similarly packages help us in storing other sub-packages and modules, so that
it can be used by the user when necessary.
Creating
and Exploring Packages:
To
tell Python that a particular directory is a package, we create a file named
__init__.py
inside it and then it is considered as a package and we
may create other modules and sub-packages within it. This __init__.py file can
be left blank or can be coded with the initialization code for the package.
To create a package in Python, we need to follow these three simple steps:
1.
First, we create
a directory and give it a package name, preferably related to its operation.
2.
Then we put the
classes and the required functions in it.
3.
Finally we
create an __init__.py file inside the directory, to let Python know that the
directory is a package.
Example of Creating Package
Let’s look at this example and see how a package is
created. Let’s create a package named Cars and build three modules in it
namely, Bmw, Audi and Nissan.
1.
First we create a directory and name it Cars.
2.
Then we need to create modules. To do this we need to create a file with the name Bmw.py
and create its content by putting this code into it.
# Python code to illustrate the Modules
class Bmw:
# First we create a constructor for
this class and add members to it, here models
def __init__(self):
self.models
= ['i8', 'x1', 'x5', 'x6']
# A normal print
function
def outModels(self):
print('These
are the available models for BMW')
for model in
self.models:
print('\t%s
' % model)
3.
Then we create
another file with the name Audi.py and add the similar type of code to it with
different members.
# Python code to illustrate the Module
class Audi:
# First we create a constructor for
this class and add members to it, here models
def __init__(self):
self.models
= ['q7', 'a6', 'a8', 'a3']
# A normal print function
def outModels(self):
print('These
are the available models for Audi')
for model in
self.models:
print('\t%s
' % model)
4. Then we create another file with the name Nissan.py and
add the similar type of code to it with different members.
# Python code to illustrate the Module
class Nissan:
# First we create a constructor for
this class and add members to it, here models
def __init__(self):
self.models
= ['altima', '370z', 'cube', 'rogue']
# A normal print
function
def outModels(self):
print('These
are the available models for Nissan')
for model in
self.models:
print('\t%s
' % model)
5. Finally we create the __init__.py file. This file will be placed inside
Cars directory and can be left blank or we can put this initialisation code
into it.
from Bmw import Bmw
from Audi import Audi
from Nissan import Nissan
Now, let’s use the package that we created. To do this
make a sample.py file in the same directory where Cars package is located and
add the following code to it:
# Import classes from your brand new package
from Cars import Bmw
from Cars import Audi
from Cars import Nissan
# Create an object of Bmw class & call its method
ModBMW = Bmw()
ModBMW.outModels()
# Create an object of Audi class & call its method
ModAudi = Audi()
ModAudi.outModels()
# Create an object of Nissan class & call its method
ModNissan = Nissan()
ModNissan.outModels()
Various
ways of Accessing the Packages
Let’s
look at this example and try to relate packages with it and how can we access
it.
Suppose the cars and the brand directories are
packages. For them to be a package they all must contain __init__.py file in
them, either blank or with some initialization code. Let’s assume that all the
models of the cars to be modules. Use of packages helps importing any modules,
individually or whole.
Suppose we want to get Bmw i5. The syntax for
that would be:
'import'
Cars.Bmw.x5
While importing a package or sub packages or modules,
Python searches the whole tree
of directories looking for the particular package and
proceeds systematically as programmed by the dot operator.
If any module contains a function and we want to import that. For e.g., a8 has
a function get_buy(1) and we want to import that, the syntax would be:
1. import Cars.Audi.a8
2. Cars.Audi.a8.get_buy(1)
While using just the import syntax, one must keep in mind
that the last attribute must be a
subpackage or a module, it should not be any function or
class name.
‘from…import’ in Packages
Now, whenever we require using such function we would need to write the whole
long line after importing the parent package. To get through this in a simpler
way we use ‘from’ keyword. For this we first need to bring in the module using
‘from’ and ‘import’:
from Cars.Audi import a8
Now
we can call the function anywhere using
a8.get_buy(1)
There’s
also another way which is less lengthy. We can directly import the function and
use
it
wherever necessary. First import it using:
from Cars.Audi.a8 import get_buy
Now
call the function from anywhere:
get_buy(1)
‘from…import *’ in Packages
While using the from…import syntax, we can import anything from submodules
to class or function or variable, defined in the same module. If the mentioned
attribute in the import part is not defined in the package then the compiler
throws an ImportError exception.
Importing sub-modules might cause unwanted
side-effects that happens while importing sub-modules explicitly. Thus we can
import various modules at a single time using * syntax. The syntax is:
from
Cars.Chevrolet import *
This will import everything i.e.,
modules, sub-modules, function, classes, from the sub-package.
10. Explain Composition
in Python.
A. It
is one of the important concepts of Object-oriented programming (OOPs).
Composition basically enables us for creating complex types objects by
combining other types of objects in the program. Composition represents ‘has a
relationship’ type or we can call composition as ‘has a relationship’ in the
OOPs concept. It means that a composite class present in the program can
contains the objects from the other class components and this type of
relationship model is called as has a relationship.
Give an example
of Composition in Python
In composition one of the classes is
composed of one or more instance of other classes. In other words one class is
container and other class is content and if you delete the container object
then all of its contents objects are also deleted.
Note:In
the above figure Classes are represented as boxes with the class name Composite and Component representing Has-A relation between
both of them.
def
__init__(self, pay):
self.pay = pay
def
get_total(self):
return
(self.pay*12)
class
Employee:
def
__init__(self, pay, bonus):
self.pay = pay
self.bonus = bonus
self.obj_salary = Salary(self.pay)
def
annual_salary(self):
return
"Total: " + str(self.obj_salary.get_total() + self.bonus)
obj_emp
= Employee(600, 500)
print(obj_emp.annual_salary())
Output: Total: 7700
Unit
–IV
Input-Output &
Exception Handling
1. Explain Input and
Output in Python
A. Input
Statement:Up
till now, our programs were static. The value of variables were defined or hard
coded into the source code.
To
allow flexibility we might want to take the input from the user. In Python, we
have the input() function to allow this. The syntax
for input() is
input([prompt])
where prompt is
the string we wish to display on the screen. It is optional.
>>>num = input('Enter a number: ')
Enter a number: 10
>>>num
'10'
How to Take Input from User in Python: Sometimes a
developer might want to take user input at some point in the program. To do
this Python provides an input() function.
Syntax:input('prompt')
where prompt is an
optional string that is displayed on the string at the time of taking input.
Example 1:# Taking input from the user
name =input("Enter your name: ") #
Enter your name: Rama
print("Hello, "+name) #
Hello, Rama
print(type(name))
#<class 'str'>
Note: Python takes all the input as a
string input by default. To convert it to any other data type we have to
convert the input explicitly. For example, to convert the input to int or float
we have to use the int() and float() method
respectively.
Example 2: Integer input in Python
num =int(input("Enter a number: ")) #
Enter a number: 25
add =num +1
print(add) #26
Output Statement:We use the print()
function to output data to the
standard output device (screen).We can also output
data to a file, An
example use is given below.
print('This sentence is output to the
screen')
Example1:
a = 5
print('The value of a is', a)# Output: The
value of a is 5
Example 2:
print(1,2,3,4) # Output: 1 2 3 4
Example 3:
print (1,2,3,4,sep='*') # Output: 1*2*3*4
Example 4:
print(1,2,3,4,sep='#',end='&') # Output: 1#2#3#4&
Example
5:
We can even use keyword arguments to
format the string.
>>>print('Hello {name}, {greeting}'.format(greeting ='Goodmorning', name ='John'))
HelloJohn,Goodmorning
Example 6:
We can even format strings like the
old printf()
style
used in C
programming language.
We use the %
operator
to accomplish this.
>>> x =12.3456789
>>>print('The value of x is %3.2f'%x)
The value of x is12.35
>>>print('The value of x is %3.4f'%x)
The value of x is12.3457
Using
% Operator
We can
use ‘%’ operator. % values are replaced with zero or
more value of elements. The formatting using % is similar to that of ‘printf’
in the C programming language.
·
%d – integer
·
%f – float
·
%s – string
·
%x – hexadecimal
·
%o – octal
Example:
|
Output:
Enter a value: 50
The sum is 55
2. Explain File Handling
in Python
A. Till now, we were taking the input
from the console and writing it back to the console to interact with the user.
Sometimes, it is
not enough to only display the data on the console. The data to be displayed
may be very large, and only a limited amount of data can be displayed on the
console, and since the memory is volatile, it is impossible to recover the
programmatically generated data again and again.
However, if we
need to do so, we may store it onto the local file system which is volatile and
can be accessed every time. Here, comes the need of file handling.
In this section of
the tutorial, we will learn all about file handling in python including,
creating a file, opening a file, closing a file, writing and appending the
file, etc.
1. Opening a file: Python provides the open() function which accepts
two arguments, file name and access mode in which the file is accessed. The
function returns a file object which can be used to perform various operations
like reading, writing, etc.
file object = open(<file-name>, <access-mode>, <buffering>)
The files can be
accessed using various modes like read, write, or append. The following are the
details about the access mode to open a file.
Sno |
Access mode |
Description |
1 |
r |
It opens the
file to read-only. The file pointer exists at the beginning. |
2 |
rb |
It opens the
file to read only in binary format. |
3 |
r+ |
It opens the
file to read and write both. |
4 |
rb+ |
It opens the
file to read and write both in binary format. |
5 |
w |
It opens the
file to write only. It overwrites the file if previously exists or creates a
new one if no file exists with the same name. |
6 |
wb |
It opens the
file to write only in binary format. It overwrites the file if it exists
previously or creates a new one if no file exists with the same name. |
7 |
w+ |
It opens the
file to write and read both. It is different from r+ in the sense that it
overwrites the previous file if one exists whereas r+ doesn't overwrite the
previously written file. |
8 |
wb+ |
It opens the
file to write and read both in binary format. |
9 |
a |
It opens the
file in the append mode. The file pointer exists at the end of the previously
written file if exists any. It creates a new file if no file exists with the
same name. |
10 |
ab |
It opens the
file in the append mode in binary format. The pointer exists at the end of
the previously written file. It creates a new file in binary format if no
file exists with the same name. |
11 |
a+ |
It opens a file
to append and read both. The file pointer remains at the end of the file if a
file exists. |
12 |
ab+ |
It opens a file
to append and read both in binary format. The file pointer remains at the end
of the file. |
Let's
look at the simple example to open a file named "file.txt" (stored in
the same directory) in read mode and printing its content on the console.
Example
#opens the file file.txt in read mode
fileptr = open("file.txt","r")
if fileptr:
print("file is opened successfully")
Output:file is opened successfully
2.The close(): Once all the
operations are done on the file, we must close it through our python script
using the close() method. Any unwritten information gets destroyed once the
close() method is called on a file object.
We can perform any
operation on the file externally in the file system is the file is opened in
python, hence it is good practice to close the file once all the operations are
done.
Example
# opens the file file.txt in read mode
fileptr = open("file.txt","r")
if fileptr:
print("file is opened successfully")
#closes the opened file
fileptr.close()
3. Reading the
file: To
read a file using the python script, the python provides us the read() method.
The read() method reads a string from the file. It can read the data in the
text as well as binary format.The syntax of the read() method is given below.
fileobj.read(<count>)
Here,
the count is the number of bytes to be read from the file starting from the
beginning of the file. If the count is not specified, then it may read the
content of the file until the end.
Consider the following
Example:
#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("file.txt","r");
#stores all the data of the file into the variable content
content = fileptr.read(9);
# prints the type of the data stored in the file
print(type(content))
#prints the content of the file
print(content)
#closes the opened file
fileptr.close()
Output:
<class 'str'>
Hi, I am
4.
Read Lines of the file:Python
facilitates us to read the file line by line by using a function readline().
The readline() method reads the lines of the file from the beginning, i.e., if
we use the readline() method two times, then we can get the first two lines of
the file.
Consider the following example
which contains a function readline() that reads the first line of our file "file.txt" containing three
lines.
Example:
.close()#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("file.txt","r");
#stores all the data of the file into the variable content
content = fileptr.readline();
# prints the type of the data stored in the file
print(type(content))
#prints the content of the file
print(content)
#closes the opened file
fileptr
Output:
<class 'str'>
Hi, I am the file and being used as
5.
Looping through the file:By looping
through the lines of the file, we can read the whole file.
Example:
#open the file.txt in read mode. causes an error if no such file exists.
fileptr = open("file.txt","r");
#running a for loop
for i in fileptr:
print(i) # i contains each line of the file
Output:
Hi, I am the file and being used as
an example to read a
file in python.
6.
Writing the file:To write some text
to a file, we need to open the file using the open method with one of the
following access modes.
Ø
a: It will append the
existing file. The file pointer is at the end of the file. It creates a new
file if no file exists.
Ø
w: It will overwrite the
file if any file exists. The file pointer is at the beginning of the file.
Consider the following example.
Example
1
#open the file.txt in append mode. Creates a new file if no such file exists.
fileptr = open("file.txt","a");
#appending the content to the file
fileptr.write("Python is the modern day language. It makes things so simple.")
#closing the opened file
fileptr.close();
Now, we can see that the content of
the file is modified.
File.txt:
Hi, I am the file and being used as
an example to read a
file in python.
Python is the modern day language. It makes things so simple.
Example
2
#open the file.txt in write mode.
fileptr = open("file.txt","w");
#overwriting the content of the file
fileptr.write("Python is the modern day language. It makes things so simple.")
#closing the opened file
fileptr.close();
Now, we can check that all the
previously written content of the file is overwritten with the new text we have
passed.
File.txt:
Python is the modern day language. It makes things so simple.
7.
Creating a new file:The new file can
be created by using one of the following access modes with the function open().
Ø x: it creates a new file with the
specified name. It causes an error a file exists with the same name.
Ø a: It creates a new file
with the specified name if no such file exists. It appends the content to the
file if the file already exists with the specified name.
Ø w: It creates a new file
with the specified name if no such file exists. It overwrites the existing
file.
Consider the following example.
Example
#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("file2.txt","x");
print(fileptr)
if fileptr:
print("File created successfully");
Output:
File created successfully
8.
Using with statement with files: The with statement was introduced in python 2.5. The
with statement is useful in the case of manipulating the files. The with
statement is used in the scenario where a pair of statements is to be executed
with a block of code in between.
The syntax to open a file using
with statement is given below.
with open(<file name>, <access mode>) as <file-pointer>:
#statement suite
The advantage of using with
statement is that it provides the guarantee to close the file regardless of how
the nested block exits.
Cnsider the following example.
Example:
with open("file.txt",'r') as f:
content = f.read();
print(content)
Output:
Python is the modern day language. It makes things so simple.
9.
File Pointer positions: Python provides
the tell() method which is used to print the byte number at which the file
pointer exists. Consider the following example.
Example:
# open the file file2.txt in read mode
fileptr = open("file2.txt","r")
#initially the filepointer is at 0
print("The filepointer is at byte :",fileptr.tell())
#reading the content of the file
content = fileptr.read();
#after the read operation file pointer modifies. tell() returns the location of the fileptr.
print("After reading, the filepointer is at:",fileptr.tell())
Output:
The filepointer is at byte : 0
After reading, the filepointer is at 26
10.
Modifying file pointer position: In the real world applications, sometimes we need to
change the file pointer location externally since we may need to read or write
the content at various locations.For this purpose, the python provides us the
seek() method which enables us to modify the file pointer position externally.
The syntax to use the seek() method
is given below.
<file-ptr>.seek(offset[, from)
The seek() method accepts two
parameters:
offset: It refers to the new
position of the file pointer within the file.
from: It indicates the
reference position from where the bytes are to be moved. If it is set to 0, the
beginning of the file is used as the reference position. If it is set to 1, the
current position of the file pointer is used as the reference position. If it
is set to 2, the end of the file pointer is used as the reference position.
Consider the following example.
Example:
# open the file file2.txt in read mode
fileptr = open("file2.txt","r")
#initially the filepointer is at 0
print("The filepointer is at byte :",fileptr.tell())
#changing the file pointer location to 10.
fileptr.seek(10);
#tell() returns the location of the fileptr.
print("After reading, the filepointer is at:",fileptr.tell())
Output:
The filepointer is at byte : 0
After reading, the filepointer is at 10
The
file related methods:
The file object provides the
following methods to manipulate the files on various operating systems.
SN |
Method |
Description |
1 |
file.close() |
It closes the
opened file. The file once closed, it can't be read or write any more. |
2 |
File.flush() |
It flushes the
internal buffer. |
3 |
File.fileno() |
It returns the
file descriptor used by the underlying implementation to request I/O from the
OS. |
4 |
File.isatty() |
It returns true
if the file is connected to a TTY device, otherwise returns false. |
5 |
File.next() |
It returns the
next line from the file. |
6 |
File.read([size]) |
It reads the
file for the specified size. |
7 |
File.readline([size]) |
It reads one
line from the file and places the file pointer to the beginning of the new
line. |
8 |
File.readlines([sizehint]) |
It returns a
list containing all the lines of the file. It reads the file until the EOF
occurs using readline() function. |
9 |
File.seek(offset[,from) |
It modifies the
position of the file pointer to a specified offset with the specified
reference. |
10 |
File.tell() |
It returns the
current position of the file pointer within the file. |
11 |
File.truncate([size]) |
It truncates the
file to the optional specified size. |
12 |
File.write(str) |
It writes the
specified string to a file |
13 |
File.writelines(seq) |
It writes a
sequence of the strings to a file. |
3.
What is an Exception Handling in Python?
An exception is an error which happens at the time of
execution of a program. However, while running a program, Python generates an
exception that should be handled to avoid your program to crash. In Python
language, exceptions trigger automatically on errors, or they can be triggered
and intercepted by your code.
The exception indicates that, although the event can
occur, this type of event happens infrequently. When the method is not able to
handle the exception, it is thrown to its caller function. Eventually, when an
exception is thrown out of the main function, the program is terminated
abruptly.
Common
Examples of Exception:
v Division
by Zero
v Accessing
a file which does not exist.
v Addition
of two incompatible types
v Trying
to access a nonexistent index of a sequence
v Removing
the table from the disconnected database server.
v ATM
withdrawal of more than the available amount
Why
should you use Exceptions?
Here are the reasons for using exceptions in Python:
v Exception
handling allows you to separate error-handling code from normal code.
v An
exception is a Python object which represents an error.
v As
with code comments, exceptions helps you to remind yourself of what the program
expects.
v It
clarifies the code and enhances readability.
v Allows
you to stimulate consequences as the error-handling takes place at one place
and in one manner.
v An
exception is a convenient method for handling error messages.
v In
Python, you can raise an exception in the program by using the raise exception
method.
v Raising
an exception helps you to break the current code execution and returns the
exception back to exception until it is handled.
v Processing
exceptions for components which can’t handle them directly.
Rules
of Exceptions
Here are some essential rules of Python exception
handling:
v Exceptions
must be class objects
v For
class exceptions, you can use try statement with an except clause which
mentions a particular class.
v Even
if a statement or expression is syntactically correct, it may display an error
when an attempt is made to execute it.
v Errors
found during execution are called exceptions, and they are not unconditionally
fatal.
Python
Exception Handling Mechanism
Exception handling is managed by the following 5
keywords:
- try
- catch
- finally
- throw
1. Python Try Statement: A try statement includes keyword try, followed by a
colon (:) and a suite of code in which exceptions may occur. It has one or more
clauses.
During the execution of the try statement, if
no exceptions occurred then, the interpreter ignores the exception handlers for
that specific try statement.
In case, if any exception occurs in a try
suite, the try suite expires and program control transfers to the matching
except handler following the try suite.
Syntax:
try:
statement(s)
2. The catch Statement:
Catch blocks take one
argument at a time, which is the type of exception that it is likely to catch.
These arguments may range from a specific type of exception which can be varied
to a catch-all category of exceptions.
Rules
for catch block:
v You can define a catch block by using the
keyword catch
v Catch Exception parameter is always enclosed
in parentheses
v It always represents the type of exception
that catch block handles.
v An exception handling code is written between
two {} curly braces.
v You can place multiple catch block within a
single try block.
v You can use a catch block only after the try
block.
v All the catch block should be ordered from
subclass to superclass exception.
Example:
try
{
}
catch (ArrayIndexOutOfBoundsException e)
{
System.err.printin("Caught first " +
e.getMessage());
}
catch (IOException e)
{
System.err.printin("Caught second "
+ e.getMessage());
}
3. Finally Statement
in Python: Finally block always
executes irrespective of an exception being thrown or not. The final keyword
allows you to create a block of code that follows a try-catch block.Finally,
clause is optional. It is intended to define clean-up actions which should be
that executed in all conditions.
try:
raise KeyboardInterrupt
finally:
print 'welcome, world!'
Output:
Welcome, world!
KeyboardInterrupt
Finally, clause is executed before try
statement.
4. Raise Statement in
Python: The raise statement
specifies an argument which initializes the exception object. Here, a comma
follows the exception name, and argument or tuple of the argument that follows
the comma.
Syntax:raise [Exception [, args [, traceback]]]
List
of Standard Exceptions:
Sr.No. |
Exception
Name & Description |
1 |
Exception: Base class for all exceptions |
2 |
StopIteration: Raised when the next() method of an iterator
does not point to any object. |
3 |
SystemExit: Raised by the sys.exit() function. |
4 |
ArithmeticError: Base class for all errors that occur for numeric calculation. |
5 |
OverflowError: Raised when a calculation exceeds maximum
limit for a numeric type. |
6 |
FloatingPointError: Raised when a floating point calculation
fails. |
7 |
ZeroDivisionError: Raised when division or modulo by zero takes
place for all numeric types. |
8 |
EOFError: Raised when there is no input from either the
raw_input() or input() function and the end of file is reached. |
9 |
IndexError: Raised
when an index is not found in a sequence. |
10 |
lIOError: Raised when an input/ output operation fails,
such as the print statement or the open() function when trying to open a file
that does not exist. |
#import
module sys to get the type of exception
import
sys
randomList=[‘a’,0,2]
for
entry in randomList:
try:
print(“The entry
is”,entry)
r=1/int(entry)
break
except:
print(“Oops!”,sys.exce_info()[0],”Occurred”)
print(“Next entry”)
print()
print(“The
reciprocal of”,entry,”is”,r)
Output:
The entry is a
Oops! <class 'ValueError'> occurred.
Next entry.
The entry is 0
Oops! <class 'ZeroDivisionError'> occured.
Next entry.
The entry is 2
The reciprocal of 2 is 0.5
Example:
defdivide(x, y):
... try:
... result = x / y
... exceptZeroDivisionError:
... print("division by
zero!")
... else:
... print("result is", result)
... finally:
... print("executing
finally clause")
Unit –V
1. Explain Basic Oops Concepts in Python?
A.Python OOPs Concepts: Like other general-purpose
programming languages, Python is also an object-oriented language since its
beginning. It allows us to develop applications using an Object-Oriented
approach. In Python, we can easily create and use classes and objects.
An object-oriented paradigm is
to design the program using classes and objects. The object is related to
real-word entities such as book, house, pencil, etc. The Oops concept focuses
on writing the reusable code. It is a widespread technique to solve the problem
by creating objects.
Major principles of object-oriented programming system are given
below.
1.
Class: The class can be
defined as a collection of objects. It is a logical entity that has some specific
attributes and methods. For example: if you have an employee class, then it
should contain an attribute and method, i.e. an email id, name, age, salary,
etc.
Syntax:
class ClassName:
<statement-1>
.
.
<statement-N>
2. Object:The
object is an entity that has state and behavior. It may be any real-world
object like the mouse, keyboard, chair, table, pen, etc.
Everything in Python is an object, and
almost everything has attributes and methods. All functions have a built-in
attribute __doc__, which returns the docstring defined in the function source
code.
When we define a class, it needs to
create an object to allocate the memory. Consider the following example.
Example:
class car:
def __init__(self,modelname, year):
self.modelname = modelname
self.year = year
def display(self):
print(self.modelname,self.year)
c1 = car("Toyota", 2016)
c1.display()
3. Method:The method is a function that is associated
with an object. In Python, a method is not unique to class instances. Any
object type can have methods.
4. Inheritance:Inheritance is the most important
aspect of object-oriented programming, which simulates the real-world concept
of inheritance. It specifies that the child object acquires all the properties
and behaviours of the parent object.
By
using inheritance, we can create a class which uses all the properties and
behaviour of another class. The new class is known as a derived class or child
class, and the one whose properties are acquired is known as a base class or
parent class.
It
provides the re-usability of the code.
5. Polymorphism:Polymorphism contains two words
"poly" and "morphs". Poly means many, and morph means
shape. By polymorphism, we understand that one task can be performed in
different ways. For example - you have a class animal, and all animals speak.
But they speak differently. Here, the "speak" behaviour is
polymorphic in a sense and depends on the animal. So, the abstract
"animal" concept does not actually "speak", but specific
animals (like dogs and cats) have a concrete implementation of the action
"speak".
6. Encapsulation:Encapsulation is also an
essential aspect of object-oriented programming. It is used to restrict access
to methods and variables. In encapsulation, code and data are wrapped together
within a single unit from being modified by accident.
7. Data Abstraction:Data abstraction and encapsulation both are often used
as synonyms. Both are nearly synonyms because data abstraction is achieved
through encapsulation.
Abstraction is
used to hide internal details and show only functionalities. Abstracting
something means to give names to things so that the name captures the core of
what a function or a whole program does.
2. Differences between Oops and Pops
A.Object-oriented vs. Procedure-oriented Programming languages
The difference between object-oriented and
procedure-oriented programming is given below:
Sno |
Object-oriented Programming |
Procedural Programming |
1. |
Object-oriented
programming is the problem-solving approach and used where computation is
done by using objects. |
Procedural
programming uses a list of instructions to do computation step by step. |
2. |
It makes the
development and maintenance easier. |
In procedural
programming, It is not easy to maintain the codes when the project becomes
lengthy. |
3. |
It simulates the
real world entity. So real-world problems can be easily solved through oops. |
It doesn't simulate
the real world. It works on step by step instructions divided into small
parts called functions. |
4. |
It provides data
hiding. So it is more secure than procedural languages. You cannot access
private data from anywhere. |
Procedural language
doesn't provide any proper way for data binding, so it is less secure. |
5. |
Example of
object-oriented programming languages is C++, Java, .Net, Python, C#, etc. |
Example of
procedural languages are: C, Fortran, Pascal, VB etc. |
3. Explain Class and Object in Python with
Example?
A. Python
Classes/Objects: Python is an object oriented
programming language.Almost everything in Python is an object, with its
properties and methods.A Class is like an object constructor, or a
"blueprint" for creating objects.
Create
a Class: To create a
class, use the keyword class:
Example:
Create a class
named MyClass, with a property named x:
class MyClass:
x = 5
The __init__() Function: The examples above are classes
and objects in their simplest form, and are not really useful in real life
applications.To understand the meaning of classes we have to understand the
built-in __init__() function.All classes have a function called __init__(),
which is always executed when the class is being initiated.Use the __init__()
function to assign values to object properties, or other operations that are
necessary to do when the object is being created:
Example: Create a class named Person, use the __init__()
function to assign values for name and age:
class Person:
def __init__(self, name, age):
self.name =
name
self.age = age
p1 = Person("SriRama", 36)
print(p1.name)
print(p1.age)
Object Methods: Objects can also contain methods. Methods in objects
are functions that belongs to the object.Let us create a method in the Person
class:
Example:
Insert a
function that prints a greeting, and execute it on the p1 object:
class Person:
def __init__(self, name, age):
self.name =
name
self.age = age
def myfunc(self):
print("Hello my name is
" + self.name)
p1 = Person("John", 36)
p1.myfunc()
The self-Parameter: The self
-parameter
is a reference to the current instance of the class, and is used to access
variables that belong to the class.It does not have to be named self
,
you can call it whatever you like, but it has to be the first parameter of any
function in the class:
Example:
Use the words mysillyobject and abc instead of self:
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name
= name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is
" + abc.name)
p1 = Person("John", 36)
p1.myfunc()
Modify Object Properties: You can modify properties on
objects like this:
Example:
Set the age of p1 to 40:
p1.age = 40
Delete Object Properties: You can delete properties on
objects by using the del
keyword:
Example:
Delete the age
property from the p1 object:
del p1.age
Delete Objects: You can delete objects by using the del
keyword:
Example:
Delete the p1
object:
del p1
4. Explain built
in class Attributes?
A. Python In-built class functions: The in-built functions defined in
the class are described in the following table.
SN |
Function |
Description |
1 |
getattr(obj,name,default) |
It is used to
access the attribute of the object. |
2 |
setattr(obj,
name,value) |
It is used to
set a particular value to the specific attribute of an object. |
3 |
delattr(obj,
name) |
It is used to
delete a specific attribute. |
4 |
hasattr(obj,
name) |
It returns true
if the object contains some specific attribute. |
Example:
class Student:
def __init__(self,name,id,age):
self.name = name;
self.id = id;
self.age = age
#creates the object of the class Student
s = Student("John",101,22)
#prints the attribute name of the object s
print(getattr(s,'name')) # John
# reset the value of attribute age to 23
setattr(s,"age",23)
# prints the modified value of age
print(getattr(s,'age')) #23
# prints true if the student contains the attribute with name id
print(hasattr(s,'id')) # True
# deletes the attribute age
delattr(s,'age')
# this will give an error since the attribute age has been deleted
print(s.age) #AttributeError: 'Student' object has no attribute 'age'
Built-in class attributes: Along with the other attributes, a python class also contains some
built-in class attributes which provide information about the class.The
built-in class attributes are given
in the below
table.
SN |
Attribute |
Description |
1 |
__dict__ |
It provides the
dictionary containing the information about the class namespace. |
2 |
__doc__ |
It contains a string
which has the class documentation |
3 |
__name__ |
It is used to
access the class name. |
4 |
__module__ |
It is used to
access the module in which, this class is defined. |
5 |
__bases__ |
It contains a
tuple including all base classes. |
Example:
class Student:
def __init__(self,name,id,age):
self.name = name;
self.id = id;
self.age = age
def display_details(self):
print("Name:%s, ID:%d, age:%d"%(self.name,self.id,self.age))
s = Student("John",101,22)
print(s.__doc__) #None
print(s.__dict__) #{'name': 'John',
'id': 101, 'age': 22}
print(s.__module__) #__main__
5.
What is Inheritance? Explain types of Inheritance.
A. Inheritance is
an important aspect of the object-oriented paradigm. Inheritance provides code
reusability to the program because we can use an existing class to create a new
class instead of creating it from scratch.
In inheritance, the child class acquires the properties and
can access all the data members and functions defined in the parent class. A
child class can also provide its specific implementation to the functions of
the parent class. In this section of the tutorial, we will discuss inheritance
in detail.
In python, a derived class can inherit base class by just
mentioning the base in the bracket after the derived class name. Consider the
following syntax to inherit a base class into the derived class.
Syntax:
class derived-class(base class):
<class-suite>
A class can inherit multiple classes by mentioning all of
them inside the bracket. Consider the following syntax.
Syntax:
class derive-class(<base class 1>, <base class 2>, ..... <base class n>):
<class - suite>
Example (Single Inheritance)
class Animal:
def speak(self):
print("Animal Speaking")
#child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
d.bark()
d.speak()
Output:
dog barking
Animal Speaking
Python Multi-Level inheritance: Multi-Level inheritance is
possible in python like other object-oriented languages. Multi-level
inheritance is archived when a derived class inherits another derived class.
There is no limit on the number of levels up to which, the multi-level
inheritance is archived in python.The syntax of multi-level inheritance is
given below.
Syntax
class class1:
<class-suite>
class class2(class1):
<class suite>
class class3(class2):
<class suite>
.
Example (Multilevel inheritance)
class Animal:
def speak(self):
print("Animal Speaking")
#The child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
#The child class Dogchild inherits another child class Dog
class DogChild(Dog):
def eat(self):
print("Eating bread...")
d = DogChild()
d.bark() # dog barking
d.speak() # Animal Speaking
d.eat() # Eating bread...
Python Multiple inheritance: Python provides us the
flexibility to inherit multiple base classes in the child class.The syntax to
perform multiple inheritances is given below.
Syntax:
class Base1:
<class-suite>
class Base2:
<class-suite>
.
.
<class-suite>
class Derived(Base1, Base2, ...... BaseN):
<class-suite>
Example (Multiple Inheritance)
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(d.Summation(10,20)) #30
print(d.Multiplication(10,20)) #200
print(d.Divide(10,20)) #0.5
6. What is method
overloading in Python?
A. Methods in Python can be called with zero, one, or more parameters. This
process of calling the same method in different ways is called method overloading. It is one of the important
concepts in OOP. Two methods cannot have the same name in Python; hence method
overloading is a feature that allows the same operator to have different
meanings.
Method overloading…
v reduces complexities
v improves the quality of
the code
v
is also used for reusability and easy accessibility
Example:
class Compute:
# area method
def area(self, x = None, y = None):
if x != None and y != None:
return x * y
elif x != None:
return x * x
else:
return 0
obj = Compute() # object
print("Area Value:", obj.area()) # zero argumentà0
print("Area Value:", obj.area(4)) # one argumentà16
print("Area Value:", obj.area(3, 5)) # two argument à15
7. Explain Method Overriding with
Example.
A. We can provide
some specific implementation of the parent class method in our child class.
When the parent class method is defined in the child class with some specific
implementation, then the concept is called method overriding. We may need to
perform method overriding in the scenario where the different definition of a
parent class method is needed in the child class.
Consider the following example to perform method overriding
in python.
Example:
class Animal:
def speak(self):
print("speaking")
class Dog(Animal):
def speak(self):
print("Barking")
d = Dog()
d.speak() #Output: Barking
Real Life Example of method
overriding
Example:
class Bank:
def getroi(self):
return 10;
class SBI(Bank):
def getroi(self):
return 7;
class ICICI(Bank):
def getroi(self):
return 8;
b1 = Bank()
b2 = SBI()
b3 = ICICI()
print("Bank Rate of interest:",b1.getroi()); # Bank Rate of interest: 10
print("SBI Rate of interest:",b2.getroi()); # SBI Rate of interest: 7
print("ICICI Rate of interest:",b3.getroi()); # ICICI Rate of interest: 8
8. What is Data Hiding give with
an Example?
A. Data hiding is
a part of object-oriented programming, which is generally used to hide the data
information from the user. It includes internal object details such as data
members, internal working. It maintained the data integrity and restricted
access to the class member. The main working of data hiding is that it combines
the data and functions into a single unit to conceal data within a class. We
cannot directly access the data from outside the class.
This process is also known as the data
encapsulation. It is done by hiding the working information to
user. In the process, we declare class members as private so that no other
class can access these data members. It is accessible only within the class.
We can perform data hiding in Python using the __ double
underscore before prefix. This makes the class members private and inaccessible
to the other classes.
Example -
class CounterClass:
__privateCount = 0
def count(self):
self.__privateCount += 1
print(self.__privateCount)
counter = CounterClass()
counter.count()
counter.count()
print(counter.__privateCount)
However we can access
the private member using the class name.
print(counter._CounterClass__privatecounter)
Output:
1
2
2
Advantages of Data Hiding
Below are the main advantages of the data hiding.
v
The
class objects are disconnected from the irrelevant data.
v
It
enhances the security against hackers that are unable to access important data.
v
It
isolates object as the basic concept of OOP.
v
It
helps programmer from incorrect linking to the corrupt data.
v
We
can isolate the object from the basic concept of OOP.
v
It
provides the high security which stops damage to violate data by hiding it from
the public.
Disadvantages of Data Hiding
Every coin has two sides if there are advantages then there
will be disadvantage as well. Here are the some disadvantages are given below.
v
Sometimes
programmers need to write the extra lien of the code.
v
The
data hiding prevents linkage that act as link between visible and invisible
data makes the object faster.
v It forces the
programmers to write extra code to hide the important data from the common
users.
Regular
Expression
: Match function, Search
function, Matching VS Searching, Modifiers, patterns
9. Explain Regular Expressions in Python?
A. The
term Regular Expression is popularly shortened as regex. A regex is a sequence
of characters that defines a search pattern, used mainly for performing find
and replace operations in search engines and text processors.
Python offers regex capabilities through the re
module
bundled as a part of the standard library.
v
Raw strings: Different
functions in Python's re module use raw string as an
argument. A normal string, when prefixed with 'r' or 'R'
becomes a raw string.
Example: Raw
String
rawstr
=r'Hello! How are you?'
print(rawstr
) #Hello! How are you?
The difference between a
normal string and a raw string is that the normal string in print() function
translates escape characters (such as \n
, \t
etc.) if any, while those in a raw string
are not.
Example: String vs Raw String
str1
="Hello!\nHow are you?"
print("normal string:",str1
) #normal string: Hello!
str2
=r"Hello!\nHow are you?" #How are you?
print("raw string:",str2
) #raw string: Hello!\nHow are you?
In the above
example, \n
inside str1
(normal
string) has translated as a newline being printed in the next line. But, it is
printed as \n
in str2
- a raw string.
v
meta characters:
Some characters carry a special meaning when they appear as a
part pattern matching string. In Windows or Linux DOS commands, we use *
and ? - they are similar to meta characters. Python's re module uses the
following characters as meta characters:
. ^
$ * + ? [ ] \ | ( )
When a set
of alpha-numeric characters are placed inside square brackets []
, the target string is matched with these characters. A
range of characters or individual characters can be listed in the square
bracket. For example:
Pattern |
Description |
[abc] |
match any of the characters a, b, or c |
[a-c] |
which uses a range to express the same set of characters. |
[a-z] |
match only lowercase letters. |
[0-9] |
match only digits. |
The
following specific characters carry certain specific meaning.
Pattern |
Description |
\d |
Matches any decimal digit; this is equivalent to the class
[0-9]. |
\D |
Matches any non-digit character |
\s |
Matches any whitespace character |
\S |
Matches any non-whitespace character |
\w |
Matches any alphanumeric character |
\W |
Matches any non-alphanumeric character. |
. |
Matches with any single character except newline ‘\n’. |
? |
match 0 or 1 occurrence of the pattern to its left |
+ |
1 or more occurrences of the pattern to its left |
* |
0 or more occurrences of the pattern to its left |
\b |
boundary between word and non-word. /B is opposite of /b |
[..] |
Matches any single character in a square bracket |
\ |
It is used for special meaning characters like .to match a
period or + for plus sign. |
{n,m} |
Matches at least n and at most m occurrences of preceding |
a| b |
Matches either a or b |
v
re.match() function: This
function in re
module tries to find if the
specified pattern
is present at the beginning of the given string.
Syntax:
re.match(pattern, string)
The function
returns None, if the given pattern is not in the beginning, and a match objects
if found.
Example-1: re.match()
fromre
importmatch
mystr
="Welcome to TutorialsTeacher"
obj1
=match
("We",mystr
)
print(obj1
)
obj2
=match
("teacher",mystr
)
print(obj2
)
Output:
<re.Match object; span=(0, 2), match='We'>
None
The match
object has start
and end
properties.
Example-2:
print("start:",obj
.start
(),"end:",obj
.end
()) #start: 0 end: 2
The
following example demonstrates the use of the range of characters to find out
if a string starts with 'W' and is followed by an alphabet.
Example-3: match()
fromre
importmatch
strings
=["Welcome to TutorialsTeacher","weather forecast","WinstonChurchill","W.G.Grace","Wonders of India","Water park"]
forstring
instrings
:
obj
=match
("W[a-z]",string
)
print(obj
)
Output
<re.Match object; span=(0, 2), match='We'>
None
<re.Match object; span=(0, 2), match='Wi'>
None
<re.Match object; span=(0, 2), match='Wo'>
<re.Match object; span=(0, 2), match='Wa'>
v
re.search() function: The re.search()
function searches for a
specified pattern
anywhere in the given string and stops the search on the first
occurrence.
Example: re.search()
fromre
importsearch
string
="Try to earn while you learn"
obj
=search
("earn",string
)
print(obj
)
print(obj
.start
(),obj
.end
(),obj
.group
())
711 earn
Output:
<re.Match object; span=(7, 11), match='earn'>
This function also returns
the Match
object with start and end attributes. It
also gives a group of characters of which the pattern is a part of.
v re.findall() Function: As against
the search()
function,
the findall()
continues
to
search for the pattern till the target string is exhausted. The object
returns a list of all occurrences.
Example-1: re.findall()
fromre
importfindall
string
="Try to earn while you learn"
obj
=findall
("earn",string
)
print(obj
)
Output:
['earn', 'earn']
This function can be used
to get the list of words in a sentence. We shall use \W* pattern for the
purpose. We also check which of the words do not have any vowels in them.
Example-2: re.findall()
obj
=findall
(r"\w*","Fly in the sky.")
print(obj
)
forword
inobj
:
obj
=search
(r"[aeiou]",word
)
ifword
!=''andobj
==None:
print(word
)
Output:
['Fly', '', 'in', '', 'the', '', 'sky', '', '']
Fly
sky
v re.finditer() function: The re.finditer()
function returns an
iterator object of all
matches in the target string. For each matched group, start and end
positions can be obtained by span() attribute.
Example: re.finditer()
fromre
importfinditer
string
="Try to earn while you learn"
it
=finditer
("earn",string
)
formatch
init
:
print(match
.span
())
Output:
(7, 11)
(23, 27)
v
re.split() function: The re.split()
function works similar to
the split() method
of str
object
in Python. It splits the given string every time a white space is found. In the
above example of the findall()
to
get all words, the list also contains each occurrence of white space as a word.
That is eliminated by the split()
function
in re
module.
Example: re.split()
fromre
importsplit
string
="Flat is better than nested. Sparse is better than dense."
words
=split
(r' ',string
)
print(words
)
Output:
['Flat', 'is', 'better', 'than', 'nested.', 'Sparse', 'is', 'better', 'than', 'dense.']
v re.compile() Function: The re.compile()
function returns a pattern
object which
can be repeatedly used in
different regex functions. In the following example, a string 'is' is compiled
to get a pattern object and is subjected to the search()
method.
Example: re.compile()
fromre
import*
pattern
=compile(r'[aeiou]')
string
="Flat is better than nested. Sparse is better than dense."
words
=split
(r' ',string
)
forword
inwords
:
print(word
,pattern
.match
(word
))
Output:
Flat None
is<re.Match object; span=(0, 1), match='i'>
better None
than None
nested. None
Sparse None
is<re.Match object; span=(0, 1), match='i'>
better None
than None
dense. None
The same
pattern object can be reused in searching for words having vowels, as shown
below.
Example: search()
forword
inwords
:
print(word
,pattern
.search
(word
))
Output:
Flat <re.Match object; span=(2, 3), match='a'>
is<re.Match object; span=(0, 1), match='i'>
better<re.Match object; span=(1, 2), match='e'>
than<re.Match object; span=(2, 3), match='a'>
nested. <re.Match object; span=(1, 2), match='e'>
Sparse <re.Match object; span=(2, 3), match='a'>
is<re.Match object; span=(0, 1), match='i'>
better<re.Match object; span=(1, 2), match='e'>
than<re.Match object; span=(2, 3), match='a'>
dense. <re.Match object; span=(1, 2), match='e'>
Multithreading
10. Explain Multithreading in Python?
A. A thread is
the smallest unit of a program or process executed independently or scheduled
by the Operating System. In the computer system, an Operating System achieves
multitasking by dividing the process into threads. A thread is a lightweight
process that ensures the execution of the process separately on the system. In
Python 3, when multiple processors are running on a program, each processor
runs simultaneously to execute its tasks separately.
Python
Multithreading: Multithreading is a threading technique in Python
programming to run multiple threads concurrently by rapidly switching between
threads with a CPU help (called context switching). Besides, it allows sharing
of its data space with the main threads inside a process that share information
and communication with other threads easier than individual processes.
Multithreading aims to perform multiple tasks simultaneously, which increases
performance, speed and improves the rendering of the application.
Benefits
of Multithreading in Python:
Following are the benefits to create a multithreaded
application in Python, as follows:
- It
ensures effective utilization of computer system resources.
- Multithreaded
applications are more responsive.
- It
shares resources and its state with sub-threads (child) which makes it
more economical.
- It
makes the multiprocessor architecture more effective due to similarity.
- It
saves time by executing multiple threads at the same time.
- The
system does not require too much memory to store multiple threads.
How
to achieve multithreading in Python?
There are two main modules of multithreading used to handle
threads in Python
1.
The
thread module
2. The threading module
1.
Thread modules: It is started
with Python 3, designated as obsolete, and can only be accessed with _thread that supports backward compatibility.
Syntax: thread.start_new_thread ( function_name, args[, kwargs] )
To implement the thread module in Python, we need to import
a thread module and then define a function that
performs some action by setting the target with a variable.
#Thread.py
import thread # import the thread module
import time # import time module
def cal_sqre(num): # define the cal_sqre function
print(" Calculate the square root of the given number")
for n in num:
time.sleep(0.3) # at each iteration it waits for 0.3 time
print(' Square is : ', n * n)
def cal_cube(num): # define the cal_cube() function
print(" Calculate the cube of the given number")
for n in num:
time.sleep(0.3) # at each iteration it waits for 0.3 time
print(" Cube is : ", n * n *n)
arr = [4, 5, 6, 7, 2] # given array
t1 = time.time() # get total time to execute the functions
cal_sqre(arr) # call cal_sqre() function
cal_cube(arr) # call cal_cube() function
print(" Total time taken by threads is :", time.time() - t1) # print the total time
Output:
Calculate the square root of the given number
Square is: 16
Square is: 25
Square is: 36
Square is: 49
Square is: 4
Calculate the cube of the given number
Cube is: 64
Cube is: 125
Cube is: 216
Cube is: 343
Cube is: 8
Total time taken by threads is: 3.005793809890747
2.
Threading Modules: The threading
module is a high-level implementation of multithreading used to deploy an application in Python
. To use multithreading, we need to
import the threading module in Python Program
Methods |
Description |
start() |
A start() method is used to
initiate the activity of a thread. And it calls only once for each thread so
that the execution of the thread can begin. |
run() |
A run() method is used to define a
thread's activity and can be overridden by a class that extends the threads
class. |
join() |
A join() method is used to block
the execution of another code until the thread terminates. |
Follow the given below steps to
implement the threading module in Python Multithreading:
1. Import the threading module
Create a new thread by importing
the threading module, as shown.
Syntax: import threading
A threading module
is made up of a Thread class, which is instantiated to create
a Python thread.
2. Declaration of the thread
parameters: It contains the target
function, argument, and kwargs as the parameter in the Thread() class.
v
Target: It defines the function name that is executed by the
thread.
v
Args: It defines the arguments that are passed to the target
function name.
For example:
import threading
def print_hello(n):
print("Hello, how old are you ", n)
t1 = threading.Thread( target = print_hello, args =(18, ))
In the above code, we invoked
the print_hello() function as the target parameter. The print_hello() contains
one parameter n, which passed to the args parameter.
3. Start a new thread: To start a
thread in Python multithreading, call the thread class's object. The start()
method can be called once for each thread object; otherwise, it throws an
exception error.
Syntax:
t1.start()
t2.start()
4. Join method: It is a join() method
used in the thread class to halt the main thread's execution and waits till the
complete execution of the thread object. When the thread object is completed,
it starts the execution of the main thread in Python.
#Joinmethod.py
import threading
def print_hello(n):
Print("Hello, how old are you? ", n)
T1 = threading.Thread( target = print_hello, args = (20, ))
T1.start()
T1.join()
Print("Thank you")
Output:
Hello, how old are you? 20
Thank you
When the above program is executed, the join() method halts
the execution of the main thread and waits until the thread t1 is completely
executed. Once the t1 is successfully executed, the main thread starts its
execution.
5. Synchronizing Threads in Python: It is a
thread synchronization mechanism that ensures
no two threads can simultaneously execute a particular
segment inside the program to access the shared resources. The situation may be
termed as critical sections. We use a race condition to avoid the critical
section condition, in which two threads do not access resources at the same
time.
Let's write a program to use the threading module in Python
Multithreading.
#Threading.py
import time # import time module
import threading
from threading import *
def cal_sqre(num): # define a square calculating function
print(" Calculate the square root of the given number")
for n in num: # Use for loop
time.sleep(0.3) # at each iteration it waits for 0.3 time
print(' Square is : ', n * n)
def cal_cube(num): # define a cube calculating function
print(" Calculate the cube of the given number")
for n in num: # for loop
time.sleep(0.3) # at each iteration it waits for 0.3 time
print(" Cube is : ", n * n *n)
ar = [4, 5, 6, 7, 2] # given array
t = time.time() # get total time to execute the functions
#cal_cube(ar)
#cal_sqre(ar)
th1 = threading.Thread(target=cal_sqre, args=(ar, ))
th2 = threading.Thread(target=cal_cube, args=(ar, ))
th1.start()
th2.start()
th1.join()
th2.join()
print(" Total time taking by threads is :", time.time() - t) # print the total time
print(" Again executing the main thread")
print(" Thread 1 and Thread 2 have finished their execution.")
Output:
Calculate the square root of the given number
Calculate the cube of the given number
Square is: 16
Cube is: 64
Square is: 25
Cube is: 125
Square is: 36
Cube is: 216
Square is: 49
Cube is: 343
Square is: 4
Cube is: 8
Total time taken by threads is: 1.5140972137451172
Again executing the main thread
Thread 1 and Thread 2 have finished their execution.
11. What is an Array in Python and
its Operations?
A.
The Array is an idea of storing multiple items of
the same type together, making it easier to calculate the position of each
element by simply adding an offset to the base value. A combination of the
arrays could save a lot of time by reducing the overall size of the code. It is
used to store multiple values in a single variable. If you have a list of items
that are stored in their corresponding variables like this:
car1 = "Lamborghini"
car2 = "Bugatti"
car3 = "Koenigsegg"
If you want to loop through cars and find a specific one,
you can use the Array. You can use an array to store more than one item in a
specific variable.
The Array can be handled in Python by a module
named Array. It is useful when we must manipulate only
specific data values. The following are the terms to understand the concept of
an array:
Element -
Each item stored in an array is called an element.
Index -
The location of an element in an array has a numerical index, which is used to
identify the element's position. The index value is very much important in an
Array.
Array Representation:
An array can be declared in various ways and in different
languages. The important points that should be considered are as follows:
- The index starts with 0.
- We can easily find any elements
within this Array using the Index value.
- The length of the Array defines the
capacity to store the elements. It is written like x[100], which means the
length of array x is specified by 100.
v Array operations
Some of the basic operations supported by an array are as
follows:
- Traverse - It prints all the elements one by one.
- Insertion - It adds an element at the given index.
- Deletion - It deletes an element at the given index.
- Search - It searches an element using the given
index or by the value.
- Update - It updates an element at the given index.
The Array can be created in Python by importing the array
module to the python program.
from array import *
arrayName = array(typecode, [initializers])
Accessing array elements
We can access the array elements using the respective
indices of those elements.
Program code:
Here we give an example of how we access the elements of
an array using its index value in Python. The code is given below -
import array as arr
a = arr.array('i', [2, 4, 5, 6])
print("First element is:", a[0])
print("Second element is:", a[1])
print("Third element is:", a[2])
print("Forth element is:", a[3])
print("last element is:", a[-1])
print("Second last element is:", a[-2])
print("Third last element is:", a[-3])
print("Forth last element is:", a[-4])
print(a[0], a[1], a[2], a[3], a[-1],a[-2],a[-3],a[-4])
Output:
Now we compile the above code in python, and after
successful compilation, we run it. Then the output is given below -
First element is: 2
Second element is: 4
Third element is: 5
Forth element is: 6
last element is: 6
Second last element is: 5
Third last element is: 4
Forth last element is: 2
2 4 5 6 6 5 4 2
v How to change or add elements?
Arrays are mutable, and their elements can be changed
similarly to lists.
Program code:
Here in this example, we can change or add or replace any
element from the Array in Python. The code is given below -
import array as arr
numbers = arr.array('i', [1, 2, 3, 5, 7, 10])
# changing first element 1 by the value 0.
numbers[0] = 0
print(numbers) # Output: array('i', [0, 2, 3, 5, 7, 10])
# changing last element 10 by the value 8.
numbers[5] = 8
print(numbers) # Output: array('i', [0, 2, 3, 5, 7, 10])
# replace the value of 3rd to 5th element by 4, 6 and 8
numbers[2:5] = arr.array('i', [4, 6, 8])
print(numbers) # Output: array('i', [0, 2, 4, 6, 8, 10])
Output:
Now we compile the above code in python, and after
successful compilation, we run it. Then the output is given below -
array('i', [0, 2, 3, 5, 7, 10])
array('i', [0, 2, 3, 5, 7, 8])
array('i', [0, 2, 4, 6, 8, 8])
v Why use Arrays in Python?
A combination of arrays saves a lot of time. The Array
can reduce the overall size of the code. Using an array, we can solve a problem
quickly in any language. The Array is used for dynamic memory allocation.
How to Delete Elements from an
Array?
The elements can be deleted from an array using
Python's del statement. If we want to delete any
value from the Array, we can use the indices of a particular element.
import array as arr
number = arr.array('i', [1, 2, 3, 3, 4])
del number[2] # removing third element
print(number) # Output: array('i', [1, 2, 3, 4])
Output:
Now we compile the above code in python, and after
successful compilation, we run it. Then the output is given below -
array('i', [10, 20, 40, 60])
v Finding the length of an array
The length of an array is defined as the number of
elements present in an array. It returns an integer value that is equal to the
total number of the elements present in that array.
Syntax
By using the syntax below, we can easily find the length
of the given Array. The syntax is -
len(array_name)
Array Concatenation
We can easily concatenate any two arrays using the +
symbol.
Example 1:
a=arr.array('d',[1.1 , 2.1 ,3.1,2.6,7.8])
b=arr.array('d',[3.7,8.6])
c=arr.array('d')
c=a+b
print("Array c = ",c)
Output:
Now we compile the above code in python, and after
successful compilation, we run it. Then the output is given below -
Array c= array('d', [1.1, 2.1, 3.1, 2.6, 7.8, 3.7, 8.6])
Example 2:
import array as arr
x = arr.array('i', [4, 7, 19, 22]) # Initialize the array elements
print("First element:", x[0])
print("Second element:", x[1])
print("Second last element:", x[-1])
Output:
First element: 4
Second element: 7
Second last element: 22
0 Comments