0% found this document useful (0 votes)
14 views23 pages

Python (SEP) Unit 1

Uploaded by

sujithtm2002
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)
14 views23 pages

Python (SEP) Unit 1

Uploaded by

sujithtm2002
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/ 23

PYTHON PROGRAMMING

BY
Smt.ANURADHA T S , Assistant Professor

Department of Computer Science


PYTHON PROGRAMMING PYTHON PROGRAMMING BASICS

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

Anuradha T S Assistant Professor 3


PYTHON PROGRAMMING PYTHON PROGRAMMING BASICS
Java programs are verbose. Python programs are concise and compact.
Declaration of variable is compulsory Type declaration is NOT required.
Type discipline is static and weak Type discipline is dynamic and string
It has while, for and do-while loops It has while and for loops
It has switch-case statement It does not have switch-case statement
The variable in for loop does not The variable in the for loop incremented
incremented automatically. automatically.
Memory allocation and de-allocation is Memory allocation and de-allocation is done
automatically by JVM automatically by PVM.

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

The following table lists all the important versions of Python:

Anuradha T S Assistant Professor 4


PYTHON PROGRAMMING 3Sem BCA (SEP)

Version Release Date Important Features


Python 0.9.0 February 1991 Classes with inheritance,
exception handling,
functions, modules
Python 1.0 January 1994 Functional
programming tools
(lambda, map,
filter, reduce);
support for complex
numbers; functions
with
keyword arguments
Python 2.0 October 2000 List comprehensions;
cycle- detecting
garbage collector;
support for Unicode
Python 3.0 [Py3k] December 2008 Backward
incompatible; print
keyword changed to
print()
Function
Python 3.6 December 2016 raw_input() function
deprecate
d; unified
str/unicod
e types
Python 3.6.5 March 2018 Utilities for automatic
conversion of
Python 2.x code
Python 3.7.0 May 2018 New C API for
thread-local storage;
built-in breakpoint();
data classes, context variables
Python 3.8 October 2019 Assignment
expression;
positional-only
parameters;
parallel file system
cache for
compiled bytecode files
Python 3.9 October 2020 Dictionary merge &
update operators;
new removeprefix()
and removesuffix()
string
methods; built-in
generic types
Python 3.13.7 August 2025 Latest stable version;
performance
improvements, bug
fixes, updated
standard libraries,
enhanced typing
Features

Steps to Install Python (Windows)


Anuradha T S Assistant Professor
PYTHON PROGRAMMING 3Sem BCA (SEP)
1. Download Python
• Go to the official Python website: https://www.python.org/downloads/windows/
• Click 'Download Python 3.13.7 (64-bit)' (choose 32-bit only if your PC is older).

2. Run the Installer


1. Double-click the downloaded file (python-3.13.7-amd64.exe).
2. Tick the box 'Add Python 3.13 to PATH.'
3. Click 'Install Now' for the recommended installation.

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.

5. (Optional) Install an Editor/IDE


• You can use IDLE (installed automatically with Python) or install VS Code or PyCharm for better coding
experience.

Getting Started With Python


Python shell
 Python provides a Python Shell, which is used to execute a single Python command and display the result.
 It is also known as REPL (Read, Evaluate, Print, Loop), where it reads the command, evaluates the
command, prints the result, and loop it back to read the command again.
 Python shell is like a window, which gives you access to the Python interactive mode.
 It also has a file editor that lets you create and edit existing Python source files.

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:

Anuradha T S Assistant Professor


PYTHON PROGRAMMING 3Sem BCA (SEP)

 What you are seeing is called Python Shell.


 >>>is known as prompt string, it simply means that Python shell is ready to accept you commands.
 Python shell allows you type Python code and see the result immediately.

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.

Simple python Program


Create a new file named first.py and following code to it:

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

Anuradha T S Assistant Professor


