0% found this document useful (0 votes)
15 views20 pages

Unit I Introduction

Uploaded by

yashbhosle919
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views20 pages

Unit I Introduction

Uploaded by

yashbhosle919
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Unit I-Introduction to basic control structure of python.

Introduction-Python is a general-purpose, dynamic, high-level, and


interpreted programming language .

It supports Object Oriented programming approach to develop applications. It is


simple and easy to learn and provides lots of high-level data structures.

Python is an easy-to-learn yet powerful and versatile scripting language, which


makes it attractive for Application Development.

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.

Python is not intended to work in a particular area, such as web programming. It


is a multipurpose programming language because it can be used with web,
enterprise, 3D CAD, etc.

We don't need to use data types to declare variable because it is dynamically


typed, so we can write a=10 to assign an integer value in an integer variable.
Python makes development and debugging fast because no compilation step is
included in Python development, and the edit-test-debug cycle is very fast.

Python History and Versions


o Python laid its foundation in the late 1980s.
o The implementation of Python was started in December 1989 by Guido Van
Rossum at CWI in Netherland.
o In February 1991, Guido Van Rossum published the code (labeled version 0.9.0)
to alt.sources.
o In 1994, Python 1.0 was released with new features like lambda, map, filter, and
reduce.
o Python 2.0 added new features such as list comprehensions, garbage collection
systems.
o On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was
designed to rectify the fundamental flaw of the language.
o 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.

COCSIT college,Latur prepared by:Kamble A.D.


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

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.

Python Version List


Python programming language is being updated regularly with new features and
supports. There are lots of update in Python versions, started from 1994 to current
release.
A list of Python versions with its released date is given below.

COCSIT college,Latur prepared by:Kamble A.D.


Python Version Released Date
Python 1.0 January 1994
Python 1.5 December 31, 1997
Python 1.6 September 5, 2000
Python 2.0 October 16, 2000
Python 2.1 April 17, 2001
Python 2.2 December 21, 2001
Python 2.3 July 29, 2003
Python 2.4 November 30, 2004
Python 2.5 September 19, 2006
Python 2.6 October 1, 2008
Python 2.7 July 3, 2010
Python 3.0 December 3, 2008
Python 3.1 June 27, 2009
Python 3.2 February 20, 2011
Python 3.3 September 29, 2012
Python 3.4 March 16, 2014
Python 3.5 September 13, 2015
Python 3.6 December 23, 2016
Python 3.7 June 27, 2018
Python 3.8 October 14, 2019
Features of python

1.Easy to Learn: Python is easy to learn as compared to other programming


languages. Its syntax is straightforward and much the same as the English
language. There is no use of the semicolon or curly-bracket, the indentation
defines the code block. It is the recommended programming language for
beginners.

COCSIT college,Latur prepared by:Kamble A.D.


2.Easy to Code:
Python is a very developer-friendly language which means that anyone and
everyone can learn to code it in a couple of hours or days. As compared to other
object-oriented programming languages like Java, C, C++, and C#, Python is one
of the easiest to learn

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.

4:Free &open source:


Python is freely available for everyone. It is freely available on its official
website www.python.org. It has a large community across the world that is
dedicatedly working towards make new python modules and functions. Anyone
can contribute to the Python community. The open-source means, "Anyone can
download its source code without paying any penny."

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.

COCSIT college,Latur prepared by:Kamble A.D.


8.High Level Language:
Python is a high-level programming language because programmers don’t
need to remember the system architecture, nor do they have to manage the
memory. This makes it super programmer-friendly and is one of the key features
of Python.

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.

11.Large Standard Library:


Python has a large standard library that provides a rich set of modules
and functions so you do not have to write your own code for every single thing.
There are many libraries present in Python such as regular expressions, unit-
testing, web browsers, etc.

12.Dynamic Typed Language:


Many programming languages need to declare the type of the variable
before runtime. With Python, the type of the variable can be decided during
runtime. This makes Python a dynamically typed language.
For example, if you have to assign an integer value 20 to a variable “x”, you don’t
need to write int x = 20. You just have to write x = 15.

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.

