Python (SEP) Unit 1
Python (SEP) Unit 1
BY
Smt.ANURADHA T S , Assistant Professor
UNIT 1
Introduction
Introduction to Python
Python is a general purpose, dynamic, high level, interpreted, interactive, and scripting, object oriented
programming language.
It is simple and easy to learn and provides lots of high-level data structures.
Overview:
Python Evolution/History
The implementation of Python was started in the December 1989 by Guido VanRossum in
Netherland
He was a Dutch Scientist/programmer.
Python is derived from ABC programming language, which is a general-purpose
programming language that had been developed at the CWI.
Rossum chose the name "Python", since he was a big fan of Monty Python's Flying Circus.
Features of Python
Simple & Easy to learn:
– Python is a simple and minimalistic language. Reading a good Python program feels almost like
reading English language.
– Python has an extraordinarily simple syntax and simple program structure.
Portable & Platform independent:
– Due to its open-source nature, Python has been ported to (i.e. changed to make it work on)
many platforms.
– Using a Python Virtual Machine (PVM), anybody can run these byte code instructions on any
computer system. Hence, Python programs are not dependent on any specific operating system.
– All your Python programs can work on any platforms without requiring any changes at all if you are
careful enough to avoid any system-dependent features.
Object-Oriented Language:
– 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.
Interpreted Language:
– Python converts the source code into an intermediate form called byte codes and then translates this
into the native language of your computer using PVM(Is s interpreter) and then runs it.
High level language:
– When you write programs in Python, you never need to bother about the low- level details such as
managing the memory used by your program, etc.
Open Source:
– There is no need to pay for Python software.
– It can be free downloaded from www.python.org website. Its source can be read, modified and used
in programs as desired by the programmers.
GUI Programming Support:
– Graphical User Interface is used for the developing Desktop application.
– PyQT5, Tkinter, Kivy are the libraries which are used for developing the web application.
Large Standard Library:
– It provides a vast range of libraries for the various fields such as machine learning, web developer,
and also for the scripting.
– There are various machine learning libraries, such as Tensor flow, Pandas, Numpy, Keras, and
Anuradha T S Assistant Professor 2
PYTHON PROGRAMMING PYTHON PROGRAMMING BASICS
Pytorch, etc. Django, flask, pyramids are the popular framework for Python web development.
Scripting language:
– Python is considered as scripting language as it is interpreted and it is used on the Internet to support
other software.
Database connectivity:
– Python provides interface to connect its programs to all major databases like Oracle, Sybase or MySQL.
Applications
GUI based desktop applications (Games, Scientific Applications)
Web frameworks and applications
Enterprise and Business applications
Operating Systems
Language Development
Prototyping
Difference between,
C Python
An Imperative programming model is An object-oriented programming model is
basically followed by C. basically followed by Python.
Variables are declared in C. Python has no declaration.
C doesn’t have native OOP. Python has OOP which is a part of language.
No pointers functionality is available in
Pointers are available in C language.
Python.
C is a compiled language. Python is an interpreted language.
There is a limited number of built-in There is a large library of built-in functions
functions available in C. in Python.
Implementation of data structures requires its It is easy to implement data structures in Python
functions to be explicitly with built-in insert, append
implemented. functions.
C is compiled direct to machine code Python is firstly compiled to a byte-code and
which is executed directly by the CPU then it is interpreted by a large C program.
Declaring of variable type in C is There is no need to declare a type of
necessary condition. variable in Python.
C does not have complex data
Python has some complex data structures.
structures.
C is statically typed. Python is dynamically typed.
Syntax of C is harder than python because of
It is easy to learn, write and read Python programs
which programmers prefer
than C.
to use python instead of C
C programs are saved with .c Python programs are saved by .py
extension. extension.
Assignment gives an error in line. For
An assignment is allowed in a line.
example, a=5 gives an error in python.
In C language testing and debugging In Python, testing and debugging is not
is harder. harder than C.
C is complex than Python. Python is much easier than C.
Java Python
Pure Object-Oriented Programming Both Object-Oriented and Procedure-Oriented
Language programming language
It supports single and multi dimensional arrays It supports only single dimensional array. Implement multi
dimensional array we should use third party application
like numpy.
The array index should be positive integer. Array index can be positive and negative integer.
Negative index represents location
from the end of the array.
Indentation of statements in not Indentation is required to represents a block
Necessary of statements.
A semicolon is used to terminate the New line indicates end of the statements and semicolon is
statements and comma is used to used as an expression separator.
separate expressions / variables.
The collection objects like stack, linked list or The collection objects like lists and dictionaries
vector but not primitive data types like int, can store objects of any type including
float, char etc., numbers and lists.
Python Versions
Python programming language is updated regularly with new features. Python has mainly 3 versions, they
are 1,2 and 3 sub versions are
1989--------------implementation started
1991-------------- labeled version 0.9.0
1994-------------- Python 1.0 – lambda, map, reduce and filter
2000------------- Python 2.0 – list, garbage, collection system etc..
2001-------------- Python 2.1
2008------------- Python 3.0 [also called “Py3k”] – It was designed to rectify fundamental flaw
of the language.
2016-------------- Python 3.6
2018------------- Python 3.7
2019 ---------------- Python 3.8
2020 ---------------- Python 3.9
2025------------- Python 3.13.7 Latest Stable Version
3. Finish Installation
• Wait until the setup completes.
• When 'Setup was successful' appears, click 'Close.
4. Verify Installation
1. Open Command Prompt (press Win + R, type cmd, press Enter).
2. Type: python --version
3. You should see: Python 3.13.
Python Interpreter is a program which translates your code into machine language and then executes it line by
line.
We can use Python Interpreter in two modes:
Interactive Mode.
Script Mode.
Python Command Line Mode (also called Interactive Mode) is a way to run Python statements directly
from a terminal or command prompt without writing them in a separate file first. It’s useful for quick testing,
debugging, or learning.
Interactive Mode:
Python interpreter in interactive mode is commonly known as Python Shell.
In Interactive Mode, Python interpreter waits for you to enter command. When you type the command,
Python interpreter goes ahead and executes the command, and then it waits again for your next
command.
To start the Python Shell enter the following command in terminal or command prompt:
Script Mode:
In Script mode, Python Interpreter runs a program from the source file.
Python Shell is great for testing small chunks of code but there is one problem – the statements you enter
in the Python shell are not saved anywhere.
In case, you want to execute same set of statements multiple times you would be better off to save the
entire code in a file. Then, use the Python interpreter in script mode to execute the code from a file.
Save the file. all Python programs have .py extension and Run/execute
Python IDE’s
A Python IDE (Integrated Development Environment) is a software application that is designed to help
developers write, test, and debug Python code more efficiently . It is a program that provides a set of
tools that all work together, such as a text editor, compiler, build automation, debugging, libraries, and
many more . An IDE understands the code significantly better than a text editor and can provide features
such as code linking, testing, and debugging, which can significantly speed up your work . Some popular
Python IDEs include PyCharm, Spyder, Thonny, and IDLE
If you’re looking for a Python IDE, you might want to consider the following factors:
Ease of use: Choose an IDE that is easy to use and has a user-friendly interface.
Features: Look for an IDE that has all the features you need, such as code completion, debugging, and
version control.
Compatibility: Make sure the IDE you choose is compatible with your operating system.
Cost: Some IDEs are free, while others require a subscription or a one-time payment
PYTHON BASICS:
Elements of Python
Identifiers:
Identifier is the name given to various program elements like variables, function, arrays, classes,
strings etc.,
The Python identifiers follow the following rules:
o The Name should begin with an alphabet.
o Only alphabets, digits and underscores are permitted.
o Distinguish between uppercase and lowercase alphabets.
o Keywords should not be used as identifiers.
o No blank space between the identifiers.
Keywords:
The keywords have predefined meaning assigned by the Python Complier.
The keywords are also called as reserved word.
All keywords are written in lower case alphabets.
The Python keywords are:
Variables:
Variable is a name which is used to refer memory location.
Variable also known as identifier and used to hold value, whose value changes during the execution of the
program.
In Python, we don't need to specify the type of variable, because Python is smart enough to get variable
type.
Unlike other programming languages, Python has no command for declaring a variable.
When we assign any value to the variable that variable is declared automatically.
Variables do not need to be declared with any particular type and can even change type after they have
been set.
Example:
a=10
Now this a is of type int
a=’s’ This
as type char
A data type represents the type of data stored into a variable or memory. There are 5 different data types are:
• None type
• Numeric type
• Sequences
• Sets
• Dictionary
1. None data type : The none data type represents an object that does not contain any value. In java language it
is called “NULL” object. But in Python it is called as “none”. In Python maximum of only one ‘none’ object
is provided. If no value is passed to the function, then the default value will be taken as ‘none’.
2. Numeric data type:
Numeric data type represents the data which has numeric value.
Numeric value can be integer, floating number or even complex numbers.
There are 3 sub types:
o int
o float
o complex
Output:
5 is of type <class 'int'>
2.0 is of type <class 'float'>
3. Sequences:
A sequence represents a group of items or elements.
There are several types of sequences in Python, few important sequences as follows,
o str
o list
o tuple
Example
str=”python”
# str is name of string variable, string value is python.
Example
list=[10,3.5,-20,'python']
print(list) # It display all elements in the list
output:
[10,3.5,-20, 'python']
print(list[0]) # it display 10
Example
tpl=(10,3.5,-20,'python')
print(tpl)
output:
(10,3.5,-20, 'python')
print(tpl[0]) # it display 10
print(tpl[1:3]) # it display 3.5, -20
tpl[1]=1.5 # replace 1st location element by 1.5 Display an error message -
“tuple does not support this assignment, tuples are immutable.
4. Sets:
Set is an unordered collection of unique items and un-indexed.
The order of elements is not maintained in the sets.
A set does not accept duplicate elements.
Set is defined by values separated by comma inside braces { }.
There are two sub types in sets:
o Set data type
o Frozen set data type
output: {10,5,30,50}
In the above example, it displays un-orderly and repeated elements only once, because set is unordered collection
and unique items.
5. Dictionary:
A dictionary is an unordered collection, changeable and indexed.
In Python dictionaries are written with curly brackets, and they have keys and values.
That means dictionary contains pair of elements such that first element representsthe key and the next
one becomes its value.
The key and value should be separated by a colon(:) and every pair should beseparated by comma.
All the elements should be enclosed inside curly brackets.
Example
d={1:12,2:'hi',3:"hi"}
print(d) # prints {1: 12, 2: 'hi', 3: 'hi'}
Here, d is the name of dictionary. 1 is the key and its associated value is 12. The next is 2
and its value is ‘hi’ and so on.
Literals:
Literal is a raw data given in a variable or constant. In Python, there are various types of literals they are as
follows:
Numeric Literals :
Numeric Literals are immutable (unchangeable). Numeric literals can belong to 3different numerical types
Integer, Float and Complex.
Example:
a=5 # integer literal
b=2.5 # float literal
c=3.5j # complex literal
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. Character literal is a single character surrounded by single or double quotes.
Example:
a=’s’
Boolean literals :
A Boolean literal can have any of the two values: True or False.
Example:
x=true
Y=false
Special literals:
Python contains one special literal i.e. None. We use it to specify to that field that is not created.
Example:
k=none
Operators
Operators are special symbols that are used to perform operations on operands.
Python supports different types of operators,
o Arithmetic Operators.
o Relational Operators.
o Assignment Operators.
o Logical Operators.
o Membership Operators.
o Identity Operators.
o Bitwise Operators.
Relational operator:
These are the operators which are used to perform comparison,
Logical operator:
These are the operators which are used to perform combining two or more expressions,
Assignment operator:
These are the operators which are used to perform assigning values to variables,
Symbol Description Example-1
Assigned values from right side
= x=10
operands
Anuradha T S Assistant Professor
PYTHON PROGRAMMING 3Sem BCA (SEP)
to left variable. 10
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,
Assigning single value to multiple variables:
x=y=z=50
Assigning multiple values to multiple variables:
a,b,c=2,3,4
Membership operators:
Python has membership operators, which test for membership in a sequence, such as strings, lists or
tuples.
There are two membership operators are:
Identity operator:
Identity operators compare the memory locations of two objects.There are two Identity
operators are:
Ternary Operator
Ternary operator is also called as conditional operator.
It operates on 3 data elements.
It was added to Python in version 2.5.
It simply allows testing a condition in a single line replacing the multiline if-else making the code
compact.
Syntax: var = [true statement] if(condition) else [flase statement]
Example:
a=12 b=10
big=a if(a>b) else b print(big)
Precedence of Operators:
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so
it first multiplies 3*2 and then adds into 7.
Example 1:
>>> 3+4*2
11
>>> (10+10)*2 40
Association:
Operator Precedence and Associativity in Python
This table lists all operators from the highest precedence to the lowest precedence.
Precedence Operators Description Associativity
Multiplication, matrix,
6 *, @, /, //, % division, floor division, Left to right
remainder
in, not in, is, is not, <, <=, >, Comparisons, membership
>=, !=, == tests, identity tests
12 Left to Right
Assignment expression
(walrus operator)
18 := Right to left
Statements:
A statement is an instruction that the Python interpreter can execute. We have normally two basic statements, the
assignment statement and the print statement. Some other kinds of statements that are if statements, while
statements, and for statements generally called as control flows.
Examples:
An print statement is something which is an input from the user, to be printed / displayed on to the screen (or ) monitor.
Degree college
Expressions in Python
An expression is a combination of operators and operands that is interpreted to produce some
other value. In any programming language, an expression is evaluated as per the precedence of its
Anuradha T S Assistant Professor
PYTHON PROGRAMMING 3Sem BCA (SEP)
operators. So that if there is more than one operator in an expression, their precedence decides
which operation will be performed first.
Indentation
Indentation refers to the ‘whitespaces at the beginning of a code line’.
Python uses indentation to indicate a block of code. This means that statements which go together must
have the same indentation.
Where in other programming languages the indentation in code is for readability only, the indentation in
Python is very important.
Leading whitespace (spaces and tabs) at the beginning of the logical line is used to determine the
indentation level of the logical line, which in turn is used to determine the grouping of statements.
Example:
if 5 > 2:
print("Five is greater than two!")
Python will give you an error if you skip the indentation: if 5 > 2:
print("Five is greater than two!")
Comments:
Comments are non-executable statements.
Comments are text notes added to the program to provide explanatory information about the source code.
Python supports two types of comments:
o Single Lined Comment
o Multi Lined Comment
Single lined comment:
In case user wants to specify a single line comment, then comment must start with # symbol.
Example: # This is single line comment.
Sep Attribute(separator)
By default, the print function places a single space in between the items it prints. Print uses keyword arguments
named sep to specify the string to use insert between items. The name sep stands for separator. The default value
of sep is the string ' ', containing single space. The program sep.py shows the sep keyword customizes print’s
behaviour.
Program to illustrate sep: printsep.py C:\>python Printsep.py is 10
w, x, y, z = 10, 15, 20, 25 15 20 25
print(w, x, y, z) 10,15,20,25
print(w, x, y, z, 10 15 20 25
sep=' , ') 10:15:20:25
print(w, x, y, z, sep=' ') 10-----15-----20 -------- 25
print(w, x, y, z, sep=' : ')
print(w, x, y, z, sep='- ')
1. import math
pie=math.pie
print(“The value of oi is:”,pie)
if statements: A one-way if statement executes the statements if the condition is true. The syntax for a one- way
if statement is:
if boolean-expression:
statement
if_elif_else statement : In python we can define a series of conditionals (multiple alternatives) using if for the first
one, elif for the rest, until the final (optional) else for anything not caught by the other conditionals.
Syntax: if condition1:
Statement 1
elif condition2:
Statement 2
elif condition3:
Statemen
t 3 else:
Statement 4
Loops : Execution of a set of statements in a program repeatedly based on condition is called looping which is also
referred to as iteration. The statements in a loop are executed again and again as long as particular logical
condition remains true. There are two looping constructs in python – for and while.
Note 1: Here body of the loop is indented with respect to the while statement.
2. The statements within the body of the while loop must ensure that the condition eventually becomes false; otherwise it
becomes to an infinite loop.
e.g.1: While1.py
Program to print “Python programming” 10 times count = 0
while count < 10:
print(" Python programming n!") count = count + 1
for Loop: The for loop is used to iterate over the elements of a sequence. It means for loop executes a group of
statements repeatedly depending on number of elements in the sequence. A loop of this type is called a counter-
controlled loop.
In general, the syntax of a for loop is: c:\>python Demo.py
for var in sequence: R
statements A
e.g.: Program to display characters of a string using for loop J
str=‘RAJA’ A
for ch in str:
print(ch)
Built-in function range() : Python built-in function range() generates the integer numbers between the given start
integer to the stop integer, i.e. it returns a range object. Using for loop, the range() function iterates over a sequence of
numbers .
range () takes 3 arguments. Out of the three, 2 arguments start and step are optional. A start argument is a starting number
of the sequence. i.e., lower limit. By default, it starts with 0 if not specified.
1. A stop argument is an upper limit. i.e., generate numbers up to this number.
2. The step is a difference between each number in the result. If not specified, the default value of step is 1.
Continue: A continue statement will skip to the next iteration of the loop bypassing the rest of the current block
but continuing the loop. It is used only inside loop.
Example: continue1.py
for i in (0,1,2,3,4,5): Note that 2 and 4 aren't printed, since continue goes
if i == 2 or i == 4: to the next iteration instead of continuing on to
continue print(i) when i == 2 or i == 4.
print(i) Executing this loop now prints: 0 1 3 5
Example: In the provided code, when i is equal to 5, it prints "exit" and attempts to exit the Python
interpreter using the exit() function. If i is not equal to 5, it prints the value of i.
for i in range(10):
if i == 5:
print(exit)
exit()
print(i)
Output:
0
1
2
3
4
Use exit() or Ctrl-D (i.e. EOF) to exit
******************************END***************************