PYTHON PROGRAMMING 3Sem BCA (SEP)
Python Virtual Machine (PVM) or Interpreter
Python converts the source code into byte code. Byte code represents the fixed set of instructions
created by Python developers representing all types of operations. The size of each byte code instruction is 1
byte.
The role of PVM is to convert the byte code instructions into machine code. So that the computer can
execute those machine code instruction and display the final output. The PVM is also called as interpreter.

PYTHON BASICS:
Elements of Python

Tokens: Tokens are the smallest individual unit in a program.

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:

and del For lambda true


as elif From Not try
assert else Global Or while
break except If Pass with
class exec Import Print yield
continue false In Raise
def finally Is Return

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

Anuradha T S Assistant Professor


PYTHON PROGRAMMING 3Sem BCA (SEP)
Data types:

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

int data type:


 The int data type represents positive or negative whole numbers (without fraction or
decimal).
 In Python there is no limit to how long an integer value can be.
 Example. a=10 b=-10

float data type:


 The float data type represents floating point number. A floating point number isa number with
fraction.
 Floating point numbers can also be written in scientific notation using
exponentiation format.
 A floating point number is accurate up to 15 decimal places.
 Example. c=2.0
d=-29.45
x=2.5E4

complex data type:


 A complex number is number is written in the form of x +yj or x+yJ.
 Here x is the real part and y is the imaginary part.
 Example. a= 5 +6j
b= 2.5 + 6.2J

Anuradha T S Assistant Professor


PYTHON PROGRAMMING 3Sem BCA (SEP)
type() function:
We can use the type() function to know which class a variable or a value belongs to
Example
a=5
print(a, "is of type", type(a))b = 2.0 print(a,
"is of type", type(b))

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

str data type :


The str represents string data type. A string is a collection of character enclosed in single or double quotes.
Both are valid.

Example
str=”python”
# str is name of string variable, string value is python.

 The [] operator used to retrieve specified character from the string.


 The string index starts from 0. Hence, str[0] indicates the 0th character in the string.
Example
str=”python”
print(str) # it display - python
print(str[0]) # it display –t
print(str[2:4]) # it display 2nd to 4th character print(str[-1])
#it display first character from end – r

list data type:


 A List is a collection which is ordered and changeable.
 A list is similar to array. Lists are represented by square brackets [] and the elements are separated by
comma.
 The main difference between a list and an array is that a list can store different datatype elements, but an
array can store only one type of elements.
 It allows duplicate members.
 List can also grow dynamically in memory but the size of array is fixed and they cannot grow
dynamically.

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

Anuradha T S Assistant Professor


PYTHON PROGRAMMING 3Sem BCA (SEP)
print(list[1:3]) # it display 3.5, -20
list[1]=1.5 # replace 1st location element by 1.5

tuple data type:


 A tuple is similar to list.
 A tuple contains group of elements which can be different types.
 The elements in the tuple are separated by commas and enclosed in parentheses ().
 Tuples once created cannot be modified.
 The tuple cannot change dynamically. That means a tuple can be treated as read-only list.

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

Set data type:


To create a set, we should enter the elements separated by comma inside a curly brace.
Example
s = {10,30,5, 30,50}
print(s)

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.

The update() method used to add new elements to a sets.update([25,15])


print(s) #output: {10,5,15,30,25,30}

The remove() method used to remove a particular element from thes.remove(30)


print(s) # it display: {10,5,15,25,30}

Frozen set data type:


 Frozen set is just an immutable version of a Python set object.
 While elements of a set can be modified at any time, an element of frozen set remains the same
after creation.
 Due to this, frozen sets can be used as key in Dictionary or as element of another set.
Anuradha T S Assistant Professor
PYTHON PROGRAMMING 3Sem BCA (SEP)

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.

Anuradha T S Assistant Professor


PYTHON PROGRAMMING 3Sem BCA (SEP)
Arithmetic operator:
These are the operators which are used to perform arithmetic operations,

Symbol Description Example-1