COCSIT college,Latur prepared by:Kamble A.D.


Mutable:
These datatypes can be changed anytime. They consist of List,
Dictionary, and Set.

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

2)Floating point Numbers:


In Python, the float data type is used to represent floating-point numbers,
which are numbers with decimal points.
Example:
pi = 3.14159
temperature = 98.6

3)Complex Numbers:
complex is used to store complex (real, imaginary) numbers.

COCSIT college,Latur prepared by:Kamble A.D.


Example:
# integer variable.
a=100
print("The type of variable having value", a, " is ", type(a))

# 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”]

COCSIT college,Latur prepared by:Kamble A.D.


Access elements in a List:
To access elements of a list in Python, use variable name followed by square
brackets, and the index inside the square brackets.
Syntax:

element = aList[index]

Example:# program Access elements in alist


aList = [21, 'John', 541, 84.25, True]
element = aList[2]
print(element)
element = aList[4]
print(element)

o/p: 541
True

Modify element in a List


You can change the value of element at a given index by assigning the value to
the element using index.

Syntax:
aList[index] = new_value

program:#modify element in a List.

aList = ['apple', 'banana', 'cherry', 'orange', 'papaya']

aList[2] = 'mango'

print(aList)

o/p:
['apple', 'banana', 'mango', 'orange', 'papaya'].

COCSIT college,Latur prepared by:Kamble A.D.


Check if given element is present in List
To check if given element is present in the Python list, you can use in keyword.
Syntax:
element in aList.

Example:#program for Check if given element is present in List.


aList = ['apple', 'banana', 'cherry', 'orange', 'papaya']
ele = 'banana'
if ele in aList:
print('The element is present in list.')
else:
print('The element is not present in list.')

O/P: The element is present in list.

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.

Example:#program for to display length of a list.


aList = [21, 541, 84.25]
print(len(aList))

O/P:3

Python List Methods


Python list class provides many methods that transform or operate on the items
of the List. In addition to these, we have builtin methods that operate on list
objects and transform them.
1)append():

Append element to List

list.append() function appends element to the end of the list.

Example:#program for append element to List.


aList = [21, 53, 84]
aList.append(96)
print(aList)

COCSIT college,Latur prepared by:Kamble A.D.


o/p:
[21, 53, 84, 96]
2)insert()

Insert element in List


list.insert(index, element) method inserts the element at specified index of the
list. The index of elements that were originally present from that index are
shifted right by one position.

Example :1):#program for Insert element in List.


aList = ['apple', 'banana', 'cherry']
aList.insert(2, 'mango')
print(aList)

O/P: ['apple', 'banana', 'mango', 'cherry']

2)#program for insert element in list using for loop.


aList = ['apple', 'banana', 'cherry']
aList.insert(2, 'mango’)
for ele in aList:
print(ele)

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.

Example:#program for Sort a List.


aList = [21, 53, 84, 5, 62]
aList.sort()
for element in aList:
print(element)

COCSIT college,Latur prepared by:Kamble A.D.


O/P:
5
21
53
62
84
#program for list of numbers in descending order.
aList = [21, 53, 84, 5, 62]
aList.sort(reverse=True)
for element in aList:
print(element)
o/p:
84
62
53
21
5

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.

COCSIT college,Latur prepared by:Kamble A.D.


clear() method modifies the original list.

Syntax:
myList.clear()

Example:#program for clear ()

#take a list
myList = ['apple', 'banana', 'cherry']

#remove all elements from the list


myList.clear()
print(myList)

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)

Example:#program for count()


#take a list
myList = ['apple', 'banana', 'apple', 'cherry']
#count 'apple' occurrences
n = myList.count('apple')
print(n)

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.

COCSIT college,Latur prepared by:Kamble A.D.


Examples:
1.tuple1=(‘a’,1,23,”Latur”)
2.tuple2=(“Delhi”,”Mumbai”,”chennai”)

