0% found this document useful (0 votes)
41 views42 pages

Unit Ii Final

This document provides an overview of Python programming, covering its features, applications, and data types. Python is a high-level, open-source language known for its readability and versatility, used in web development, game development, machine learning, and more. It also explains the Python interpreter, interactive mode, debugging, and various data types such as integers, floats, booleans, and strings.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views42 pages

Unit Ii Final

This document provides an overview of Python programming, covering its features, applications, and data types. Python is a high-level, open-source language known for its readability and versatility, used in web development, game development, machine learning, and more. It also explains the Python interpreter, interactive mode, debugging, and various data types such as integers, floats, booleans, and strings.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 42

UNIT II

DATA TYPES, EXPRESSIONS, STATEMENTS

2.1 Introduction
A Python program is read by a parser. Python was designed to
be a highly readable language. The syntax of the Python
programming language is the set of rules which defines how a
Python program will be written.

Need of Python
Python is an open source, object-oriented, high-level
powerful programming language.
Developed by Guido Van Rossum in the early 1990s. Named
after Monty Python
Python runs on many Operating Systems such as Unix, Mac,
and on Windows etc.
Python Program
Python programs are composed of modules
Modules contain statements

 Statements contain expressions


 Expressions create and process objects
Features of Python
Open Source: Python is publicly available open source software,
any user can utilize source code available that doesn’t cost anything.
Open Source Software means free license to use source code by any
user.
Easy-to-learn: Popular scripting language, clear and easy
syntax, no type declarations, automatic memory management, high-
level data types and operations, design to read and write fast. Code
size is shorter compared to C, C++, and Java.
Interactive Mode: Python has support for an interactive mode
which allows interactive testing and debugging of snippets of code.
GUI Programming: Python supports GUI applications that can
be created and ported to many system calls, libraries and windows
system.

High-level Language:

Python is an example of a high-level language like C, C++, Perl,


and Java with low-level optimization.

Portable:

High level languages are portable, which means they are able to
run across all major hardware and software platforms with few or no
change in source code. Python is portable and can be used on Linux,
Windows, Macintosh, Solaris, FreeBSD, OS/2, Amiga, AROS, AS/400
and many more.
Object-Oriented: Python is a full-featured object-oriented
programming language, with features such as classes, inheritance,
objects, and overloading.
APPLICATIONS OF PYTHON

 System utilities (system admin tools, command line programs).


 Web Development.
 Graphical User Interfaces (Tkinter, gtk, Qt).
 Internet scripting.
 Embedded scripting.
 Database access and programming.
 Game programming.
 Rapid prototyping and development.
 Distributed programming

Python Definition

Python is a high-level programming language designed to be


easy to read and simple to implement. It is open source, which
means it is free to use, even for commercial applications.
Python can run on Mac, Windows, and Unix systems.

1. Web Development

Python one of the most popular programming languages


for web development is that Python comes with a wide array of
frameworks and Content Management Systems(CMS) that
exist to simplify a web developer’s life.

Python offers many choices for web development

 Framework such as Dijango and Pyramid.


 Micro framework such as Flask and Bottle.
 Advanced content management systems such as Plone and
Dijango CMS.

Python standard library supports many internet protocols.

 HTML and XML


 JSON
 E-mail processing
 Support for FTP,IMAP,and other internet protocols.
 Easy-to-use Socket interface.

2. Game Development

 Python is also used in the development of interactive


games.
 There are libraries such as PySoy which is a 3D game
engine supporting Python 3, PyGame which provides
functionality and a library for game development.
 Games such as Civilization-IV, Disney’s Toontown Online,
Vega Strike etc. have been built using Python.

3. Machine Learning and Artificial Intelligence

Python is GitHub’s second most popular language and the most


popular language for machine learning.

Python’s stability and security make it a perfect


programming language for handling the intensive computations that
keep the Artificial Intelligence and Machine Learning systems
running. More so, Python’s vast collection of libraries facilitate the
development of models and algorithms that run modern AI and ML
systems. Some of the popular libraries for the job are:

 Sci Py for scientific and technical computing

 Pandas for data analysis and manipulation

 Keras for Artificial Neural Networks

 TensorFlow for Machine Learning tasks, especially Deep Neural


Networks ○ NumPy for complex mathematical functions and
computation

 Scikit-Learn for working with various Machine Learning models

4. Data Science and Data Visualization


Data is money if you know how to extract relevant information
which can help you take calculated risks and increase profits.
Libraries such as Pandas, NumPy help you in extracting information.
visualize the data libraries such as Matplotlib, Seaborn, which are
helpful in plotting graphs and much more. This is what Python offers
you to become a Data Scientist.