5+6
+ Addition
11
10-5
- Subtraction
5
5*6
* Multiplication
30
7/3
/ Division
2.333
5%2
% Remainder / Modulo
1
2**3
** Exponentiation
8
7 // 3
// Integer Division
2

Relational operator:
These are the operators which are used to perform comparison,

Symbol Description Example-1


7<10
< Less than
True
7 >10
> Greater Than
False
7<=10
<= Less than or equal to
True
7>=10
>= Greater than or equal to
False
7!=10
!= , <> Not equal to
True
7==10
== Equal to
False

Logical operator:
These are the operators which are used to perform combining two or more expressions,

Symbol Description Example-2


If any one of the operand istrue,
7<=10 or 7 ==10
Or then condition
True
becomes TRUE
If both the operands aretrue,
And then the 7<10 and 7 >20
condition becomes TRUE False
Reverse the state of
Not not 7<10 False
operand / condition

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

Variations of Assignment Operators:


Symbol Description Example-1
added and assign back the result
>>> x+=27
+= to left operand

subtracted and assign back the


>>> x-=23
-= result to left operand

multiplied and assign back


>>> x*=210
*= the result to left operand

divided and assign back the >>> x/=2


/=
result to left operand 2

Bit wise operator:


These are the operators which are used to perform operation based on bits.

Symbol Description Example


| Performs binary OR operation 5 | 3 gives 7
Performs binary AND
& 5 & 3 gives 1
operation
Performs binary XOR
~ 5 ^ 3 gives 6
operation
Performs binary one's
^ ~5 gives -6
complement operation
Left shift operator: The left-hand
side operand bit is moved left by
<< the number specified on the right- 0010 << 2 gives 8
hand side (Multiply by 2)
Left shift operator: The left-hand
side operand bit is moved left by
>> the number specified on the right- 2 gives 1
hand side (Divided by 2)

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:

Anuradha T S Assistant Professor


PYTHON PROGRAMMING 3Sem BCA (SEP)

Symbol Description Example

Returns True if the specified x = [1,2,4,6,8]


In operand is found in the sequence 3 in x false

Returns True if the specified x = [1,2,4,6,8]


Not in operand is found in the 3 not in x
sequence true

Identity operator:
Identity operators compare the memory locations of two objects.There are two Identity
operators are:

Symbol Description Example 1 Example 2


X=10 x=[1,2,3]
Is
Y=10 y=[1,2,3]
Returns True if two variables point to
the same object and False, otherwise X is Y x is y
true false
X=10 x=[1,2,3]
is not
Y=10 y=[1,2,3]
Returns False if two variables point to
the same object and True, otherwise X is not Y x is not y
false true

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:

Operator precedence affects how an expression is evaluated.

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

Anuradha T S Assistant Professor


PYTHON PROGRAMMING 3Sem BCA (SEP)
Multiplication gets evaluated before the addition operation

>>> (10+10)*2 40

Parentheses () overriding the precedence of the arithmetic operators

Association:
Operator Precedence and Associativity in Python

This table lists all operators from the highest precedence to the lowest precedence.
Precedence Operators Description Associativity

1 () Parentheses Left to right

2 x[index], x[index:index] Subscription, slicing Left to right

3 await x Await expression N/A

4 ** Exponentiation Right to left

Positive, negative, bitwise


5 +x, -x, ~x Right to left
NOT

Multiplication, matrix,
6 *, @, /, //, % division, floor division, Left to right
remainder

7 +, – Addition and subtraction Left to right

8 <<, >> Shifts Left to right

9 & Bitwise AND Left to right

10 ^ Bitwise XOR Left to right

11 | Bitwise OR Left to right

Anuradha T S Assistant Professor


PYTHON PROGRAMMING 3Sem BCA (SEP)

in, not in, is, is not, <, <=, >, Comparisons, membership
>=, !=, == tests, identity tests
12 Left to Right

13 not x Boolean NOT Right to left