Since items in tuple are ordered, we can access individual items using index.

Example: #program for access individual items using index


names = ('apple', 'banana', 'cherry')
print(names[0])
print(names[1])
print(names[2])
O/p:
apple
banana
cherry

Tuple is immutable. We can neither append items, delete items not assign new
values for existing items.

When we try to update an item in a tuple, we get TypeError, as shown in the


following program’s output.

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.

COCSIT college,Latur prepared by:Kamble A.D.


Syntax:
myTuple.count(element)

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.

Example:#program for tuple in index().

myTuple = ('apple', 'banana', 'cherry', 'orange', 'mango', 'kiwi')

COCSIT college,Latur prepared by:Kamble A.D.


index = myTuple.index('mango')

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.

Example:#program for create a dictionary.

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)

O/P:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

Dictionary Methods in Python


Python dict class provides many methods that transform or operate on the
items (key:value pairs) of the given dictionary.
1)clear()

COCSIT college,Latur prepared by:Kamble A.D.


Python Dictionary clear() method removes all the items from the dictionary.
All data in the dictionary will be lost and the length of the dictionary becomes
zero.
Syntax:
dict.clear()
clear() method returns None.

Example:#program for clear().


myDictionary = {'a': 58, 'b': 22, 'c': 39}
myDictionary.clear()
print(myDictionary)
O/P:{}
2)copy():
copy() method returns a shallow copy of the dictionary.

Syntax:
dict.copy()

copy() method returns a new dictionary with the items of this dictionary.

Example:#program for copy().


dictionary1 = {'a': 58, 'b': 61, 'c': 39}
dictionary2 = dictionary1.copy()
print(dictionary1)
print(dictionary2)
O/P:
{'a': 58, 'b': 61, 'c': 39}
{'a': 58, 'b': 61, 'c': 39}

COCSIT college,Latur prepared by:Kamble A.D.


3)get()
Dictionary get(key[, default]) method returns the value for the key if the
key is present, else returns default (if provided) value. If key is not present
in the dictionary and default value is not provided, get() returns None.

Syntax:
dict.get(key[, default])

Example:#program for get().


myDictionary = {'a': 58, 'b': 61, 'c': 39}
print(myDictionary.get(‘m’))
o/p:None.

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

Example:#program for print values only.


#initialize dictionary
aDict = {
1:'Banana',
2:'apple',
'hi':'Strawberry'
}

COCSIT college,Latur prepared by:Kamble A.D.


print(aDict.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.

COCSIT college,Latur prepared by:Kamble A.D.


Syntax:
dict.update([other])
Example:#program for update().
myDictionary = {'a': 58, 'b': 61, 'c': 39}
other = {'k': 44, 'm': 22}
myDictionary.update(other)
print(myDictionary)

O/P:
{'a': 58, 'b': 61, 'c': 39, 'k': 44, 'm': 22}

5)Set:
Python Set is a collection of items.

Python Set is Unordered

There is no order in which the items are stored in a Set. We cannot access
items in a Set based on index.

Python Set has Unique Items


Python Set can store only unique items. We cannot add an item that is already
present in the Set.

Python Set is Mutable


We can modify a Set. In other words, we can add items to a Set or remove items
from a Set.

Create Python Set


To create a Set in Python, use curly braces {}.

Syntax:
set_1 = {item_1, item_2, item_3}

Example:#create set using curly braces

COCSIT college,Latur prepared by:Kamble A.D.


set_1 = {2, 4, 6}
print(set_1)

#create set using set() builtin function


set_2 = set({'a', 'b', 'c'})
print(set_2)

O/P:
{2, 4, 6}
{'a', 'b', 'c'}

Set Methods:

1)add()

Set add(element) method adds the element to the set.

Syntax:
set.add(element)

Example:

s = {'apple', 'banana', 'cherry'}

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.

Example:#program for Boolean datatype.


A=True
Print(A)
O/P:
True

COCSIT college,Latur prepared by:Kamble A.D.

You might also like