Unit - 1
Unit - 1
III Python Complex data types: Using string data type and string operations, Defining list and list slicing, Use of 04
Tuple data type. String, List and Dictionary, Manipulations Building blocks of python programs, string
manipulation methods, List manipulation. Dictionary manipulation, Programming using string, list and dictionary
in-built functions. Python Functions, Organizing python codes using functions.
IV Python File Operations: Reading files, Writing files in python, Understanding read functions, read(), readline(), 04
readlines(). Understanding write functions, write() and writelines() Manipulating file pointer using seek
Programming, using file operations.
V Python packages: Simple programs using the built-in functions of packages matplotlib, numpy, pandas etc. GUI 04
Programming: Tkinter introduction, Tkinter and PythonProgramming, Tk Widgets, Tkinter examples. Python
programming with IDE.
Features of Python
•
#create a set
>>> set1 = {10,20,3.14,"New Delhi"}
>>> print(type(set1))
<class 'set'>
>>> print(set1)
{10, 20, 3.14, "New Delhi"}
#duplicate elements are not included in set
• >>> set2 = {1,2,1,3}
>>> print(set2)
{1, 2, 3}
None
var = None
# checking it's value
None is a special data type with a single value. if var is None:
It is used to signify the absence of value in a situation. print("var has a value
of None")
None supports no special operations, and it is neither else:
print("var has a
same as False nor 0 (zero). value")
>>> print(myVar)
None
Mapping
Mapping is an unordered data type in Python. Currently,
there is only one standard mapping data type in Python Example 5.8
called dictionary. #create a dictionary
(A) Dictionary
Dictionary in Python holds data items in key-value pairs. >>> dict1 = {'Fruit':'Apple',
'Climate':'Cold', 'Price(kg)':120}
Items in a dictionary are enclosed in curly brackets { }. >>> print(dict1)
Dictionaries permit faster access to data.
{'Fruit': 'Apple', 'Climate': 'Cold',
Every key is separated from its value using a colon (:) sign. 'Price(kg)': 120}
The key : value pairs of a dictionary can be accessed using >>> print(dict1['Price(kg)'])
the key. 120
The keys are usually strings and their values can be any data
type.
In order to access any value in the dictionary, we have to
specify its key in square brackets [ ].
Mutable and Immutable Data Types
• Variables whose values can be changed
after they are created and assigned are
called mutable.
• Variables whose values cannot be changed
after they are created and assigned are
called immutable.
• When an attempt is made to update the
value of an immutable variable, the old
variable is destroyed and a new variable is
created
by the same name in memory.
Python data types can be classified into
mutable and immutable as shown in Figure
5.7
List Comprehension
• List comprehension offers a shorter syntax when you want to create a new list based on the
values of an existing list.
• Example: Based on a list of fruits, you want a new list, containing only the fruits with the
letter "a" in the name.
• Without list comprehension you will have to write a for statement with a conditional test
inside:
//Without list comprehension
fruits =
// with list comprehension
["apple", "banana", "cherry", "kiwi", "mango
"]
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
for x in fruits:
newlist = [x for x in fruits if "a" in x]
if "a" in x:
newlist.append(x)
print(newlist)
print(newlist)
Arithmetic Operators
Relational Operators
Assignment Operators
Questions
a) num1 += num2 + num3
print (num1)
• Give the output of the following when num1 = 4, num2 = 3, num3
Output:9
=2 b) num1 = num1 ** (num2 + num3)
• a) num1 += num2 + num3 print (num1)
• print (num1) Output:1024
• b) num1 = num1 ** (num2 + num3) c) num1 **= num2 + num3
Output:1024
• print (num1)
d) num1 = ‘5’ + ‘5’
• c) num1 **= num2 + num3 print(num1)
• d) num1 = ‘5’ + ‘5’ Output:55
• print(num1) e) print(4.00/(2.0+2.0))
• e) print(4.00/(2.0+2.0)) Output:1.0
f) num1 = 2+9*((3*12)-8)/10
• f) num1 = 2+9*((3*12)-8)/10 print (num1)
• print(num1) Output:27.2
• g) num1 = 23// 4 // 2 g) num1 = 24 // 4 // 2
print(num1)
Output:2
Ans
Questions a) Assign 10 to variable length and 20 to variable
breadth.
length = 10
• Write the corresponding Python assignment breadth = 20
statements: b) Assign the average of values of variables length and
• a) Assign 10 to variable length and 20 to breadth to a variable sum.
variable breadth. Sum = (length + breadth)/2
• b) Assign the average of values of variables c) Assign a list containing strings ‘Paper’, ‘Gel Pen’,
length and breadth to a variable sum. and ‘Eraser’ to a variable stationery.
• c) Assign a list containing strings ‘Paper’, ‘Gel Stationary=[‘Paper’ , ‘Gel Pen’ , ‘Eraser’
Pen’, and ‘Eraser’ to a variable stationery. d) Assign the strings ‘Mohandas’, ‘Karamchand’, and
• d) Assign the strings ‘Mohandas’, ‘Gandhi’ to variables first, middle and last.
‘Karamchand’, and ‘Gandhi’ to variables first, first = ‘Mohandas’
middle and last.
middle= ‘Karamchand’
• e) Assign the concatenated value of string last= ‘Gandhi’
variables first, middle and last to variable
fullname. Make sure to incorporate blank e) Assign the concatenated value of string variables
spaces appropriately between different parts first, middle and last to variable fullname. Make sure
of names. to incorporate blank spaces appropriately between
different parts of names.
fullname = first +” “+ middle +” “+ last
Logical Operators
Questions
STATEMENT LOGICAL EXPRESSIONS
The sum of 20 and –10
Write logical expressions corresponding to the is less than 12.
(20 + (-10)) < 12
following statements in Python and evaluate num3 is not more than num3 <=
the expressions (assuming variables num1, 24. 24 or not(num3 > 24)
num2, num3, first, middle, last are already 6.75 is between the (6.75 >=
having meaningful values): values of integers num1 num1) and (6.75 <=
and num2. num2)
a) The sum of 20 and –10 is less than 12. e.g. The string ‘middle’ is
(20 + (-10)) < 12 larger than the string (middle >
b) num3 is not more than 24. ‘first’ and smaller than first) and (middle < last)
c) 6.75 is between the values of integers num1 the string ‘last’.
and num2. List Stationery is empty. len(Stationery) == 0
d) The string ‘middle’ is larger than the string
‘first’ and smaller than the string ‘last’.
e) List Stationery is empty.
Identity Operators
Membership Operator
What will be the outcome [AKTU Q]
a=0
b=2
c=3
x= c or a
print(x)
Precedence of Operators
• Add a pair of parentheses to each expression so
that it evaluates to True.
• a) 0 == 1 == 2 e.g. (0 == (1 == 2))
EXPRESSION WITH
EXPRESSION
PARENTHESIS
• b) 2 + 3 == 4 + 5 == 7 0 == 1 == 2 (0 == (1 == 2))
2 + 3 == 4 + 5 == 7 (2 + (3 == 4 )+ 5) == 7
• c) 1 < -1 == 3 > 4 (1 < -1 ) == (3 > 4)
• 1 < -1 == 3 > 4
I NPUT AND OUTPUT statement
>>> fname = input("Enter your first name: ")
Enter your first name: Rajiv
>>> age = input("Enter your age: ")
Enter your age: 46
>>> type(age)
<class 'str'>
Function int() to convert string to integer
>>> age = int( input("Enter your age:"))
Enter your age: 19
>>> type(age)
<class 'int'>
Enter a number and double it.
a=a+b
b=a-b
a=a-b
print("After swap",a,b)
Write a program that asks the user to enter their name and age.
Print a message addressed to the user that tells the user the
year in which they will turn 100 years old.
Answer:
fromdatetime import datetime
name = input(‘Name \n’)
age = int(input(‘Age \n’))
defhundred_year(age):
hundred = int((100-age) + datetime.now().year)
return hundred
x=hundred_year(age)
print (‘Hello %s. You will turn 100 years old in %s.’ % (name,x))
import math
defheight_reched(length,degrees):
radian=math.radians(degrees)
Presume that a ladder is put upright against sin=math.sin(radian)
a wall. Let variables length and angle store height=round(length*sin,2)
the length of the ladder and the angle that it return height
forms with the ground as it leans against the
wall. Write a Python program to compute the print(” height reached by the ladder on the wall for
height reached by the ladder on the wall for the length is 16 feet and 75 degrees “)
the following values of length and angle: print(height_reched(16,75))
a)16 feet and 75 degrees print(” height reached by the ladder on the wall for
b)20 feet and 0 degrees the length is 20 feet and 0 degrees “)
c)24 feet and 45 degrees print(height_reched(20,0))
d)24 feet and 80 degrees print(” height reached by the ladder on the wall for
the length is 24 feet and 45 degrees “)
print(height_reched(24,45))
print(” height reached by the ladder on the wall for
the length is 24 feet and 80 degrees “)
print(height_reched(24,80))
Raise Keyword
• Python Python raise Keyword is used to raise exceptions or errors.
The raise keyword raises an error and stops the control flow of the
program. It is used to bring up the current exception in an exception
handler so that it can be handled further up the call stack.
• Python Raise Syntax
• raise {name_of_ the_ exception_class}
a=5
if a % 2 != 0:
raise Exception("The number shouldn't be an odd integer")
s = 'apple'
try:
num = int(s)
except ValueError:
raise ValueError("String can't be
changed into integer")
Conclusion
• Python is an open-source, high level, interpreter- based language that
can be used for a multitude of scientific and non-scientific computing
purposes.
• Comments are non-executable statements in a program.
• An identifier is a user defined name given to a variable or a constant
in a program.
• The process of identifying and removing errors from a computer
program is called debugging.
• Trying to use a variable that has not been assigned a value gives an
error.
• There are several data types in Python — integer, boolean, float,
complex, string, list, tuple, sets, None and dictionary.
Thank You