14 and Boolean AND Left to right

15 or Boolean OR Left to right

16 if-else Conditional expression Right to left

17 lambda Lambda expression N/A

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 assignment statement creates new variables and gives them values:


>>> x=10
>>> course="BCA "

An print statement is something which is an input from the user, to be printed / displayed on to the screen (or ) monitor.

>>> print("Degree college")

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.

Multi lined Comment:


Multi lined comment can be given inside triple double quotes (“””) or triple single quotes (‘’’).
Example: “”” This Is
Multiline comment’’’

Built-in Functions- Console Input and Console Output


Console Input-Input(): To provide input to a computer, python provides the input statement.
If the input provided is not correct then either syntax error or exception is raised by python. Programs may use the
input function to obtain information from the user. The simplest use of the input function assigns a string to a
variable:
x = input()
The parentheses are empty because the input function does not require any information to do its job. Using
input.py demonstrates that the input function produces a string value.

Program to accept a string from the keyboard.


C:\>python Input.py Enter
a string: Tanvi
str = input("Enter a string:") Entered string is Tanvi
print("Entered string is", str)

Console Output- Print()


The print function enables a python program to display textual information to the user.
The print a line of text, and then the cursor moves down to the next line so any future printing appears on the next
line.

Anuradha T S Assistant Professor


PYTHON PROGRAMMING 3Sem BCA (SEP)
print('enter an integer value:')
The print statement accepts an additional argument that allows the cursor to remain on the same line as the
printed text:
print('enter an integer value:', end=' ')
The expression end=' ' is the keyword that cause the cursor to remain on the same line as the printed text. Without
this keyword argument, the cursor moves down to the next line after printing the text.

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='- ')

Formatting numbers and strings


Format function is used to return a formatted string for displaying numbers in a certain desirable format. e.g.:
Following code computes interest, given the amount and the annual interest rate.
>>>amount = 12618.98
>>>interestRate = 0.0013
>>>interest = amount * interestRate
Interest is 16.40
>>>print("Interest is",format(interest, ‘0.2f ‘))
The syntax to invoke this function is format(item, format-specifier)
Where item is a number or a string and format-specifier is a string that specifies how the item is formatted. The
function returns a string.

Place holder substitution within a formatting


string print('{0} {1}'.format(2, 10**2))
This expression has two parts:
'{0} {1}': This is known as the formatting string. It is a python string because it is a sequence of characters enclosed
with quotes. This formatting string serves as a pattern that the second part of the expression will use. {0} and {1} are
placeholders, known as positional parameters, to be replaced by other objects. This formatting string, therefore,
represents two objects separated by a single space.

Conversion of data types


Depending on the type of data, Python internally assumes the data type for the variable. But sometimes, the
programmers want to convert one data type into another type explicitly. This is called type conversion or coercion.
This is possible by mentioning the data type with parameters.
e.g.: To convert a number into integer type, we can write int (num).
 int(x) is used to convert the number x into int type.
x=15.56
int(x) will display 15

Anuradha T S Assistant Professor


PYTHON PROGRAMMING 3Sem BCA (SEP)
Python Libraries
A Python library is a collection of related modules. It contains bundles of code that can be used repeatedly in
different programs. It makes Python Programming simpler and convenient for the programmer.
The Python Standard Library contains the exact syntax, semantics, and tokens of Python. It contains built -in modules
that provide access to basic system functionality like I/O and some other core modules. Most of the Python Libraries
are written in the C programming language. The Python standard library consists of more than 200 core modules. All
these work together to make Python a high-level programming language. Python Standard Library plays a very
important role.
The commonly used libraries:
1. TensorFlow: This library was developed by Google in collaboration with the Brain Team. It is also used
in machine learning and deep learning algorithms.
2. Matplotlib: This library is responsible for plotting numerical data and that’s why it is used in data analysis.
3. Pandas: Pandas are an important library for data scientists.
4. Numpy: The name “Numpy” stands for “Numerical Python”. It is the commonly used library. It is a popular
machine learning library that supports large matrices and multi-dimensional data.
5. SciPy: The name “SciPy” stands for “Scientific Python”. It is an open-source library used for high-level
scientific computations.

