Python - 1 Year - Unit-1
Python - 1 Year - Unit-1
by
K. KUMARASWMY
C. RAJEEV
Assistant Professor,
Assist. Prof.
Department of CSE,
Dept. of. CSE,
MRECW MRECW.
Course Objectives:
This course will enable students to
Learn Syntax and Semantics and create Functions in
Python.
Handle Strings and Files in Python.
Understand Lists, Dictionaries and Regular
expressions in Python.
Implement Object Oriented Programming concepts in
Python.
Build GUI Programming in Python.
Course Outcomes:
The students should be able to
Examine Python syntax and semantics and be fluent in the use
in Python.
Implement exemplary applications related to Graphical User
Features, Python Applications, Why Python is Becoming Popular Now a Day?, Existing
Programming, Flavors in Python, Python Versions, Download & Install the Python in
Windows & Linux, How to set Python Environment in the System?, Anaconda - Data Science
Distributor, Downloading and Installing Anaconda, Jupyter Notebook & Spyder, Python IDE -
bool, str, Number Data Types: Decimal, Binary, Octal, Hexa Decimal & Number Conversions,
Inbuilt Functions in Python, Data Type Conversions, Priorities of Data Types in Python,
Slicing & Indexing, Forward Direction Slicing with +ve Step, Backward Direction Slicing
with -ve Step, Decision Making Statements, if Statement, if-else Statement, elif Statement,
Looping Statements, Why we use Loops in python?, Advantages of Loops for Loop, Nested for
Loop, Using else Statement with for Loop, while Loop, Infinite while Loop, Using else with
Python while Loop, Conditional Statements, break Statement, continue Statement, Pass
Statement
UNIT III
Advanced Data Types: List, Tuple, Set, Frozenset, Dictionary, Range, Bytes & Bytearray,
None, List Data Structure, List indexing and splitting Updating List values, List Operations,
Iterating a List, Adding Elements to the List, Removing Elements from the List, List Built-in
Functions, List Built-in Methods, Tuple Data Structure, Tuple Indexing and Splitting, Tuple
Operations, Tuple Inbuilt Functions, Where use Tuple, List Vs Tuple, Nesting List and Tuple,
Set Data Structure, Creating a Set, Set Operations, Adding Items to the Set, Removing Items
from the Set, Difference Between discard() and remove(), Union of Two Sets, Intersection of
Two Sets, Difference of Two Sets, Set Comparisons, Frozenset Data Structure, Dictionary Data
Structure, Creating the Dictionary, Accessing the Dictionary Values, Updating Dictionary
Values, Deleting Elements Using del Keyword, Iterating Dictionary, Properties of Dictionary
Keys, Built-in Dictionary Functions, Built-in Dictionary Methods, List Vs Tuple Vs Set Vs
UNIT IV
Python Built-in Functions, Python Lambda Functions, String with Functions, Strings Indexing
and Splitting String Operators, Python Formatting Operator, Built-in String Functions, Python
File Handling, Opening a File, Reading the File, Read Lines of the File, Looping through the
File, Writing the File, Creating a New File Using with Statement with Files, File Pointer
Position, Modifying File Pointer Position Renaming the File & Removing the File, Writing
Python Output to the Files File Related Methods, Python Exceptions, Common Exceptions,
Problem without Handling Exceptions, except Statement with no Exception, Declaring Multiple
Python Packages, Python Libraries, Python Modules, Collection Module, Math Module, OS
Module, Random Module, Statistics Module, Sys Module, Date & Time Module, Loading the
Module in our Python Code, import Statement, from-import Statement, Renaming a Module,
Inheritance, Polymorphism, Data Abstraction, Encapsulation, Python Class and Objects, Creating
Classes in Python, Creating an Instance of the Class, Python Constructor, Creating the,
Class Functions, In-built Class Attributes, Python Inheritance, Python Multi-Level Inheritance,
Graphical User Interface (GUI) Programming, Python Tkinter, Tkinter Geometry, pack()
TEXT BOOK:
1. Core Python Programming, Wesley J. Chun, Second Edition, Pearson
REFERENCE BOOK:
1. Programming Languages, A.B. Tucker, R.E. Noonan, TMH.
2. Programming Languages, K. C. Louden and K A Lambert., 3rd
edition, Cengage Learning.
3. Programming Language Concepts, C Ghezzi and M Jazayeri, Wiley
India.
4. Programming Languages 2nd Edition Ravi Sethi Pearson.
5. Introduction to Programming Languages Arvind Kumar Bansal CRC
Press.
UNIT I
PYTHON Programming Introduction, History of Python, Python is Derived from?, Python
Features, Python Applications, Why Python is Becoming Popular Now a Day?, Existing
Programming, Flavors in Python, Python Versions, Download & Install the Python in
Windows & Linux, How to set Python Environment in the System?, Anaconda - Data Science
Distributor, Downloading and Installing Anaconda, Jupyter Notebook & Spyder, Python IDE -
Python is said to have succeeded is ABC Programming Language, which had the interfacing
with the Amoeba Operating System.
Python is derived from many other languages, including ABC, Modula-3, C, C++,Algol-68,
SmallTalk, and Unix shell and other scripting languages
Here interesting fact is- Python is named after the BBC TV comedy show Monty
Secondly, it is open-source. This means that its source code is available to the public.
You can download it, change it, use it, and distribute it. This is called FLOSS(Free/Libre
and Open Source Software).
3. High- Level
It is a high-level language. This means that as programmers, we don’t need to
remember the system architecture. Nor do we need to manage the memory. This
makes it more programmer-friendly.
4. Portable
We can take one code and run it on any machine, there is no need to write different
code for different machines. This makes Python a portable language. However, you
must avoid any system-dependent features in this case.
5. Interpreted:
If you’re any familiar with languages like C++ or Java, you must first compile it, and
then run it. But in Python, there is no need to compile it. Internally, its source code is
converted into an immediate form called bytecode.
So, all you need to do is to run your Python code without worrying about linking to
libraries, and a few other things.
By interpreted, we mean the source code is executed line by line, and not all at once.
Because of this, it is easier to debug your code.
6. Object-Oriented
Python allows us to develop applications using an Object-Oriented approach.
Object-oriented programming (OOP) is nothing but that which allows the writing
of programs with the help of certain classes and real-time objects
4) Business Applications
7) 3D CAD Applications
8) Enterprise Applications
9) Image applications
1) Web Applications
We can use Python to develop web applications. It provides libraries to handle internet
protocols such as HTML and XML, JSON, Email processing, request, beautifulSoup,
Feedparser etc.
It also provides Frameworks such as Django, Pyramid, Flask etc to design and develop
web based applications. Some important developments are: PythonWikiEngines, Pocoo,
PythonBlogSoftware etc.
Some other useful toolkits wxWidgets, Kivy, pyqt that are useable on several platforms.
The Kivy is popular for writing multitouch applications.
3) Software Development
Python is helpful for software development process. It works as a support language and
can be used for build control and management, testing etc.
5) Business Applications
Python is used to build Business applications like ERP and e-commerce systems.
Tryton is a high level application platform.
8) 3D CAD Applications
To create CAD application Fandango is a real application which provides full features of
CAD.
9) Enterprise Applications
Python can be used to create applications which can be used within an Enterprise or an
Organization.
Some real time applications are: OpenErp, Tryton, Picalo etc.
Python has a simple syntax similar to the English language. whereas the other languages use
punctuations.
Python has syntax that allows developers to write programs with fewer lines than some other
programming languages.
Python is a programming language that allows you work quickly and integrate systems
more efficiently.
Python is a great language for the beginner level programmers and supports the
development of a wide range of applications.
6. Advantages of Python:
1. Freeware: Python is open source language. It doesn't require any activation key or
subscription to work on it. It is free to use software and all the tool available on python
are absolutely free.
2. Less Coding: The syntax written in python is very simple and use common English
language which makes it more user-friendly.
3. Efficient: Python relies on indentation, using white space, to define scope; such as the
scope of loops, functions, and classes. Other Programming Languages use curly-brackets
for this purpose.
4. Portability: Python can run any operating system. Also, we use the Python Code
written on one system onto another system without making any changes to the code.
Existing Programming Vs Python Programming:
C, c++ ,java , python program to find addition of two numbers
scanf("%d %d", &a, &b); cout << "Enter two integers: ";
cin >> firstNumber >> secondNumber;
sum = a + b;
sumOfTwoNumbers = firstNumber + secondNumber;
printf("Sum : %d", sum);
cout << firstNumber << " + " << secondNumber << " = " << sumOfTwoNumbers;
return(0);
return 0;
}
}
--------java program--------
--------python program--------
public class AddTwoNumbers {
num1 = 1.5; num2 = 6.3
public static void main(String[] args) {
sum = num1 + num2
int num1 = 5, num2 = 15, sum;
print('The sum of two numbers”, sum))
sum = num1 + num2;
System.out.println("Sum of these numbers: "+sum);
}
}
7. Python Versions:
The implementation of Python was started in December 1989.
In February 1991, Guido Van Rossum published the code (labeled version 0.9.0) to alt.sources.
8. Uber - at the lower level backend, the engineers work mostly in Python,
Node.js, Go and Java .
9. Yahoo(Maps)
10. YouTube
11. Mozilla
12. Dropbox
8. Installing Python(in ubuntu)
1. Open terminal via Ctrl+Alt+T or searching for “Terminal” from app launcher.
>python --version
9. How to execute python program:
By using Python Interpreter, we can execute python programs in 2 modes .they
are:
1. Immediate mode
2. Script mode
1. Immediate mode: (in windows)
In the mode, you type Python expressions into the Python Interpreter window,
and the interpreter immediately shows the results.
C:\>python
'python' is not recognized as an internal or external command, operable program or
batch file.
As you can see from the output above, the command was not found.
To run python.exe, you need to specify the full path to the executable:
To add the path to the python.exe file to the Path variable, start the Run box and enter sysdm.cpl:
This should open up the System Properties window. Go to the Advanced tab and click
the Environment Variables button:
In the System variable window, find the Path variable and click Edit:
Position your cursor at the end of the Variable value line and add the path to the python.exe file,
preceeded with the semicolon character (;). In our example, we have added the following value: ;
Close all windows. Now you can run python.exe without specifying the full path to the file:
10. How to install Anaconda software in ubuntu
6. Activate Installation
We can now activate the installation with the following command:
Source ~/.bashrc
7. if you want to add Anaconda to your PATH use command:
$ export PATH=/usr/bin/anaconda/bin:$PATH
8. To launch application use following command:
$ anaconda -navigator
9. After launching, the following applications are available by default in Navigator:
1.JupyterLab
2.Jupyter Notebook
3.QTConsole
4.Spyder
5.VSCode
6.Glueviz
7.Orange 3 App
8.Rodeo
9.RStudi0
8. From the Navigator Home tab, click the launch button in Spyder, and it is open
editor to write and execute our code.
In ubuntu, Immediate mode and scripting mode of Anaconda
How to install Anaconda software in windows
Output:
>>> msg
'Hello World'
>>> code
123
3.Comments in Python
In a Python script, the symbol # indicates the start of a comment line. It is effective
till the end of the line in the editor.
It can be used also in the middle of a line. The text before it is a valid Python
expression, while the text following is treated as a comment.
Example:
# this is a comment
print ("Hello World")
print ("Welcome to Python Tutorial") #this is also a comment but after a
statement
In Python, there is no provision to write multi-line comments, or a block comment.
(As in C#/C/C++, where multiple lines inside /* .. */ are treated as a multi-line
comment).
Then how to represent Multi Line Comments:
Python does not really have a syntax for multi line comments.
To add a multiline comment you could insert a # for each line.
Ex:
#This is a comment
#written in
#more than just one line
print("Hello, World!")
We can also represent Multi Line Comments using a multiline string(triple quotes).
Ex:
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
4.Indentation:
One of the most distinctive features of python is use of indentation to mark blocks of
code.
Generally, in C,C++,java languages ,we use curly brackets { } to indicate block of code
for class ,function definition or flow of control. but where as in python curly braces are
not allowed.
Then, what is indentation?
So, in python block of code are denoted by indentation.
Indentation refers to the whitespaces(spaces and tabs) at the beginning of a code line.
Where in other programming languages the indentation in code is for readability only.
How to use this: When a block is to be started, type the exclamation symbol (:) and
press Enter. Then follow indentation Ex:
test=5
if test<10:
print(“A”)
else:
print(“C”)
In the following program, the block statements have no indentation.
In order to signal the end of a block, the whitespace is de-dented by pressing the backspace key
Instructions:
Use 4 spaces per indentation and no tabs.
Do not mix tabs and spaces. Tabs create confusion and it is recommended to use
only spaces.
Python will give you an error if you skip the indentation, so use the same number of
spaces in the same block of code,
5. Python identifiers:
A identifier is a name used to identify a variable, function, class, module or other
object.
An identifier start with a letter A t o Z (or) a to z an underscore(_) followed by zero
or more letters, underscores and digits(0-9).
Python doesn’t allows punctuation characters such as @,$,% with identifiers.
1.An identifier should not start with digit but it can contains digit.
Ex:
>>> 12ab=20 syntax error: invalid syntax
>>> ab12=20 20
2. An identifier can contain underscores (single, double, and also triple)
Ex:
>>> _a=10
>>> _a
10
>>> a_b=20
>>> a_b
20
>>> ab_=30 >>> __ab__cd=90
>>> ab_ >>> __ab__cd
30 90
Note: In python, underscore (_) has special meaning in the interactive interpreter: the last
evaluated expression.
>>> _
3. An identifier must not contain special characters except underscores .
>>> @a=20
SyntaxError: invalid syntax >>> a*b=20
>>> a@b=20 SyntaxError: can't assign to operator
SyntaxError: can't assign to operator >>> &a=20
>>> $b=10 SyntaxError: invalid syntax
SyntaxError: invalid syntax >>> a&b=20
>>> a$b=20 SyntaxError: can't assign to operator
SyntaxError: invalid syntax
>>> !a=20 >>> a_b=20
SyntaxError: invalid syntax >>> a_b
>>> a!b=20 20
SyntaxError: invalid syntax
>>> *a=20
SyntaxError: starred assignment target must be in a list or tuple
4. Identifiers are case sensitive, so python is a case sensitive language.
>>> a=100
>>> A=200
>>> print(a)
100
>>> print(A)
200
Ex:1
>>> if=100
File "<stdin>", line 1
if=100
^
SyntaxError: invalid syntax
Ex:2
>>> return=10
File "<stdin>", line 1
return=10
^
SyntaxError: invalid syntax
6.Keywords:
Computer programming language comprises of a set of predefined words which are called
keywords.
Similarly, Python 3.x interpreter has 35 keywords defined in it.(In C, 32 keywords)
They cannot be used for any other purpose like constants or variable or identifier names.
>>> help("keywords“)
Here is a list of the Python keywords.
False class from or
None continue global pass
True def if raise
and del import return
Note: only False, None,
as elif in try
True are capitalized
assert else is while
async except lambda with
await finally nonlocal yield
break for not
>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif',
'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or',
'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
Just we declare variable has a name that is used to refer to memory location. Python
variable is also known as an identifier and used to hold value.
In python, we don't need to declare explicitly variable i.e., variables need not be
declared or defined in advance.
In C, it actually creates a block of memory In Python, variables work more like tags,
space so that it can hold the value for that When you do an assignment in Python, it tags
variable. the value with the variable name.
int a=1; a=1
Ex: Let's consider the example code "a = 1" , "a" is name and it's points to the reference
"258041008" and the reference points to the object "1" which is in binary format.
We can get this reference object, with python built-in function id( )
So that, a name is just a label for an object.
In C, if you change the value of the variable, In Python. if you change the value of the
the box will be updated with the new value. variable, it just changes the tag to the new
int a = 2; value in memory.
a=2
In C, if we assign one variable to another In Python, Assigning one variable to another
makes a copy of the value and put that value in makes a new tag bound to the same value:
the new box. a=2
int a=2; b=a
int b = a;
In python, we don’t need to do the housekeeping job of freeing the memory here. Python's
whereas, a variable is a “name given to memory location”, that is used to hold value,
which may get modified during program execution.
1. Assigning single value to single variable:
The operand to the left of the = operator is the variable and the right of the =operator is
the value stored in the variable
For example, >>> n = 10 >>m=20.5 >>>p=‘python’
>>>n >>>m >>>p
10 20.5 python
>>> x=y=z=50
>>> id(x)
>>> x
1372546288
50
>>> id(y)
>>> y
1372546288
50
>>> id(z)
>>> z
1372546288
50
>>>
4. Tuple assignment :
x, y = 50, 100
X,
5. List assignment:
[x, y] = [2, 4]
print('x = ', x)
print('y = ', y)
6. Sequence assignment:
a, b, c = 'HEY’
print('a = ', a)
print('b = ', b)
print('c = ', c)
7. To check the data type of specific variable we can use type( ) function.