Unit I Introduction
Unit I Introduction
With its interpreted nature, Python's syntax and dynamic typing make it an ideal
language for scripting and rapid application development.
Python supports multiple programming patterns, including object-oriented,
imperative, and functional or procedural programming styles.
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.
The comedy series was creative and well random. It talks about everything. Thus
it is slow and unpredictable, which made it very interesting.
Python is also versatile and widely used in every technical field, such as Machine
Learning, Artificial Intelligence, Web Development, Mobile Application,
Desktop Application, Scientific Calculation, etc.
3.Interpreted Language:
When a programming language is interpreted, it means that the source code
is executed line by line, and not all at once. Programming languages such as C++
or Java are not interpreted, and hence need to be compiled first to run them. There
is no need to compile Python because it is processed at runtime by the interpreter.
5.Object oriented:
Python supports object-oriented language and concepts of classes and
objects come into existence. It supports inheritance, polymorphism, and
encapsulation, etc. The object-oriented procedure helps to programmer to write
reusable code and develop applications in less code.
6.Cross Platform:
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. It
enables programmers to develop the software for several competing platforms by
writing a program only once.
7.Extensive Feature:
Python has the capabilities to be extended and be a more versatile
programming language. Python proves to be a versatile language as it covers a
large area in software development applications due to its adaptability to various
functionalities. We can compile the code in languages like C/C++, and then can
use that in our python code which can be compiled and run anywhere. It allows
the execution of the code written in other programming languages. This provides
Python new capabilities and functionality by integrating other programming
language’s code.
9.Database support:
Python supports various databases like SQLite, MySQL, Oracle, Sybase,
PostgreSQL, etc. Python also supports Data Definition Language (DDL), Data
Manipulation Language (DML) and Data Query Statements. The Python standard
for database interfaces is the Python DB-API.
10.GUI program:
Graphical User interfaces can be made using a module such as PyQt5,
PyQt4, wxPython, or Tk in Python. PyQt5 is the most popular option for
creating graphical apps with Python.
Datatypes in Python
Data types are used in Python to classify a particular type of data. It is important
because the specific type of information you use will determine which values you
can assign and what you can do. Every Python value has a datatype.
In Python programming, everything is an object, data types are classes, and
variables are instance (object) of these classes.
Immutable
These datatypes cannot be changed once declared. They consist of
Numbers, String, Tuple.
I.None
II.Numbers-int,float,complex.
III.Sequence Type-List,Tuple,String
IV.Mapping-Dictionary
V.set
VI.Boolean
I.None
None is a special data type with a single value.It is used to signify the
absence of value.
Numers
Numers data type stores numerical values only.
It is further classified into three different types:
• Integers.
• Floating Point Numbers.
• Complex Numbers.
1)Integers
Integer values belong to the int class. Specifically, integers represent positive or
negative whole numbers without a decimal. Some examples of integers include:
e.g-a = 5
3)Complex Numbers:
complex is used to store complex (real, imaginary) numbers.
# float variable.
b=20.345
print("The type of variable having value", b, " is ", type(b))
# complex variable.
c=10+3j
print("The type of variable having value", c, " is ", type(c))
Sequence Type: A Python sequence is an ordered collection of items,where each
item is indexed by an integer.
The three types of sequence data types in python are:
1)String-
String is a group of characters.These characters may be alphabets,digits or
special characters including spaces.
String values are enclosed either in single quotes , double quotes and triple double
quotes,triple single quotes.
Examples:
1.str1=’hello’ #using single quotes.
2.str2=”python” #using double quotes.
3.str3=””” hello
Python””” #using triple double quotes.
4.str4=’’’Guido van
Rossum’’’#using triple single quotes.
2)List-
List is a of items separated by commas and the items are enclosed in square
brackets[].
Examples:
1.list1=[1,25,”abc”,”India”]
2.list2=[“India”,”USA”,”UK”]
element = aList[index]
o/p: 541
True
Syntax:
aList[index] = new_value
aList[2] = 'mango'
print(aList)
o/p:
['apple', 'banana', 'mango', 'orange', 'papaya'].
Length of List
You can use len() function to get the length of the list. Pass the list as
argument to len() builtin function, and it returns an integer.
O/P:3
O/p:
apple
banana
mango
cherry
3)sort():
Sort a List
list.sort() function sorts the list in ascending order by default. You can specify
to sort in descending order using ‘reverse’ attribute.
4)remove()
Python list.remove(element) method removes the first occurrence of given
element from the list.
If specified element is present in the list, remove() method raises ValueError.
If there are multiple occurrences of specified element in the given list, remove()
method removes only the first occurrence, but not the other occurrences.
remove() method modifies the original list.
Syntax
myList.remove(element)
Example:
list1 = [25, 74, 19, 52, 68, 34]
list1.remove(19)
print(list1)
O/P:
[25, 74, 52, 68, 34]
5) clear()
Python list.clear() method removes all the elements from the list.
Syntax:
myList.clear()
#take a list
myList = ['apple', 'banana', 'cherry']
O/p:[]
6) count()
Python list.count(element) method returns the number of occurrences of the
given element in the list.
Syntax:
myList.count(element)
O/P:
2
3)Tuple-
Tuple is a sequence of items separated by commas and items are enclosed
in parenthesis().once created, we cannot change the tuple.
Since items in tuple are ordered, we can access individual items using index.
Tuple is immutable. We can neither append items, delete items not assign new
values for existing items.
Example:
names = ('apple', 'banana', 'cherry')
names[1] = 'mango'
o/p:
Traceback (most recent call last):
File "D:/aaa.py", line 2, in <module>
names[1] = 'mango'
TypeError: 'tuple' object does not support item assignment
Tuple Methods
Python tuple class provides two methods.
1)count():
Python tuple.count(element) method returns the number of occurrences of
the given element in the tuple.
where
▪ myTuple is a Python tuple.
▪ count is method name.
▪ element is the object to be searched for in the tuple.
Example:
myTuple = ('apple', 'banana', 'apple', 'cherry')
#count 'apple' occurrences
n = myTuple.count('apple')
print(f'No. of occurrences : {n}')
O/P:
No. of occurrences : 2.
2) index()
Python Tuple index() method returns the index of the specified element, that is
passed as argument, in the calling tuple.
If the element is not at all present in the tuple, then it throws ValueError.
Syntax:
myTuple.index(element)
where
▪ myTuple is the tuple of elements.
▪ index is the name of the method.
▪ element is the one whose index in the tuple is to be found.
print(index)
O/P:4
4)Dictionary:
Python Dictionary is a collection. It can contain multiple elements. Each
element is a key-value pair.
Python Dictionary is un-ordered. The elements in the dictionary are not stored
in a sequence. For example, if you add an item to a dictionary, it can be inserted
at any index.
Python Dictionary is changeable. You can update an item using its key, delete
an item, or add an item. The original dictionary gets updated. Simply put,
Python Dictionary is mutable.
Python Dictionary is indexed. You can access a specific key:value pair using
key as index.
Create a Dictionary
To create a python dictionary, assign a variable with comma separated
key:value pairs enclosed in curly braces.
In the following example, we create a dictionary with some initial key:value
pairs.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
O/P:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Syntax:
dict.copy()
copy() method returns a new dictionary with the items of this dictionary.
Syntax:
dict.get(key[, default])
4)values()
Python Dictionary values() method returns a new view object containing
dictionary’s values. This view object presents dynamic data, which means if any
update happens to the dictionary, the view object reflects those changes.
The view object returned by values() is of type dict_values. View objects
support iteration and membership checks. So, we can iterate over the values,
and also check if a value is present or not using membership test.
Syntax:
Dict.values()
O/P:
dict_values(['Banana', 'apple', 'Strawberry']
5)keys()
Python Dictionary keys() method returns a new view object containing
dictionary’s keys. This view object presents dynamic data, which means if any
update happens to the dictionary, the view object reflects those changes.
The view object returned by keys() is of type dict_keys. View objects support
iteration and membership checks. So, we can iterate over the keys, and also
check if a key is present or not using membership test.
Syntax:
dict.keys()
Example: #program for print keys only.
#initialize dictionary
aDict = {
1:'Banana',
2:'apple',
'hi':'Strawberry'
}
print(aDict.keys())
O/P:
dict_keys([1, 2, 'hi'])
6) update()
Python Dictionary update() method updates this dictionary with the key:value
pairs from the other dictionary.
If this dictionary has keys same as that of in other dictionary, the values in this
dictionary are updated with values from other dictionary.
If other dictionary has keys which this dictionary has not, those key:value pairs
are added to this dictionary.
O/P:
{'a': 58, 'b': 61, 'c': 39, 'k': 44, 'm': 22}
5)Set:
Python Set is a collection of items.
There is no order in which the items are stored in a Set. We cannot access
items in a Set based on index.
Syntax:
set_1 = {item_1, item_2, item_3}
O/P:
{2, 4, 6}
{'a', 'b', 'c'}
Set Methods:
1)add()
Syntax:
set.add(element)
Example:
e = 'mango'
s.add(e)
print(s)
O/p:
{'mango', 'apple', 'cherry', 'banana'}
6)Boolean Type
The boolean value can be of two types only i.e. either True or False. The
output <class ‘bool’> indicates the variable is a boolean data type.