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

Unit Ii

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views23 pages

Unit Ii

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

UNIT-2

DATA TYPES, EXPRESSIONS AND STATEMENTS

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:

 Python is an interpreted programming language.


 It is high level and object oriented programming language.
 It was created by Guido van Rossum during 1985 - 1990.
 Python 3.0 was released in 2008.
 Name Python was selected from “Monty Python‟s Flying Circus” a British sketch comedy series
created by comedy group Monty Python and broadcast by BBC

Features of Python Programming:

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

1. Numbers – Integers and Float

2. Boolean

3. Strings

4. List

5. Tuple

6. Dictionary

7. Sets

1. Numbers : In Python, there are three different types of numerical types

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.

For example – 3.14, -88.33

iii) long : It represents the long integers. These can be represented in octal and hexadecimal.

For example 74563284L, -0x1879L


2. Boolean: Boolean is a data type named after George Boole (1815-1864).

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

3. 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,

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:

String is collection of characters. Concatenation and Repetition operations are performed on


strings using operators like + and *. For example

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

>>> mytuple =(10,20,30,40)


>>> print(mytuple[0])
10
>>> print(mytuple[1:3])
(20, 30)
>>>
4. Dictionary:
It is a kind of hash data type in which elements are present in form of key-value pair format..
Dictionaries are enclosed within curly brackets {…}.

For example –

>>> mydict={'name':'AAA','roll':10,'marks':94}

>>> print(mydict.keys())

dict_keys(['name', 'roll', 'marks'])

>>> print(mydict.values())

dict_values(['AAA', 10, 94])

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

>>>

Variable, Expressions and Statements

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

Expressions and Statements

Expression is a combination of values, variables and operators. Value is considered as an


expression. For example : Following are expressions

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

Consider the expression 4+5=9

Here, 4 and 5 are called operands and + is called operator

Here + operator is for addition, * is for multiplication and ** is for exponentiation.

 When more than one operator appears in an expression, Order depends on rules of precedence.

Acronym PEMDAS is a useful way to remember the order of operations.

1. P : Parentheses have highest precedence.

2. E : Exponentiation has the next highest 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

Examples a=10 b=5

Arithmetic operators Output:


print("a+b=",a+b) 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) a%b= 0
print("a//b=",a//b) a//b= 2
print("a**b=",a**b) a**b= 100000

Assignment Operators: It is used in Python to assign values to variables.

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:

It is used to compare values. It either returns True or False according to condition.

Operator Example

== Equal to (a == b) is not true

!= Not Equal to (a!=b) is true

< Less than (a > b) is not true.

> Greater than (a < b) is true.

<= Less than Equal to (a >= b) is not true

>= Greater than Equal to (a <= b) is true.

Example : a=10 b=5

Comparison (Relational) Operators Output

print("a>b=>",a>b) a>b=> True

print("a>b=>",a<b) a>b=> False

print("a==b=>",a==b) a==b=> False

print("a!=b=>",a!=b) a!=b=> True

print("a>=b=>",a<=b) a>=b=> False

print("a>=b=>",a>=b) a>=b=> True

Logical Operators: Logical operators are and, or, not operators.


Example a = True b = False

Logical Operator Output

print('a and b is',a and b) a and b is False

print('a or b is',a or b) a or b is True

print('not a is',not a) not a is False

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

Example: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)

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.

For example : The tuple can be created as follows :


>>> student = ('AAA',96,'Std_X')
>>> print(student)
('AAA', 96, 'Std_X')
>>> print(student[0])
AAA
>>> print(student[1:3])
(96, 'Std_X')
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:
temp = a
a=b
b = temp
Tuple assignment solves this problem neatly:

(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:

# This is comment line


print(“I love my country”)
Output: I love my country

# print(„This is not run‟)


print(„Hello‟)
Output: Hello

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

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
2. Swapping - Exchange the values of two variables by using function

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

Circulate the values of n variable with the help of list.


Suppose list a is created as [1,2,3,4], then 4 variables can be rotated as follows –

Program with Output:

a=list(input("enter the list"))

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']

Program – Function Definition


Step 1 : Create a function for circulating the values. Save this function in some file.

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

Program with Output:


4. Distance between Two Points
Program:
import math
print("Enter value of x1")
x1=int(input())
print("Enter value of x2")
x2=int(input())
print("Enter value of y1")
y1=int(input())
print("Enter value of y2")
y2=int(input())
dist = math.sqrt( (x2 - x1)**2 + (y2 - y1)**2 )
print("The 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

5. Test for Leap Year

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.

These conditions are -

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

1. Addition of two numbers: 3. Area & circumference of circle


print("enter first number") print(“enter the radius of circle”)
a=input() r=int(input())
print("enter first number") a=3.14*r*r
b=input() c=2*3.14*r
a=int(a) print(“the area of circle”,a)
b=int(b) print(“the circumference of circle”,c)
c=a+b Output:
print("the sum is ",c) enter the radius of circle 3
Output: the area of circle 28.259
enter first number the circumference of circle 18.84
9
4. Area of rectangle
enter first number
l=int(input(“enter the length of rectangle”))
6
b=int(input(“enter the breath of rectangle”))
the sum is 15
a=l*b
2. Subtraction of two numbers:
print(a)
print("enter first number")
Output
a=input()
enter the length of rectangle 5
print("enter first number")
enter the breath of rectangle 6
b=input()
30
a=int(a)
5. Check voting eligibility
b=int(b)
age=int(input(“enter your age”))
c=a-b
If(age>=18):
print("Subtraction of two numbers ",c)
print(“eligible for voting”)
Output:
else:
enter first number
print(“not eligible for voting”)
81
Output:
enter first number
Enter your age
61
19
Subtraction of two numbers 20
Eligible for voting
enter ur age17
not eligible for voting
Basic Python Programs

6. Find greatest of three numbers 8. Print n even numbers


a=int(input("enter the value of a")) i=2
b=int(input("enter the value of b")) n=10
c=int(input("enter the value of c")) while(i<=n):
if(a>b): print(i)
if(a>c): i=i+2
print("the greatest no is",a) Output
else: 2
print("the greatest no is",c) 4
6
else:
8
if(b>c): 10
print("the greatest no is",b)
9. Print n odd numbers
else:
i=1
print("the greatest no is",c)
n=10
Output:
while(i<=n):
enter the value of a 9
print(i)
enter the value of b 6
i=i+2
enter the value of c 5
Output
the greatest no is 9
1
3
7. Print n natural numbers
5
7
i=1
9
n=5
while(i<=n): 10. Find sum of n numbers

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

11. Factorial of n numbers 13. Check the no divisible by 5 or not


i=1 n=eval(input("enter n value"))

fact=1 if(n%5==0):

print("enter value of n") print(" number is divisible by 5")

n=int(input()) else:

while(i<=n): print(" number not divisible by 5")

fact=fact*i Output

i=i+1 enter n value10

print(“Factorial value is “,fact) number is divisible by 5

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

You might also like