5. Desktop GUI

 We use Python to program desktop applications. It


provides the Tkinter library that can be used to develop user
interfaces.
 There are some other useful toolkits such as the
wxWidgets, Kivy, PYQT that can be used to create
applications on several platforms.

6. Web Scraping Applications

Python is a savior when it comes to pull a large amount of data


from websites which can then be helpful in various real-world
processes such as price comparison, job listings, research and
development
7. Business Applications

Python is also used to build ERP and e-commerce systems.


 Odoo is an all in the management software that offers a range of
business applications that form a complete suite of enterprise
management applications.

 Tryton is a three-tire high -level general purpose application


platform.

8. Audio and Video Applications


 Python to develop applications that can multi-task and
also output media.

 Video and audio applications such as TimPlayer, Cplay


have been developed using Python libraries. They provide
better stability and performance in comparison to other
media players.

9. CAD Applications

 Computer-Aided Designing is quite challenging to make as


many things have to be taken care of. Objects and their
representation, functions are just the tip of the iceberg
when it comes to something like this.

 Python makes this simple too and the most well-known


application for CAD is Fandango

10. Embedded Applications

 Python is based on C which means that it can be used to


create Embedded C software for embedded applications.

 This helps us to perform higher-level applications on


smaller devices which can compute Python.

 We use python in a variety of applications. For example,


Digital Cameras, Smart phones, Raspberry Pis, and
Industrial Robots are just some of the many devices that
can be controlled with Python.

2.2 Python interpreter and interactive mode, debugging

2.2.1 Python Interactive Mode


Python has two basic modes interpreter and interactive mode.
Interactive mode is a command line shell which gives immediate
feedback for each statement, while running previously fed statements
in active memory. As new lines are fed into the interpreter, the fed
program is evaluated both in part and in whole. To start interactive
mode, simply type “Python” without any arguments.
One of the benefits of working with an interpreted language is
that you can test bits of code in interactive mode before you put them
in a script.
In this mode the prompts for the next command with the primary
prompt, usually three greater-than signs (>>>); for continuation lines
it prompts with the secondary prompt, by default three dots (...). The
interpreter prints a welcome message stating its version number and
a copyright notice before printing the first prompt:
Invoking the interpreter without passing a script file as a
parameter brings up the following prompt-

Source Interpreter
Processing or Processing Output
Code
Intermediate

 The first three lines contain information about the interpreter and the operating
system it is running on.
 The last line >>> is a PROMPT(chevron)
 The version number is 3.6.0. It begins with 2, if the version is python 2.
 That indicates that the interpreter is ready to enter code. If the user types a line
of code and hits Enter, the interpreter displays the result.
Example :
>>>5+7
12
>>>print(“HELLO”)
HELLO
>>>num=10
>>>num=num/2
>>>print(num)
5.0

2.2.2 Python Interpreter Mode

Python is a flexible and dynamic language that user can use in


different ways. An interpreter is a program that reads and executes
code line by line. This includes source code, pre-compiled code and
scripts. Python programs are executed by an interpreter.

The interpreter mode is the mode where the scripted and finished .py files are run in the
python interpreter.
2.2.3 Debugging

Debugging is the process of finding and fixing the errors in your program.
Error:
An error can sometimes called a “bug” is anything in the code that prevents a program
from compiling and running correctly .

Types of error:
There are three types of error
 Compile time error
 Run time error
 Logical error
Compile time error:
 Errors that occur during compilation are called compile time error.
 Compilation is nothing but the process the computer takes to convert a high level
programming language into machine language that the computer an understand.
 It can be classified into two categories
1. Syntax error
2. Semantic error
1. Syntax error:
 Syntax errors occur when rules of a programming language are misused.
 Syntax refers to formal rules governing the construction of valid statements in a
language.
 Example :
print(HELLO) //wrong syntax
print(“HELLO”) //correct syntax
2. Semantic error:
 It occurs when statements are not meaningful.
 Semantic refers to the set of rules which gives the meaning to a statement.
 Example:
X*Y=Z
Logical error:
 These are encountered when the program does not give he desired output due to
wrong logic of the program.
 For example, assigning a value to the wrong variable may cause a series of
unexpected program errors.
 Multiplying two numbers instead of adding them together may also produce
unwanted results. So these types of errors are referred to logical errors.
Runtime error:
 Errors that occur during the execution of a program are called runtime errors.
 Some runtime errors stops the execution of the program which is called “crashed” or
“abnormally terminated”.

2.3 VALUES AND TYPES


2.3.1 Value

A value is number or word which is manipulated by the program.


