Data, Expressions, Statements
Data, Expressions, Statements
1.
INTRODUCTION TO PYTHON:
• 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.
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++,JavaScript ,
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.
Applications:
❖Bit Torrent file sharing
❖Google search engine, YouTube
❖Intel, Cisco, HP,IBM
❖i–Robot
❖NASA
❖Face book, Drop box
31
Python interpreter:
Interpreter: To execute a program in a high-level language by translating it one line ata time. Compiler:
To translate a program written in a high-level language into a low-level language all at once, in preparation
for later execution.
Compiler Interpreter
Compiler Takes Entire program as input Interpreter Takes Single instruction as input
Program need not be compiled every time Every time higher level program is converted
into lower level program
Errors are displayed after entire program is checked Errors are displayed for every
instruction interpreted (if any)
32
This is an example of a print statement. It displays a result on the screen. In this case, the result is the words.
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.
A way of using the Python interpreter by A way of using the Python interpreter to read
typing commands and expressions at the prompt. and execute statements in a script.
Can’t save and edit the code Can save and edit the code
If we want to experiment with the code, If we are very clear about the code, we
we can use interactive mode. can use script mode.
we cannot save the statements for further use and we can save the statements for further use and we
we have to retype all the statements to re-run no need to retype all the statements to re-run
them. them.
We can see the results immediately. We can’t see the code immediately.
33
Auto completion with smart indentation.
Python shell to display output with syntax highlighting.
Value:
Value can be any letter, number or string.
Eg, Values are 2, 42.0, and 'Hello, World!'. (These values belong to different datatypes.)
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:
Numbers:
❖ Number data type stores Numerical Values.
❖ This data type is immutable [i.e. values/items cannot be changed].
❖ Python supports integers, floating point numbers and complex numbers. They are defined as,
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)
datatypes.
34
❖ There are three types of sequence data type available in Python, they are
1. Strings
2. Lists
3. Tuples
Strings:
A String in Python consists of a series or sequence of characters - letters, numbers, and special
characters.
Strings are marked by quotes:
• Single quotes(' ') E.g., 'This a string in single quotes'
• double quotes(" ") E.g., "'This a string in double quotes'"
• triple quotes(""" """)E.g., """This is a paragraph. It is made up of multiple lines and
sentences."""
Individual character in a string is accessed using a subscript(index).
Characters can be accessed using indexing and slicing operations .Strings are
Immutable i.e the contents of the string cannot be changed after it is created.
Indexing:
35
Slice operator is >>>print(s[:4])
- Displaying items from 1stposition till
used to extract part Good
of a data rd
3 .
type
Operations on list:
Indexing
Slicing
Concatenation
Repetitions
Updation, Insertion, Deletion
Creating a list >>>list1=["python", 7.79, 101, Creating the list with elements
"hello”] of different data
>>>list2=["god",6.78,9] types.
36
6.78, 9]
Updating the list >>>list1[2]=45 Updating the list using index value
>>>print( list1)
[‘python’, 7.79, 45, ‘hello’]
Tuple:
❖ A tuple is same as list, except that the set of elements is enclosed in parentheses
instead of square brackets.
❖ A tuple is an immutable list.i.e. once a tuple has been created, you can't add elements to a tuple or
remove elements from the tuple.
❖ Benefit of Tuple:
❖ Tuples are faster than lists.
❖ If the user wants to protect the data from accidental changes, tuple can be used.
❖ Tuples can be used as keys in dictionaries, while lists can't.
Basic Operations:
Creating a tuple >>>t=("python", 7.79, 101, Creating the tuple with
"hello”) elements of different data
types.
Altering the tuple data type leads to error. Following error occurs when user tries to do.
37
>>>t[0]="a"
Trace back (most recent call last):
File "<stdin>", line 1, in <module>
Type Error: 'tuple' object does not support item assignment
Mapping
-This data type is unordered and mutable.
-Dictionaries fall under Mappings.
Dictionaries:
❖ Lists are ordered sets of objects, whereas dictionaries are unorderedsets.
❖ Dictionary is created by using curly brackets. i,e.{}
❖ Dictionaries are accessed via keys and not via their position.
❖ A dictionary is an associative array (also known as hashes). Any key of the dictionary is associated
(or mapped) to a value.
❖ The values of a dictionary can be any Python data type. So dictionaries are unordered key-value
pairs(The association of a key and a value is called a key- value pair)
Dictionaries don't support the sequence operation of the sequence data types like strings, tuples and lists.
Creating a >>> food = {"ham":"yes", Creating
dictionary "egg" : "yes", "rate":450 } the
>>>print(food) dictionary
{'rate': 450, 'egg': 'yes', 'ham': 'yes'} with
of
different
elements
data
types.
If you try to access a key which doesn't exist, you will get an error message:
>>>words = {"house" : "Haus", "cat":"Katze"}
>>>words["car"]
Traceback (most recent call last): File
"<stdin>", line 1, in <module>KeyError: 'car'
Data type Compile time Run time
38
❖ 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.
>>>a,b,c=2,4,"ram"
KEYWORDS:
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 (_).
39
❖ 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.
Example:
Names like myClass, var_1, and this_is_a_long_variable
Valid declarations Invalid declarations
Num Number 1
Num num1
Num1 addition of program
_NUM 1Num
NUM_temp2 Num.no
IF if
Else else
Statements:
-Instructions that a Python interpreter can executes are called statements.
-A statement is a unit of code like creating a variable or displaying avalue.
>>> 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.
Expressions:
-An expression is a combination of values, variables, and operators.
- A value all by itself is considered an expression, and also a variable.
- So the following are all legal expressions:
>>> 42
42
>>> a=2
>>>a+3+2 7
>>> z=("hi"+"friend")
>>>print(z) hifriend
INPUT: Input is data entered by user (end user) in the program. In python, input
() function is available for input.
Syntax for input() is:
variable = input (“data”)
40
Example:
>>> x=input("enter the name:")
enter the name: george
>>>y=int(input("enter the number"))
enter the number 3
#python accepts string as default data type. Conversion is required for type.
Most of the programming languages like C, C++, Java use braces { } to define a block of code. But,
python uses indentation.
Blocks of code are denoted by line indentation.
It is a space given to the block of codes for class and function definitions or flow control.
41
Example:
a=3
b=1
if a>b:
print("a is greater")
else:
print("b is greater")
QUOTATION INPYTHON:
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals. Anything that is
represented using quotations are considered as string.
Example:
-It is useful to swap the values of two variables. With conventional assignment statements, we have to use a
temporary variable. For example, to swap a and b:
Swap two numbers Output:
a=2;b=3 (2, 3)
print(a,b) (3, 2)
temp = a >>>
a=b
b = temp
print(a,b)
42
-Tuple assignment solves this problem neatly:
(a, b) = (b, a)
-In tuple unpacking, the values in a tuple on the right are ‘unpacked ‘into the variables/names on the
right:
>>>b = ("George", 25, "20000") # tuple
packing>>>(name, age, salary)=b #
tupleunpacking >>>name
'George'
>>>age
25
>>>salary
'20000'
-The right side can be any kind of sequence (string, list,tuple)
Example:
-To split an email address in to user name and a domain
>>>mailid='[email protected]'
>>>name,domain=mailid.split('@')
>>>print name god
>>> print (domain) abc.org
4.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 operator
Types of Operators:
-Python language supports the following types of operators
• Arithmetic Operators
• Comparison (Relational)Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
43
Arithmetic operators:
They are used to perform mathematical operations like addition, subtraction, multiplication etc.
Assume, a=10 and b=5
Operator Description Example
% Modulus Divides left hand operand by right hand operand and b%a=0
returns remainder
** Exponent Performs a**b =10 to the
exponential (power) calculation on power 20
operators
Examples (Relational)Operators:
a=10 Output:
b=5 a+b=15
print("a+b=",a+b) a-b= 5
print("a-b=",a-b) a*b= 50
print("a*b=",a*b)
a/b= 2.0
print("a/b=",a/b)
print("a%b=",a%b) a%b=0
print("a//b=",a//b) a//b=2
print("a**b=",a**b) a**b= 100000
Comparison
44
becomes true. not true.
!= If values of two operands are not equal, then condition becomes true. (a!=b) is
true
> If the value of left operand is greater than the value of right operand, (a > b) is
then condition becomes true. not true.
< If the value of left operand is less than the value of right operand, (a < b) is
then condition becomes true. true.
>= If the value of left operand is greater than or equal to the value of (a >= b) is
right operand, then condition becomes true. not true.
<= If the value of left operand is less than or equal to the value of (a <= b) is
right operand, then condition becomes true. true.
Example print("a>=b=>",a>=b)
a=10
b=5 Assignment Operators:
print("a>b=>",a>b)
print("a>b=>",a<b) Output: a>b=> True a>b=>
print("a==b=>",a==b) False a==b=> False a!=b=> True
print("a!=b=>",a!=b) a>=b=> False a>=b=> True
print("a>=b=>",a<=b)
= Assigns values from right side operands to left side operand c=a+b
assigns value
of a + b into c
+= Add AND It adds right operand to the left operand and assign the result c += a is
to leftoperand equivalent
to c = c + a
-= Subtract It subtracts right operand from the left operand and assign the c -= a is
AND result to left operand equivalent
to c = c -a
45
*= It multiplies right operand with the left operand and assign c *= a is
Multiply the result to left operand equivalent
AND to c = c *a
/= It divides left operand with the right operand and assign the c /= a is
Divide result to left operand equivalent
AND to c = c /ac
/= a is
equivalent
to c = c /a
//= Floor It performs floor division on operators and assign value to the c //= a is
Division left operand equivalent
to c = c // a
46
Logical Operators:
-Logical operators are the and, or, not operators.
Example
a = True
Bitwise Operators:
b = False
Output
print('a and b is', a and b)
x and y is False x or y is True not
print('a or b is' ,a or b)
x is False
print('not a is', not a)
• A bitwise operation operates on one or more bit patterns at the level of individual bits
Example: Let x = 10 (0000 1010 in binary)and
y = 4 (0000 0100 in binary)
Example Output
Line 1 - Value of c is 12
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101 # 12 = Line 2 - Value of c is 61
c=0 Line 3 - Value of c is 49
0000 1100 Line 4 - Value of c is-61
c = a & b;
print "Line 1 - Value of c is ", c c = 3 - Value of c is ", c c =~a; # -61 =
a|b; # 61 = 00111101 print "Line 2 - 11000011
Value of c is ", c Line 5 - Value of c is 240 Line 6 -
c = a^b; # 49 = 00110001 print "Line Value of c is 15
47
print "Line 4 - Value of c is ", c
c = a<<2; # 240 = 11110000
print "Line 5 - Value of c is ", c
c = a>>2; # 15 = 00001111
print "Line 6 - Value of c is ", c
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 areused.
Example:
x=[5,3,6,4,1]
>>>5 in x
True
>>>5 not in x
False
Identity Operators:
• They are used to check if two values (or variables) are located on the same partof the
memory.
Example print(x1 is not y1) print(x2
x =5 is y2)
y =5 Output False
x2 = 'Hello'
True
y2= 'Hello'
48
5.OPERATOR PRECEDENCE:
When an expression contains more than one operator, the order of evaluation
depends on the order of operations.
Operator Description
49
Examples:
a=9-12/3+3*2-1 A=2*3+4%5-3/2+6 find m=?
a=? A=6+4%5-3/2+6 m=-43||8&&0||-2 m=-
a=9-4+3*2-1 A=6+4-3/2+6 A=6+4- 43||0||-2 m=1||-2
a=9-4+6-1 1+6 m=1
a=5+6-1 a=11- A=10-1+6
1 a=10 A=9+6 A=15
6.Functions, Function Definition And Use, Function call, Flow Of Execution, Function Prototypes,
Parameters And Arguments, Return statement, Arguments types, Modules
FUNCTIONS:
Function is a sub program which consists of set of instructions used to perform a specific task. A
large program is divided into basic building blocks called function.
Types of function:
Functions can be classified into two categories:
i) user defined function
ii) Built in function
i) Built in functions
• Built in functions are the functions that are already created and stored inpython.
• These built in functions are always available for usage and accessed by a programmer. It cannot be
modified.
50
51
Syntax:
Example:
def my_add(a,b):
c=a+b
return c
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.
Note: When you read a program, don’t read from top to bottom. Instead, follow the flow of execution. This
means that you will read the def statements as you are scanning from top to bottom, but you should skip the
statements of the function definition until you reach a point where that function is called.
Function Prototypes:
52
i) Function without arguments and without return type
o In this type no argument is passed through the function call and no output is return to main
function
o The sub function will read the input values perform the operation and print the result in the
same block
ii) Function with arguments and without return type
o Arguments are passed through the function call but output is not return to the main function
iii) Function without arguments and with return type
o In this type no argument is passed through the function call but output is return to the main
function.
iv)Function with arguments and with return type
o In this type arguments are passed through the function call and output is return to the main
function
Without Return Type
OUTPUT: OUTPUT:
enter a5 enter a5
enter b 10 enter b 10
15 15
OUTPUT: OUTPUT:
enter a5 enter a5
enter b 10 enter b 10
15 15
53
Parameters And Arguments:
Parameters:
• Parameters are the value(s) provided in the parenthesis when we write function header. •
These are the values required by function to work.
• If there is more than one value required, all of them will be listed in parameter list separated by
comma.
• Example: defmy_add(a,b):
Arguments :
• Arguments are the value(s) provided in function call/invoke statement.
• List of arguments should be supplied in same way as parameters are listed.
• Bounding of parameters to arguments is done 1:1, and so there should be same number and type of
arguments as mentioned in parameter list.
• Example:my_add(x,y)
RETURN STATEMENT:
• The return statement is used to exit a function and go back to the place from where it was called. •
If the return statement has no arguments, then it will not return any values. But exits from function.
Syntax:
return[expression]
Example:
def my_add(a,b):
c=a+b
return c
x=5
y=4
print(my_add(x,y))
Output:
9
ARGUMENT TYPES:
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.
defmy_details( name, age ):
print("Name: ", name)
print("Age ", age)
return
my_details("george",56)
54
Output:
Name:
georgeAge56
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.
DefaultArguments:
Assumes a default value if a value is not provided in the function call for that argument.
defmy_details( name, age=40 ):
print("Name: ", name)
print("Age ", age) return
my_details(name="george")
Output:
Name:
georgeAge40
Variable lengthArguments
If we want to specify more arguments than specified while defining the function, variable length
arguments are used. It is denoted by * symbol before parameter.
def my_details(*name ):
print(*name)
my_details("rajan","rahul","micheal", ärjun")
Output:
rajanrahulmichealärjun
7.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.
55
Once we import a module, we can reference or use to any of its functions or variables in our code.
Once we import a module, we can reference or use to any of its functions or variables in our code.
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.
• There is large number of standard modules also available in python.
• 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 •
Standard modules can be imported the same way as we import our user- defined
• Standard modules can be imported the same way as we import our user- defined
modules.
modules.
modules.
• Every module contains many functions.
• Every module contains many functions.
• Every module contains many functions.
• To access one of the function , you have to specify the name of the module and the name •
To access one of the function , you have to specify the name of the module and the name
• To access one of the function , you have to specify the name of the module and the name of
the function separated by dot .This format is called dot notation.
of the function separated by dot .This format is called dot notation.
of the function separated by dot .This format is called dot notation.
Syntax:
Syntax:
Syntax:
import
import
import
module_namemodule_name.function_name(variable)
module_namemodule_name.function_name(variable)
module_namemodule_name.function_name(variable)
Importing Builtin Module: Importing Importing User Defined Module:
Builtin Module: Importing Builtin Importing User Defined Module:
Module: Importing User Defined Module:
56
56
56
than or equal to x
than or equal to x
than or equal to x
math. floor(x) - Return the floor of x, the largest integer less than or equal to x.
math. floor(x) - Return the floor of x, the largest integer less 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. factorial(x)-Return x factorial.
math. factorial(x)-Return x factorial.
math.gcd(x,y)-Return the greatest common divisor of the integers a and b
math.gcd(x,y)-Return the greatest common divisor of the integers a and b
math.gcd(x,y)-Return the greatest common divisor of the integers a and b
math.sqrt(x)- Return the square root of x
math.sqrt(x)- Return the square root of x
math.sqrt(x)- Return the square root of x
math.pi - The mathematical constant π = 3.141592
math.pi - The mathematical constant π = 3.141592
math.pi - The mathematical constant π = 3.141592
math.e – returns The mathematical constant e = 2.718281
math.e – returns The mathematical constant e = 2.718281
math.e – returns The mathematical constant e = 2.718281
2 .random-Generate pseudo-random
numbers 2 .random-Generate
pseudo-random numbers
2 .random-Generate pseudo-random numbers
random.randrange(stop) random.randrange(start, stop[,
random.randrange(stop) random.randrange(start, stop[,
random.randrange(stop) random.randrange(start, stop[,
step]) random.uniform(a, b)
step]) random.uniform(a, b)
step]) random.uniform(a, b)
-Return a random floating point number
-Return a random floating point number
floating point number
-Return a random
8.ILLUSTRATIVE PROGRAMS
8.ILLUSTRATIVE PROGRAMS
8.ILLUSTRATIVE PROGRAMS
Program for SWAPPING(Exchanging Output
Output
)of Program for Output
SWAPPING(Exchanging )of
Program for SWAPPING(Exchanging
)of values
values
values
a = int(input("Enter a value ")) Enter a value 5
a = int(input("Enter a value ")) Enter a value 5
a = int(input("Enter a value ")) Enter a value 5
b = int(input("Enter b value")) Enter b value 8
b = int(input("Enter b value")) Enter b value 8
b = int(input("Enter b value")) Enter b value 8
c=a a=8
c=a a=8
c=a a=8
a=b b=5
a=b b=5
a=b b=5
b =c
b =c
b =c
print("a=",a,"b=",b,)
print("a=",a,"b=",b,)
print("a=",a,"b=",b,)
y1)**2) distance
=math.sqrt((x2-x1)**2)+((y2- y1)**2)
distance =math.sqrt((x2-x1)**2)+((y2-
y1)**2) print(distance)
print(distance)
print(distance)
57
57
57
2marks:
1. What is Python?
Python is a general-purpose interpreted, interactive, object-oriented, and high
level programming language.
3. What is IDLE?
Integrated Development Learning Environment (IDLE) is a graphical user interface which is
completely written in Python. It is bundled with the default implementation of the python language and
also comes with optional part of the Python packaging.
4. Differentiate between interactive and script mode.
Interactive mode Script mode
A way of using the Python interpreter A way of using the Python interpreter to read
by typing commands and expressions and execute statements in a script.
at the prompt.
Cant save and edit the code Can save and edit the code
we cannot save the statements for we can save the statements for further use and
further use and we have to retype we no need to retype
all the statements to re-run them. all the statements to re-run them.
We can see the results immediately. We cant see the code immediately.
58
6. What is a tuple?
❖ A tuple is same as list, except that the set of elements is enclosed in parentheses
instead of square brackets.
❖ A tuple is an immutable list.i.e. once a tuple has been created, you can't add elements to a tuple or
remove elements from the tuple.
7. Outline the logic to swap the contents of two identifiers without using third variable.
Swap two numbers Output:
a=2;b=3 (2, 3)
print(a,b) (3, 2)
a = a+b >>>
b= a-b
a= a-b
print(a,b)
59
10. What is return statement?
The return statement is used to exit a function and go back to the place from
where it was called. If the return statement has no arguments, then it will not return any
values. But exits from function.
Syntax:
return[expression
]
• Required Arguments
• Keyword Arguments
• Default Arguments
• Variable length Arguments
60
61