Importing Libraries with Examples


Import in python is similar to #include header_file in C/C++. Python modules can get access to code from
another module by importing the file/function using import.
import module_name
When the import is used, it searches for the module initially in the local scope by calling import () function. The
value returned by the function is then reflected in the output of the initial code.

1. import math
pie=math.pie
print(“The value of oi is:”,pie)

from math import *


print(pi)
print(factorial(6))
All the functions and constants can be imported using *.

Python Control Flow


Control statements are the statements which control or change the flow of execution. The following are the control
statements available in Python.
Types of Control Flow in Python:
1. Decision-making statements: such as if, if-else, nested-if, and if-elif-else, that decide the
direction of the flow of program execution based on some conditions
2. Loop statements: such as for and while, that repeat a block of code for a specified number of
times or until a condition is met.
3. Control statements: such as break, continue, and pass, that modify the behavior of the loop
statements

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

Anuradha T S Assistant Professor


PYTHON PROGRAMMING 3Sem BCA (SEP)

• The reserved word if begins as if statement.


• The condition is a Boolean expression that determines whether or not the body will be
executed . A colon (:) must follow the condition.
• The block (one or more statements) is executed if the condition is true. The statements
within the block must be indented the same number of spaces from the left.
e.g. : Simpleif.py
n= 1
if n= 1:
print('one')
if -else statements
A two-way if-else statement decides which statements to execute based on whether the condition is true or false. The
syntax for a two-way if-else statement:
if boolean-
expression:
statement1
else:
statement 2
e.g. : if_else.py
x=10
if x%2==0:
C:\>python if_else.py
print (x,"is even number")
10 is even number
else:
print (x,"is odd number ")

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

1. Program to know if a given number is zero, positive or negative.


num=-5
if num==0:
c:\>python demo.py
print (num,”is -5 is negative
zero”) elif num>0:
print(num,”is
positive”) else:
print(num,”is negative”)

Nested if statements: A series of tests can written using nested if statements.

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.

Anuradha T S Assistant Professor


PYTHON PROGRAMMING 3Sem BCA (SEP)
Syntax of while loop is:
while condition:
Body of 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 .

Syntax:range (start, stop, step)

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.

The range function has two versions.


1. range(a)
2. range(a, b, k).
range(a) is the same as range(0, a).
In range(a, b, k), k is used as step value. The first number in the sequence is a. Each successive number in the
sequence will increase by the step value k. b is the limit. The last number in the sequence must be less than b. e.g.:1.
For1.py
for i in range(4): 0
print (i) .......................................................... >> 1
2
3
4

Anuradha T S Assistant Professor


PYTHON PROGRAMMING 3Sem BCA (SEP)
3. Program to display odd numbers between 1 and 10
1
for i in range(1,10,2) 3
5
print(i)
7
9

The break and continue in loops


break statement: When a break statement executes inside a loop, control flow comes out of the loop immediately:
e. g. : break1.py
i=0 c:\>python break1.py
0
while i < 7:
1
print(i)
2
if (i == 4): 3
print("Breaking from loop") 4
break Breaking from loop
i +=1
The loop conditional will not be evaluated after the break statement is executed. Note that break statements are only
allowed inside loops. Executing the following prints every digit until number 4 when the break statement is met and
the loop stops:
The beak statements can also be used inside for loops,

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

Python Exit Command using exit() Function


The exit() in Python is defined as exit commands in python if in site.py and it works only if the site module
is imported so it should be used in the interpreter only. It is like a synonym for quit() to make Python more
user-friendly. It too gives a message when printed and terminate a program in Python.

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***************************

Anuradha T S Assistant Professor

You might also like