Unit Ii
Unit Ii
Python interpreter and interactive mode, debugging; values and types: int, float, boolean, string, and list;
variables, expressions, statements, tuple assignment, precedence of operators, comments; Illustrative
programs: exchange the values of two variables, circulate the values of n variables, distance between two
points.
Python:
1. Python is free & open source programming language. Software can be downloaded & used freely.
2. It high level programming language.
3. It is simple and easy to learn.
4. It is portable i.e. programs can be executed on various platforms without altering them.
5. Do not require compilation, rather they are interpreted
6. It is an object oriented programming language.
7. It can be embedded within your C or C++ programs.
Applications:
Bit Torrent file sharing
Google search engine,
Youtube
HP, IBM
Robotics, NASA
Facebook and Drop box
Python Interpreter
Python interpreter is a program that reads and executes Python code.
Python programs do not require compilation, rather they are interpreted.
Python converts the source code into an intermediate form called byte codes and then translates
this into the native language of your computer and then runs it.
Interpreter
Interpreter translates high level language program in a source program to a machine code and
executes it immediately in line by line manner before translating the next statement. When an error
is found the execution of the program is halted and error message is displayed on the screen.
Interactive Modes
Python has two basic modes:
Normal or Script and
Interactive Mode.
Normal mode: This mode is also called as Script mode, in which python commands are stored in a file
and file is saved using extension .py. Scripted .py files are run in Python interpreter.
Interactive mode: It is a command line shell which gives immediate result for each statement, while
running previously statements in active memory. The >>> is Python's interactive mode.
For example - If type 1+1 on interpreter immediate result i.e. 2 will be displayed by interpreter.
Proper indentation is required while writing code on interpreter shell. For example
Values and Types
Value is stored in a variable and it is a basic thing in Python. Based on data type, different values can be
stored in a variable.
Data Types: It is Type of Data stored in a Variable. There are five data types in Python
2. Boolean
3. Strings
4. List
5. Tuple
6. Dictionary
7. Sets
i) int : It represents the signed integer value. For example 100,-365, oX220
ii) float: This data type is for representing the floating point real numbers.
iii) long : It represents the long integers. These can be represented in octal and hexadecimal.
A Boolean variable can take only two values, True or False. It is used in logical expressions.
Example
a = True
b = 30 > 45 # b gets the value False
1. Strings
2. Lists
3. Tuples
2. 1. String : The string is a collection of characters. It is presented within a quote. For example –
>>> mystr="India"
>>> print(mystr[0])
I
>>> print(mystr[1:3])
Nd
String Operations:
>>> msg1=”Hello”
>>> msg2=”World”
>>> msg1+msg2
„HelloWorld‟
>>> „India‟*3
„IndiaIndiaIndia‟
2.2. List : The list is a compound data type which contains list of elements separated by comma and
enclosed within the square brackets [ ]. To some extend it is similar to array in C. For example
>>> myList=[10,20,30]
>>> print(myList[0])
10
>>> print(myList[1:2])
[20]
>>> print(myList[0:2])
[10, 20]
2.3.Tuple : Tuple is also a compound data type which contains the list of elements separated by
comma but enclosed within the circular ( … ) bracket. For example
For example –
>>> mydict={'name':'AAA','roll':10,'marks':94}
>>> print(mydict.keys())
>>> print(mydict.values())
>>>
Type Command in Python
Data type of different values can be obtained using type command. This function returns the data type of
that particular element.
>>> type(10)
<class „int‟>
>>> type(11.11)
<class „float‟>
>>> type(“Hello”)
<class „str‟>
>>>
Variables: A variable is a reserved memory location to store values. Variable is an entity to which
programmer can assign some values. For example: Declare variable count & assign value 10.
Assignment Statements
It creates new variables and then corresponding value can be assigned to it. Assignment operator
= is used to assign values to variables. Any type of value can be assigned to valid variable.
For example:
>>> a,b,c=100, 11.11, "Energy"
>>> print(a)
100
>>> print(b)
11.11
>>> print(c)
Energy
Keywords
Keywords are special words reserved for some purpose. Python3 has list of keywords
>>> a=10
>>> a+20
30
>>> 2+3*4
14
The first statement in above code is assignment statement. The second statement is an expression.
The interpreter evaluates the expression and displays the result.
Precedence of Operators
Operators are special symbols that represent computations like addition and multiplication. The values
the operator uses are called operands.
When more than one operator appears in an expression, Order depends on rules of precedence.
3. MDAS : Mul and Div have same precedence, which is higher than Add and Sub
4. Operators with the same precedence are evaluated from left to right
Example:
1. 1 * (10-5) = 5
2. 2**3 = 8.
3. 2+3*4 yields 14 rather than 20.
4. 3-2+1will result 2.
Types of Operators:
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Arithmetic operators: Used to perform mathematical operations like addition, subtraction,
multiplication etc. Assume, a=10 and b=20
Operator Example
= c=a+b
+= c += a equivalent to c = c + a
-= c -= a equivalent to c = c - a
*= c *= a equivalent to c = c * a
/= c /= a equivalent to c = c / a
**= c += a equivalent to c = c ** a
Comparison (Relational) Operators:
Operator Example
Membership Operators:
Evaluates to find a value or a variable is in 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.
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 part of the memory
Example x=5 Output
y=5 False
x2 = 'Hello' True
y2 = 'Hello'
print(x1 is not y1)
print(x2 is y2)
Bitwise Operators It operates on one or more bit patterns at level of individual bits
Tuple Assignment
Tuple is a sequence of items of any type.
Tuple is a comma separated list of values, enclosed within the parenthesis.
Tuples can be thought of as read-only lists.
Differences between lists & tuples: Lists are enclosed in brackets ( [ ] ) & their elements, size can be
changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated.
(a, b) = (b, a)
The left side is a tuple of variables; the right side is a tuple of values. Each value is assigned to its
respective variable
Comments
Comments are kind of statements that are written in program for program understanding purpose.
By the comment statements it is possible to understand what exactly the program is doing.
In Python, we use the hash (#) symbol to start writing a comment.
It extends up to the newline character. Python Interpreter ignores comment.
Single line comment: A single line comment starts with the number sign (#) character:
Multiline comment: Multiple lines can be created by repeating the number sign several times:
# This is a comment
# Second line
x=4
A common way to use comments for multiple lines is to use the (”‟) symbol:
” ” ” This is a multiline
Python comment example.” ” ”
x=5
Illustrative Programs
1. Swapping - Exchange the Values of Two Variables without using function
Step 1 : Write the program in script mode. The name of the following file is swap.py
a=10
b=20
print("Before Swapping the values are")
print(“Value of a”,a)
print(“Value of b”,b)
temp=a
a=b
b=temp
print("After Swapping the values are ")
print(“Value of a”,a)
print(“Value of b”,b)
Step 2 : Output
Step 1: Write the program in script mode. The name of the following file is swap.py
Function Definition:
def swap(a,b):
temp=a
a=b
b=temp
print(“a=”,a)
print(“b=”,b)
Function Call:
swap(5,9)
Output
3. Circulate the Values of n Variables
print(a)
for i in range(1,len(a),1):
print(a[i:]+a[:i])
Output:
enter the list 1234
['1', '2', '3', '4']
['2', '3', '4', '1']
['3', '4', '1', '2']
['4', '1', '2', '3']
Circulate.py
def Circulate(a,n):
return a[n:] + a[:n]
Function Call:
Step 2 : Run the above script using F5 key. The output can be obtained as follows :
2.1
Output:
Enter value of x1
6
Enter value of x2
3
Enter value of y1
9
Enter value of y2
8
Distance between two points is: 3.16
def Leap(year):
if year % 4 == 0 and year %100 != 0 or year % 400 == 0:
print ("\nIs a leap-year")
else:
print ("\nIs not a leap-year")
Output
Program Explanation :
Multiple conditions checked within one If Statement using Logical AND and OR operators.
1: ( year%400 == 0) OR
2: ( year%4 == 0 ) AND
3: ( year%100 == 0))
If these conditions are true then the year value is a leap year value otherwise not.
Basic Python Programs
print(i) i=1
i=i+1 sum=0
Output: n=10
1 while(i<=n):
2 sum=sum+i
3 i=i+1
4 print(sum)
5 Output
55
Basic Python Programs
fact=1 if(n%5==0):
n=int(input()) else:
fact=fact*i Output
Output:
14. Exchange values of two variables using
enter value of n 4
function
Factorial value is 24
def swap():
12. Swap or exchange the values of two variables
a=eval(input("enter a value"))
without using function
b=eval(input("enter b value"))
a=10
c=a
b=20
a=b
print("Before Swapping the values are")
b=c
print(“Value of a”,a)
print("a=",a,"b=",b)
print(“Value of b”,b)
swap()
temp=a
Output:
a=b
enter a value 6
b=temp
enter b value 9
print("After Swapping the values are ")
a= 9 b= 6
print(“Value of a”,a)
print(“Value of b”,b)
Output:
Before Swapping the values are
Value of a 10
Value of b 20
After Swapping the values are
Value of a 20
Value of b 10
Basic Python Programs
15. Circulate the Values of n Variables 16. Distance between Two Points Program:
a=list(input("enter the list")) import math
print(a) print("Enter value of x1")
for i in range(1,len(a),1): x1=int(input())
print(a[i:]+a[:i]) print("Enter value of x2")
Output: x2=int(input())
enter the list 1234 print("Enter value of y1")
['1', '2', '3', '4'] y1=int(input())
['2', '3', '4', '1'] print("Enter value of y2")
['3', '4', '1', '2'] y2=int(input())
['4', '1', '2', '3'] dist = math.sqrt( (x2 - x1)**2 + (y2 - y1)**2 )
print("Distance between two points is: ",dist)
Output:
Enter value of x1
6
Enter value of x2
3
Enter value of y1
9
Enter value of y2
8
Distance between two points is: 3.16