Unit Ii Data, Expressions, Statements
Unit Ii Data, Expressions, Statements
1. Introduction to python:
Python is a general-purpose interpreted, interactive, object-oriented, and high-level
programming language. It was created by Guido van Rossum during 1985- 1990.
Python got its name from “Monty Python’s flying circus”. Python was released in the
year 2000.
Python is interpreted: Python is processed at runtime by the interpreter. You do
not need to compile your program before executing it.
Python is Interactive: You can actually sit at a Python prompt and interact with
the interpreter directly to write your programs.
Python is Object-Oriented: Python supports Object-Oriented style or technique of
programming that encapsulates code within objects.
Python is a Beginner's Language: Python is a great language for the beginner-
level programmers and supports the development of a wide range of
applications.
1.1. Python Features:
Easy-to-learn: Python is clearly defined and easily readable. The structure
of the program is very simple. It uses few keywords.
Easy-to-maintain: Python's source code is fairly easy-to-maintain.
Portable: Python can run on a wide variety of hardware platforms and has the
same interface on all platforms.
Interpreted: Python is processed at runtime by the interpreter. So, there is no
need to compile a program before executing it. You can simply run the program.
Extensible: Programmers can embed python within their C,C++,Java script
,ActiveX, etc.
Free and Open Source: Anyone can freely distribute it, read the source code, and
edit it.
High Level Language: When writing programs, programmers concentrate on
solutions of the current problem, no need to worry about the low level details.
Scalable: Python provides a better structure and support for large programs
than shell scripting.
1.2. Applications:
Bit Torrent file sharing
Google search engine, youtube
Intel, Cisco, HP, IBM
i–Robot
NASA
Facebook, Drop box
Compiler Interpreter
Interpreter Takes Single instruction as
Compiler Takes Entire program as input
input
No Intermediate Object Code
Intermediate Object Code is Generated
is Generated
Conditional Control Statements are Conditional Control Statements are
Executes faster Executes slower
Memory Requirement is More(Since Object
Memory Requirement is Less
Code is Generated)
Every time higher level program is
Program need not be compiled every time
converted into lower level program
Errors are displayed after entire Errors are displayed for every
program is checked instruction interpreted (if any)
Example : C Compiler Example : PYTHON
Advantages:
Python, in interactive mode, is good enough to learn, experiment or explore.
Working in interactive mode is convenient for beginners and for testing small
pieces of code
Drawback:
We cannot save the statements and have to retype all the statements once again to
re-run them.
In interactive mode, you type Python programs and the interpreter displays the
result:
Script mode:
In script mode, we type python program in a file and then use interpreter to
execute the content of the file.
Scripts can be saved to disk for future use. Python scripts have the extension .py,
meaning that the filename ends with .py
Save the code with filename.py and run the interpreter in script mode to execute
the script.
Features of IDLE:
Multi-window text editor with syntax highlighting.
Auto completion with smart indentation.
Python shell to display output with syntax highlighting.
Values:
Value can be any letter, number or string.
Eg, Values are 2, 42.0, and 'Hello, World!'. (These values belong to different data types.)
Data type:
Every value in Python has a data type.
It is a set of values, and the allowable operations on those values.
Python has four standard data types:
Example:
a=10
a=eval(input(“enter a value”))
a=int(input(“enter a value”))
2.2 Float:
it has decimal part and fractional part.
Example:
a=3.15
a=eval(input(“enter a value”))
a=float(input(“enter a value”))
2.3.Complex:
It is a combination of real and imaginary part.
Example:
2+5j
a+bi
Sequence:
A sequence is an ordered collection of items, indexed by positive integers.
It is a combination of mutable (value can be changed) and immutable (values
cannot be changed) data types.
There are three types of sequence data type available in Python, they are
1. Strings
2. Lists
3. Tuples
2.4.Strings:
String is defined as a continues set of characters represented in quotation marks
(either single quotes ( ‘ ) or double quotes ( “ ).
An individual character in a string is accessed using a subscript (index).
The subscript should always be an integer (positive or negative).
A subscript starts from 0 to n-1.
Strings are immutable i.e. the contents of the string cannot be changed after it is
created.
Python will get the input at run time by default as a string.
Operations on string:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Member ship
Operations on list:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
create a list >>> a=[2,3,4,5,6,7,8,9,10] in this way we can create a
>>> print(a) list at compile time
[2, 3, 4, 5, 6, 7, 8, 9, 10]
Indexing >>> print(a[0]) Accessing the item in the
2 position 0
>>> print(a[8]) Accessing the item in the
10 position 8
>>> print(a[-1]) Accessing a last element
10 using negative indexing.
Slicing >>> print(a[0:3])
[2, 3, 4]
>>> print(a[0:]) printing a part of the string.
[2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> print(a[:8])
[2, 3, 4, 5, 6, 7, 8, 9]
>>>b=[20,30] Adding and printing the
Concatenation >>> print(a+b) items of two lists.
[2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30]
>>> print(b*3) Create a multiple copies of
Repetition [20, 30, 20, 30, 20, 30] the same string
>>> print(a[2])
4 Updating the list using
Updating the list >>> a[2]=100 index value
>>> print(a)
[2, 3, 100, 5, 6, 7, 8, 9, 10]
Inserting an >>> a. insert(0,"apple") Inserting an element in 0th
element >>> print(a) position
a=[“apple”,2,3,4,5,6,7,8,9,10]
Removing an >>> a. remove(“apple”) Removing an element by
element >>> print(a) giving the element directly
a=[2,3,4,5,6,7,8,9,10]
Example:
>>> 3==5
False
>>> True+True
2
>>> False+True
1
>>> False*True
0
2.9.Sets:
Set is an unordered collection of values of any data type with no duplicate entry.
In set every element is unique.
Elements are separated by”,” enclosed with { }
Example:
a={1,2,3,4,5,6,7,6,7}
print(a)
a={1,2,3,4,5,6,7}
3.VARIABLES:
A variable allows us to store a value by assigning it to a name, which can be used
later.
Named memory locations to store values.
Programmers generally choose names for their variables that are meaningful.
It can be of any length. No space is allowed.
We don't need to declare a variable before using it. In Python, we simply assign a
value to a variable and it will exist.
Example:
a=5 // single assignment
a,b,c=2,3,4 // multiple assignment
a=b=c=2 //assigning one value to multiple variables
5.IDENTIFIERS:
Identifier is the name given to entities like class, functions, variables etc. in
Python.
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 (_).
all are valid example.
An identifier cannot start with a digit.
Keywords cannot be used as identifiers.
Cannot use special symbols like !, @, #, $, % etc. in our identifier.
Identifier can be of any length.
6. STATEMENTS
Instructions that a Python interpreter can executes are called statements.
A statement is a unit of code like creating a variable or displaying a value.
>>> n = 17
>>> print(n)
Here, The first line is an assignment statement that gives a value to n.
The second line is a print statement that displays the value of n.
There are two types of statements available
1. single line statements
2. multi line statements
Multiline statements:
python allows the user to write multi line statement using line continuation character
(\) to denote that the line should continue.
Example:
total=mark1+\
mark2+\
mark3
7.INPUT AND OUTPUT
INPUT:
Input is a data entered by user in the program.
In python, input () function is available for input.
Syntax:
variable = input (“data”)
Example:
a=input("enter the name:")
OUTPUT:
Output can be displayed to the user using Print statement.
Syntax:
print (expression/constant/variable)
Example:
print ("Hello") // Hello
print(5) //5
print(3+5) //8
Print(c)
Example:
“”” This program is created by Robert
in Dell lab on 12/12/12
based on newtons method”””
Example:
a=3
b=1
if a>b:
print("a is greater")
else:
print("b is greater")
10.TUPLE ASSIGNMENT
An assignment to all of the elements in a tuple using a single assignment
statement.
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
The left side is a tuple of variables; the right side is a tuple of values. Each value is
assigned to its respective variable. All the expressions on the right side are
evaluated before any of the assignments.
11.OPERATORS:
Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is
called
Types of Operators:
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators
Arithmetic operators:
They are used to perform mathematical operations like addition, subtraction,
multiplication etc.
Operator Description Example
a=10,b=20
> If the value of left operand is greater than the value of right (a > b) is
operand, then condition becomes true. not true.
< If the value of left operand is less than the value of right (a < b) is
operand, then condition becomes true. true.
>= If the value of left operand is greater than or equal to the (a >= b) is
value of right operand, then condition becomes true. not true.
<= If the value of left operand is less than or equal to the value (a <= b) is
of right operand, then condition becomes true. true.
Assignment Operators:
Assignment operators are used in Python to assign values to variables.
Operator Description Example
Logical Operators:
Logical operators are and, or, not operators.
Bitwise Operators:
Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
Membership Operators:
Evaluates to find a value or a variable is in the specified sequence of string, list, tuple,
dictionary or not.
Let, x=[5,3,6,4,1]. To check particular item in list or not, in and not in operators are
used.
Identity Operators:
They are used to check if two values (or variables) are located on the same part of the
memory.
Example
x=5
y=5
a = 'Hello'
b = 'Hello'
print(x is not y) // False
print(a is b)//True
Operator Precedence:
When an expression contains more than one operator, the order of evaluation
depends on the order of operations.
Operator Description
12.Expressions:
>>> 42
42
>>> a=2
>>> a+3+2
7
>>> z=("hi"+"friend")
>>> print(z)
hifriend
a=9-12/3+3*2-1 A=2*3+4%5-3/2+6
a=? A=6+4%5-3/2+6 find m=?
a=9-4+3*2-1 A=6+4-3/2+6 m=-43||8&&0||-2
a=9-4+6-1 A=6+4-1+6 m=-43||0||-2
a=5+6-1 A=10-1+6 m=1||-2
a=11-1 A=9+6 m=1
a=10 A=15
a=2,b=12,c=1 a=2*3+4%5-3//2+6
d=a<b>c a=2,b=12,c=1 a=6+4-1+6
d=2<12>1 d=a<b>c-1 a=10-1+6
d=1>1 d=2<12>1-1 a=15
d=0 d=2<12>0
d=1>0
d=1
example:
def add():
a=eval(input(“enter a value”))
b=eval(input(“enter a value”))
c=a+b
print(c)
Syntax:
Function name(argument list)
Example:
add()
13.4.FLOW OF EXECUTION:
The order in which statements are executed is called the flow of execution
Execution always begins at the first statement of the program.
Statements are executed one at a time, in order, from top to bottom.
Function definitions do not alter the flow of execution of the program, but
remember that statements inside the function are not executed until the function
is called.
Function calls are like a bypass in the flow of execution. Instead of going to the
next statement, the flow jumps to the first line of the called function, executes all
the statements there, and then comes back to pick up where it left off.
14.FUNCTION PROTOTYPES:
Based on arguments and return type functions are classified into 4 types.
1. Function without arguments and without return type
2. Function with arguments and without return type
3. Function without arguments and with return type
4. Function with arguments and with return type
OUTPUT: OUTPUT:
enter a 5 enter a 5
enter b 10 enter b 10
15 15
def add(a,b):
c=a+b
return variable return c
x=5
y=4
c=add(a,b)
print(c)
16.ARGUMENTS TYPES:
You can call a function by using the following types of formal arguments:
1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments
Required Arguments:
The number of arguments in the function call should match exactly with the function
definition.
Example Output:
def student( name, roll ): George
print(name,roll) 98
student("george",98)
def student( name, roll ): 101
print(name,roll) rithika
student(101,”rithika”)
def student( name, roll ): student() missing 1 required positional
print(name,roll) argument: 'name'
student(101)
def student( name, roll ): student() missing 2 required positional
print(name,roll) arguments: 'roll' and 'name'
student()
Keyword Arguments:
Python interpreter is able to use the keywords provided to match the values with
parameters even though if they are arranged in out of order.
Example Output:
def student( name, roll,mark): bala
print(name,roll,mark) 102
student (mark=90,roll=102,name="bala") 90
Default Arguments:
Assumes a default value if a value is not provided in the function call for that argument.
It allows us to miss one or more arguments or place out of order in function call.
Example Output:
def student( name="raja", roll=101,mark=50): bala 102 90
print(name,roll,mark)
student (mark=90,roll=102,name="bala")
def student( name="raja", roll=101,mark=50): bala 102 50
print(name,roll,mark)
student (name="bala", roll=102)
def student( name="raja", roll=101,mark=50): raja 101 50
print(name,roll,mark)
student ()
Example Output:
def student( name,*mark): bala (90,)
print(name,mark)
student (“bala”,90)
17.MODULES:
A module is a file containing Python definitions, functions, statements and
instructions.
Standard library of Python is extended as modules.
To use these modules in a program, programmer needs to import the module.
Once we import a module, we can reference or use to any of its functions or
variables in our code.
There is large number of standard modules also available in python.
Standard modules can be imported the same way as we import our user-defined
modules.
Two ways to import your module:
1. import keyword
2. form keyword
from keyword:
from keyword is used to get only particular function from the module.
Syntax:
from module_name import function_name
1.math-mathematical module
math functions description
math.ceil(x) Return the ceiling of x, the smallest integer greater than or equal
to x
math.floor(x) Return the floor of x, the largest integer less than or equal to x.
math.factorial(x) Return x factorial
math.sqrt(x) Return the square root of x
ILLUSTRATIVE PROGRAMS
SWAPPING Output
a = int(input("Enter a value ")) Enter a value 5
b = int(input("Enter b value ")) Enter b value 8
c=a a=8
a=b b=5
b=c
print("a=",a,"b=",b,)