Example values are 2,4.20,’M’ and “Hello”( These values belong to different
datatypes)
These objects are classified into different classes, or data types: 2
is an integer, and “Hello”is string, so-called because it contains a
string or sequence of letters and the interpreter can identify strings
because they are enclosed in quotation marks.
2.3.2 Types(Data types)

Every value in Python has a data type. It is a set of values and


the allowable operations on those values. There are various types of
data/values in python programming as follows,

(i) Integer
(ii) float
(iii) Boolean
(iv) String
(v) list
(i) Integers

Integers are whole number without decimal point. The integer (or
int) data type indicates values that are whole numbers. Integer can be
positive or negative values. Integer have unlimited size in python.
Example
>>> a = 6
>>> b = -25
>>> c = 9587
>>>print b
-25
>>> 1 + 2
3
>>> a=5
>>> type(a)
<type ‘int’>

(ii) Float

Numbers with a decimal point are called floating-point numbers.


Float values are also called Real number. Float values are written with a
decimal point that segregates the integer from the fractional numbers.
Floating point numbers can be written using scientific notation where ‘e’
or ‘E’.
Example
>>> a = 6.25
>>> 5.3e2
530.0
>>> 17.45E5
1745000.0
>>>type(b)
<type ‘float’>
r Integers
(iii) Boolean
Boolean is a data type named after George Boole (1815-1864).
A Boolean variable can take only two values, True or False. The main
use of Boolean data type is to represent result of logical expressions.
Boolean data type is the primary result of conditional statement.

Example
>>> print(5 > 3)
True
>>> print ( 6 = = 6)
True
>>> print (5 < 3)
False
>>>test = (3 < 4)
<type ‘bool’>
Boolean operators
Boolean operations are performed using the and, or, and not
keywords in Python
‘and’ operator:

A B A and B
True True True
True False False
False False False
False False False
‘and’ operator:

A B A or B
True True True
True False True
False False True
False False False
‘not’ operator:

A not A
True False
False True

Example

>>> (30>29) and (20>17)


True
>>> (30>29) and (20<17)
False
>>> (30>29) or (20<17)
True
>>> (10<5)
False
>>> not(10<5)
True
>>>(10>20)
False
>>>not(10>20)
True

The operators follow some precedence rules which would make


the parentheses in the third line and in the last obsolete. Note that the
operator is implicitly chained in the following Boolean expressions:
a < b < c # same as: a < b and b < c
a == b == c # same as: a == b and b == c
(iv) Strings:
Strings in python are collection of characters represented in the quotation
marks. Python allows either single quotation (‘ ‘) or double quotation (“ “) or Triple
quotation(“’ “’). Strings are the most popular types in Python and it is an ordered
sequence of characters. Creating strings is as simple as assigning a value to a
variable. Subset of strings can be represented using the slice operator ([ ]) and [:]
with indexes starting at 0 in the beginning and -1 at the end.
Example :
str= String variable
str=”Hello,World!”

Code Comment Result


print str Prints complete string Hello World!
print str[0] Prints first character of H
the string
print str[-1] Prints last character of !
the string
print str[1:5] 1.Prints character Ello
str[start_at:end_at-1] starting from index 1
to 4

print str[2:] Prints string starting at Llo,World!


index 2 till end of the
string
print str*2 Asterisk (*) is the Hello World!Hello
repetition operator. It World!
prints the string two
times.
print str+”hai” Plus (+) is concatenate Hello World!Hai
operator. It prints
concatenated strings
Indexing
Indexing is the way to refer the individual items within an iterable by
its position. The python index() method helps you to find the index position
of an element or an item in a string of characters or a list of items. Python
supports two types of indexing. They are
 Positive indexing
 Negative indexing
Positive indexing
Positive indexing helps in accessing the string from the beginning.
Negative indexing
Negative indexing helps in accessing the string from the end.
Example

String H E L L O
Positive 0 1 2 3 4
indexing
Negativ -5 -4 -3 -2 -1
e
indexing
Example:
>>>a=”Hello”
>>>a
Hello
<class ‘str’>
>>>a[0]
‘H’
>>>[-1]
‘o’
Escape sequence Characters
An escape character lets you use characters that are otherwise impossible to put
into a string. An escape character consists of a backslash
(\) followed by the character you want to add to the string.

Lists the escape characters:

Escape
Purpose Example
Characters
Prints single >>> print("India\'s")
\’
Quote India's
>>> print("India is \"our\"
Prints double
\” Country")
quotes
India is "our" Country
Prints TAB >>> print("hai\thello")
\t
Space hai hello
>>> print("hai\nhello")
Prints NEW
\n hai
line space
hello
Print Back >>> print("hai\\hello")
Slash hai\hello

(v) Lists:
Python offers a range of compound datatypes often referred to as sequences.
List is one of the most frequently used and very versatile datatype used in Python. In
Python programming, a list is created by placing all the items (elements) inside a
square bracket [ ], separated by commas(,). It can have any number of items and
they may be of different data types (integer, float, string etc.).

Example
Empty List
>>> list=[ ]
>>> list
[]
Integer List
>>> list1=[1,2,3]
>>> list1
[1, 2, 3]
List with mixed data types
>>> list2=[10,25.5,'Agnes']
>>> list2
[10, 25.5, 'Agnes']
List operations
>>> print(list1 + list2)
[1, 2, 3, 10, 25.5, 'Agnes']

>>> list3=['Agnes','10']
>>> print(list3 * 2)
['Agnes', '10', 'Agnes', '10']
Nested List
>>> list4=["Pavi",
[10,20,30],'Agnes']
>>> list4
['Pavi', [10, 20, 30], 'Agnes']

List Index
User can use the index operator [] to access an item in a list. Index starts from
0. So, a list having 5 elements will have index from 0 to 4.
Trying to access an element other than this will raise an Index Error. The index
must be an integer. We can’t use float or other types, if given means this will result
into Type Error.

Example
>>> list=[10,20,30,40,50]
>>> print(list[0])
10
>>> print(list[3])
40
>>> list=['a', 'b', 'c', 'd']
>>> list[3]
'd'
>>> list=['Pavi', 'Agnes', 'Priyanka']
>>> print(list[2])
Priyanka
>>> list4=["Pavithra",
[10,20,30],'Santhosh']
>>> list4[0]
'Pavithra'

>>> list4[0][0]
'P'
>>> list4[1][0]
10
>>> list4[2][0]
'S'
2.4 VARIABLES
A variable is a reserved memory location to store values. In other words a variable in
a program gives data to the computer to work on it. Python variables do not need explicit
declaration to reserve memory space. The declaration happens automatically when you
assign a value to a variable. The equal sign (=) is used to assign values to variables.
Every value in Python has a data type. Different data types in Python are Numbers,
List, Tuple, Strings, Dictionary, etc. Variables can be declared by any name which starts
with alphabet.
Rules for variables:
 Variables can be a combination of letters in lower case (a to z) or upper case (A to Z)
or digits (0 to 9) or an underscore (_).
 It can be of any length.
 Example :
a, name, a12, A, A12, reg_no // these are valid variable declaration
 Variable cannot start with a digit.
 Keywords cannot be used as variables,
 We cannot use special symbols like ! ,@,#,$,% etc.,

Keywords in Python:
 Keywords are the reserved words in python.
 We cannot use a keyword as variable name, function name or any other identifier.
 Keywords are case sensitive.
Keyword Description
And Logical and
As Part of the with-as statement
Assert Assert that something true
Break Stop this loop right now
Class Define a class
Continue Continue the loop
Def Define a function
Del Delete from dictionary
Elif Else if condition
Else Else condition
Except For any exception, do this
Exec Run a string as python
Finally Ignore exceptions
For For loop
From Get specific parts of a module
Global Declaring a global variable
If If condition
Import Import a module part of for-loops
In Part of for-loops
Is Like = = to test equality
Lambda Anonymous function
Not Logical not
Or Logical or
Pass This block is empty
Print Print this string
Raise Raise an exception
Return Function return value
Try Try this block
While While loop
With With an expression
Yield Pause here and return to caller
All keywords should be written in lower case

Example for variable

>>> name="Pavi"
>>> print(name)
Pavi
>>> age=24
>>> print(age)
24
>>> skills=['C', 'C++', 'JAVA', 'PHP']
>>> print(skills)
['C', 'C++', 'JAVA', 'PHP']

Here, name, age and skills are variables used in Python interactive mode.

Local & Global Variables

There are two types of variables: global variables and local variables. A global
variable can be reached anywhere in the code, a local only in the scope.
 Local variable:
Variables that are defined inside a function body.It can be accessed only inside
the function.

 Global variable:
Variable that are defined outside a function body.It can be accessed by all the
functions of program.
[

A global variable (x) can be reached and modified anywhere in the code, local
variable (z) exists only in block 3.

In Python use the same variable for rest of the program or module and declare it
global variable, while if want to use the variable in a specific function or method you use
local variable.
Operations on variables:

1. Delete a variable
Python support delete operation of variable used in the program. Keyword used to
delete the variable is “del”. This delete the variable from the memory space, when user
print or use the deleted variable it gives error message.
Example

>>> a=10
>>> print(a)
10
>>> del a
>>> print(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined, 'PHP']
2. Swap variables
Python swap values in a single line and this applies to all objects in python.
Syntax :

var1, var2 = var2, var1

Example

>>> a=10
>>> b=20
>>> print(a)
10
>>> print(b)
20
>>> a,b = b,a
>>> print(a)
20
>>> print(b)
10

2.5 Expression
An expression is a combination of values, variables, and operators. If user types an
expression on the command line, the interpreter evaluates it and displays the result.

An expression represents data item such as variables, constants interconnected with


operators. A expression is evaluated using assignment operator.
Example

>>> x=10
>>> x=x+5 //Expression
>>> x
15
>>> 10+30 //Expression
40

2.6 STATEMENTS
A statement is a unit of code that the Python interpreter can execute. A statement is
an instruction that the Python interpreter can execute. There are two kinds of statements:
print and assignment.
When you type a statement in interactive mode, the interpreter executes it and
displays the result, if there is one.
A script usually contains a sequence of statements. If there is more than one
statement, the results appear one at a time as the statements execute.
Example
print(1) //Print statement
x=10 //Assignment statement
print(x)
OUTPUT
1
10

The assignment statement produces no output. Other kinds of statements that


includes while statement, for statement, import statement, if statement which will be
discussed in forth coming chapters.

Multi-line statement

In Python, end of a statement is marked by a newline character. But we can make a


statement extend over multiple lines with the line continuation character (\).
Example

>>> a=1+2+3+\
... 4+5+6+\
... 7+8+9
>>> a
45

>>> a=(1+2+3+
... 4+5+6+
... 7+8+9)
>>> a
45

>>> a=[1+2+3+
... 4+5+6+
... 7+8+9]
>>> a
[45]

Python Indentation

Most of the programming languages like C, C++, Java use braces { } to define a block
of code. Python uses indentation.
A code block (body of a function, loop etc.) starts with indentation and ends with the
first un-indented line. The amount of indentation is up to you, but it must be consistent
throughout that block.
Generally four whitespaces are used for indentation and is preferred over tabs.
Example
for i in range(1,11):
print(i)
if i == 5:
break
2.7 TUPLE ASSIGNMENT
A tuple is a sequence of immutable Python objects. Tuples are sequences of elements
of different types, just like lists. The differences between tuples and lists are, the values of
tuples cannot be changed but values of list can be updated. Tuples use parentheses “( )”,
whereas lists use square brackets “[ ]”.
Creating a tuple is as simple as putting different comma-separated values. Optionally
you can put these comma-separated values between parentheses also. Python has a very
powerful tuple assignment feature that allows a tuple of variables on the left of an
assignment to be assigned values from a tuple on the right of the assignment.

Example

>>> tup=(10,20,30)
>>> print(tup)
(10, 20, 30)
>>> tup2=('a','b','c')
>>> tup2
('a', 'b', 'c')
>>> tup3=("prema","latha","ravi")
>>> tup3
('prema', 'latha', 'ravi')
>>> tup4=(10,20.5,'a',"prema")
>>> tup4
(10, 20.5, 'a', 'prema')

Tuple operation
>>> tup + tup2
//Concatenation
(10, 20, 30, 'a', 'b', 'c')
>>> tup * 2 //Repetition
(10, 20, 30, 10, 20, 30)
>>> tup[0]
10
Basic Tuples Operations
Tuples respond to the + and * operators much like strings; they mean concatenation
and repetition here too, except that the result is a new tuple, not a string.

Python Expression Results Description

len((1, 2, 3)) 3 Length

(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation

('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', Repetition


'Hi!')

3 in (1, 2, 3) True Membership

for x in (1, 2, 3): print x, 123 Iteration

Difference between Tuple and list

TUPLE LIST
Tuple is collection of different List is collection of different
data type values data type values
Tuple defined using parenthesis List defined using square
“( )” brackets “[ ]”
Tuples are immutable Lists are mutable
Values of tuple cannot be Values of list can be
changed or updated changed or updated
>>> tup=(10,20,30) >>> list=[10,20,30]
>>> print(tup) >>> print(list)
(10, 20, 30) [10, 20, 30]
>>> tup[1]=40 >>> list[1]=40
Traceback (most recent call last): >>> print(list)
File "<stdin>", line 1, in [10, 40, 30]
<module>
TypeError: 'tuple' object does not
support item assignment
2.8 PRECEDENCE OF OPERATORS
Python support various operators to perform mathematical operation. Basic operators in
python are Addition, Subtraction, Multiplication, Division, Exponent etc. When more than one
operator occurs in an expression, the order of the evaluation depends on the rules of
precedence. Python follow mathematical convention acronym PEMDAS. The precedence is
used to determine how an expression involving more than one operator is evaluated.
Operators with highest level of precedence are evaluated first. When operators of the
same precedence occur in same expression, then it is evaluated from left to right.

P Parenthesis First
Exponents (include power, square
E
root)
MD Multiplication and Division (left-right)
AS Addition and Subtraction (left-right)

Operator Precedence rule in Python

Operators Meaning
() Parentheses
** Exponent
+x, -x, ~x Unary plus, Unary mi- nus, Bitwise NOT
*, /, % Multiplication, Division, Modulus
+, - Addition, Subtraction
<<, >> Bitwise shift operators
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
==, !=, >, >=, <,
Comparison,
<=
is, is not, in, not in Identity, Membership operators
Not Logical NOT
And Logical AND
Or Logical OR
Hierarchy of operators in Python

1. Expression within parenthesis is evaluated first. If more than one parenthesis occurs in
same expression, then inner most parenthesis is evaluated first.
2. Unary operators are evaluated.
3. Then priority is given for multiplication and division. If both operators occur is same
expression, then it is evaluated from left to right.
4. Next addition and subtraction is performed from left to right.
5. Relational operators evaluated next.
6. Logical operations performed
7. Finally assignment operator is carried out.
Example

1. Exponent and Other operators(+, -, *, /)

Exponent evaluated first, then other operation is performed next

>>> 5**2+5 //Exponent & Addition


30
>>> 5+2**5
37
>>> 5-5**2 //Exponent & Subtraction
-20
>>> 5**2*5 //Exponent & Multiplication
125
>>> 6**2/6 //Exponent & Division
6.0

2. Multiplication and Division

Multiplication and Division have equal priority. If both operators occur is same
expression it can be evaluated from left to right.

>>> 25/5*2
10.0
>>> 50*2/4
25.0
3. Multiplication and other operators (+,-)

Multiplication is given highest priority than Addition and Subtraction. First


multiplication operator is evaluated, then addition/subtraction is performed.

>>> 5*2+6*3
28
>>> 2+7*4-5
25

4. Addition and Subtraction


Addition and Subtraction have equal priority. If both operators occur is same
expression it can be evaluated from left to right.

>>> 100+25-50+5
80
>>> 2+3-5+8-4+2-9
-3

4. Parenthesis with operators


Parenthesis holds first priority among all other operators. Hence expression inside
the parenthesis evaluated first.

>>> (2+8)*(5-2)+(8*3)
54
Answer=(2+8)*(5-2)+(8*3)
= 10*3+24
= 30+24
= 54

Example

>>> 17/2%2*3**3
13.5
Answer = 17/2%2*3**3
= 17/2%2*27
= 8.5%2*27
= 0.5*27
= 13.5
2.9 COMMENTS
Comment line is a statement which is not interpreted during the execution of the
program. Comment line is ignored during the program execution. Comments are used
mainly for the end users to understand the logic of the program.

Comments are very important while writing a program. It describes what's going on
inside a program so that a person looking at the source code does not take more time to
understand the logic.

In Python, the hash (#) symbol is used to start writing a comment. It extends up to
the newline character. Comments are for programmers for better understanding of a
program. Python Interpreter ignores comment.

Single line comment


A single line comment starts with the number sign (#) character:

Example

#This is a program to print OUTPUT


Hello Hello
print('Hello')

Multiline comment

If we have comments that extend multiple lines, one way of doing it is to use hash
(#) in the beginning of each line.
Example

#This is a multi comment OUTPUT


#To add two numbers
# To concatenate two string
a=5 5
b=6 6
print(a) 11
print(b) PaviNiva
c=a+b
print(c)
str1="Pavi"
str2="Niva"
str=str1+str2
print(str)

Another way of doing this is to use triple quotes, either single quotation
(''') or double quotation ("""). These triple quotes are generally used for multi-line strings.
But they can be used as multi-line comment as well.
Example

"""This is a multi comment OUTPUT


To add two numbers
To concatenate two string"""
a=5 5
b=6 6
print(a) 11
print(b) PaviNiva
c=a+b
print(c)
str1="Pavi"
str2="Niva"
str=str1+str2
print(str)
Illustrative Programs
[

2.10 Exchange the values of two variables

Program 1:

Exchange the values of two variables

#Python program to swap two variables


#To take input from the user
a = input('Enter value of a:')
b = input('Enter value of b:')
#create a temporary variable and swap the
values
temp = a
a=b
b = temp
print('The value of a after swapping:',a)
print('The value of b after swapping:',b)
OUTPUT
Enter value of a:10
Enter value of b:20
The value of a after swapping: 20
The value of b after swapping: 10
2.11 Circulate the value of n variables

Program 2:

Circulate the value of n variables

def circulate(A,N):
For(I in range(1,N+1):
B=A[i:]+A[:i]
print(“Circulation”,i,”=”,B)
return
X=[91,92,93,94,95,96]
Y=int(input(“Enter Y:”)) #circulating count
circulate(X,Y)

OUTPUT
Enter Y : 3
Circulation 1= 92,93,94,95,96,91
Circulation 2= 93,94,95,96,91,92
Circulation 2= 94,95,96,91,92,93

2.12 Distance between two points

Program 3:

Distance between two points

import math
x1=int(input("Enter value of x1:"))
x2=int(input("Enter value of x2:"))
y1=int(input("Enter value of y1:"))
y2=int(input("Enter value of y2:"))
distance=math.sqrt((x2-x1)**2+(y2-y1)**2))
print(“Distance between two points=”,distance)

OUTPUT
Enter value of x1:5
Enter value of x2:3
Enter value of y1:4
Enter value of y2:5
Distance between two points=2.23606797749979

Additional Program

Program 4: Test for Leap year

year=int(input("Enter year to be checked:"))


if(year%4==0 and year%100!=0 or year%400==0):
print("The year is a leap year!")
else:
print("The year isn't a leap year!")

Output

G:\PYTHON\PROGRAM>python leap.py
Enter year to be checked:2017
The year isn't a leap year!

G:\PYTHON\PROGRAM>python leap.py
Enter year to be checked:2016
The year is a leap year!

UNIT II
2 MARKS

1. Definepython
Python is an object-oriented, high level language, interpreted, dynamic and
multipurpose programming language.

2. Give the features of python.


 Easy to Use:
 Expressive Language
 Interpreted Language
 Cross-platform language
 Free and Open Source
 Object-Oriented language
 Extensible

3. What is python interpreter?


The engine that translates and runs Python is called the Python Interpreter: There
are two ways to use it: immediate mode and script mode. The >>> is called the Python
prompt. The interpreter uses the prompt to indicate that it is ready for instructions.

4. What is the difference between intermediate mode and script mode?

 In immediate mode, you type Python expressions into the Python Interpreter
window, and the interpreter immediately shows the result.
 Alternatively, you can write a program in a file and use the interpreter to
execute the contents of the file. Such a file is called a script. Scripts have
the advantage that they can be saved to disk, printed, and so on.

4. Whatis meant by value in python?


A value is one of the fundamental things—like a letter or a number—that a
program manipulates.

5. List the standard data types in


python.
Python has five standard data
Types:
 Numbers
 Strings
 List,
 Tuples
 Dictionary
6. What is meant by python numbers?
Number data types store numeric values. Number objects are created when
you assign a value to them.
Python supports four different numerical types :
 int (signed integers)
 long (long integers, they can also be represented in octal and
 hexadecimal)
 float (floating point real values)
 complex (complex numbers)

7. What are python strings?


Strings in Python are identified as a contiguous set of characters represented in
the quotation marks. Python allows for either pairs of single or double quotes. Subsets of
strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the
beginning of the string and working their way from -1 at the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the
repetition operator.
str = 'Hello World!'
print str[0] # Prints first character of
the string o/p:
H

8. Mention the features of lists in python


Lists are the most versatile of Python's compound data types. A list contains
items separated by commas and enclosed within square brackets ([]). To some extent,
lists are similar to arrays in C. One difference between them is that all the items
belonging to a list can be of different data type.
The values stored in a list can be accessed using the slice operator ([ ] and [:])
with indexes starting at 0 in the beginning of the list and working their way to end -1.
The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition
operator. For example

list = [ 'abcd', 786 , 2.23,'john', 70.2 ] print list[0]
o/p

a
b
c
d
9. What is tuple ? What is the difference between list and tuple?
 A tuple is another sequence data type that is similar to the list. A tuple
consists of a number of values separated by commas.
 The main differences between lists and tuples are: Lists are enclosed in
brackets ( [ ] ) and their elements and size can be changed, while tuples are
enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought
of as read-only lists. Eg:

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )

10. Give the features of python dictionaries


Python's dictionaries are kind of hash table type. They work like associative
arrays and consist of key-value pairs. A dictionary key can be almost any Python type,
but are usually numbers or strings. Values, on the other hand, can be any arbitrary
Python object.Dictionaries are enclosed by curly braces ({ }) and values can be assigned
and accessed using square braces ([]). For example − dict = {}

dict['one'] = "This is one"

11. What is a variable?


One of the most powerful features of a programming language is the ability to
manipulate variables. A variable is a name that refers to a value. The assignment
statement gives a value to a variable.
Eg:
>>> n = 17
>>> pi = 3.14159

12. What are the rules for naming a variable?


Variable names can be arbitrarily long. They can contain both letters and digits,
but they have to begin with a letter or an underscore. Although it is legal to use
uppercase letters, by convention we don‘t. If you do, remember that case matters.
Bruce and bruce are different variables.
The underscore character ( _) can appear in a name.
Eg:
my_name

13. What are keywords?


Keywords are the reserved words in Python. We cannot use a keyword as
variable name, function name or any other identifier. They are used to define the syntax
and structure of the Python language In Python, keywords are case sensitive. There are
33 keywords in Python.
Eg:
False, class, finally, return
14. What are the rules for writing an identifier?
 Identifiers can be a combination of letters in lowercase (a to z) or uppercase
(A to Z) or digits (0 to 9) or an underscore (_). Names like myClass, var_1
and print_this_to_screen, all are valid example.
 An identifier cannot start with a digit. 1variable is invalid, but variable1
is perfectly fine. Keywords cannot be used as identifiers.
 We cannot use special symbols like !, @, #, $, % etc. in our
 identifier. Identifier can be of any length.

15. whatare expressions?


An expression is a combination of values, variables, operators, and calls to
functions. If you type an expression at the Python prompt, the interpreter evaluates it
and displays the result:
>>> 1 + 1=2

16. What is a statement?


A statement is an instruction that the Python interpreter can execute. When you type a
statement on the command line, Python executes it. Statements don‘t produce any result.
For example, a = 1 is an assignment statement. if statement, for statement, while
statement etc. are other kinds of statements.

17. What is multiline statement?


In Python, end of a statement is marked by a newline character. But we can make
a statement extend over multiple lines with the line continuation character (\).
For example:
a=1+2+3+\
4+5+6+\
7+8+9

18. What is docstring?


Docstring is short for documentation string. It is a string that occurs as the first
statement in a module, function, class, or method definition. It is used to explain in brief,
what a function does.

19. What is a function? Mention the type of function and use.


A Function can be called as a section of a program that is written once and can
be executed whenever required in the program, thus making code reusability.
There are two types of Functions.
a) Built-in Functions: Functions that are predefined. We have
used many predefined functions in Python.
b) User- Defined: Functions that are created according to the requirements.

20. Mention the types of arguments in python


1. python default
arguments.
2. python keyword
argument
3. python arbitrary
argument

21. What is meant by module in python?


A module is a file consisting of Python code. A module can define functions,
classes and variables. A module can also include runnable code.
22. List some built in modules in python
There are many built in modules in Python. Some of them are as follows:math,
random , threading , collections , os , mailbox , string , time , tkinter etc..

23. What is the use of dir() function?


The dir() built-in function returns a sorted list of strings containing the names
defined by a module. The list contains the names of all the modules, variables and
functions that are defined in a module.

26. What operators does python support?

 Arithmetic Operators
 Comparison (Relational) Operators
 Assignment Operator
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operator

27. What is an Arithmetic operator?


Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication etc.
The operators are: +,-,/,%,*,**

28. What is the use of comparison operator?


Comparison operators are used to compare values. It either returns True or False
according to the condition.
>,<,>=,<=,==,!=
29. What are logical operators and Bitwise operators?
Logical operators are the and, or, not operators. Bitwise operators act on
operands as if they were string of binary digits. It operates bit by bit, hence the name.
The operators are:&,|,`^,>>,<<
30. What are assignment statements?
Assignment operators are used in Python to assign values to variables.a = 5 is a
simple assignment operator that assigns the value 5 on the right to the variable a on the
left.
31. Mention the features of identity operators?
is and is not are the identity operators in Python. They are used to check if two
values (or variables) are located on the same part of the memory. Two variables that
are equal does not imply that they are identical.
32. Give the characteristics of membership operator?
in and not in are the membership operators in Python. They are used to test
whether a value or variable is found in a sequence (string, list, tuple, set and
dictionary).In a dictionary we can only test for presence of key, not the value.

Operator Meaning Example


In True if value/variable is found in the sequence 5 in x
not in True if value/variable is not found in the sequence 5 not in x

PART B

1. Explain the data types in python


2. Ilustrate interpreter and interactive mode in
python with example. 3.Explain function and
module with suitable example
4. Write short notes on types of operators in python with appropriate example
5.Explain briefly constant, variables, expression, keywords and
statements available in python 6.Write the following python programs.
a. Exchange the value
of two variable
b.Circulate the value
of n variables
c. Test whether a given year is leap year or not
d. to find the sum of n natural numbers
e. To find whether a given number is Armstrong number or
not f. To print Fibonacci series
g. To find factorial of a given number
h. To convert Celsius to Fahrenheit

You might also like