KEMBAR78
Lec 7-8 Basics of Python | PDF | Control Flow | Python (Programming Language)
0% found this document useful (0 votes)
45 views166 pages

Lec 7-8 Basics of Python

Uploaded by

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

Lec 7-8 Basics of Python

Uploaded by

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

Basics of Python

Dr. Raju Pal


Computer Science & Engineering Department,
Jaypee Institute of Information Technology,
Noida, Uttar Pradesh
Outline

1. What is Python?
2. Download & Install Anaconda for Python
3. Learn Basics of Python
4. Conditional Statements in Python
5. Loops of Python
6. Libraries in Python
WHAT’S PYTHON ?
 General purpose programming language
 Named after Monty Python-British comedy
group
 Used to do things from testing microchips at
Intel
 Used to powering Instagram
 building video games ,popular in IoT, Data
Science ,Big Data, AI and so on….
 Followed by millions of users worldwide
Why Python?

Image source:
IEEE
Spectrum Jul
2020
Why Python?
 Fast, lower learning-curve, user-friendly
 Plays well with others
 Runs everywhere
 Known for rich-ecosystem & utilities
 Major advantage is its breadth
 Has thousands of third-party modules and libraries
 Libraries/frameworks are mature and tested for 10+
years
PYTHON TOOLS FOR
SCIENTIFIC COMMUNITY
WHO USES PYTHON?
 Google makes extensive use of Python in its web search
system
 Intel, Cisco, Hewlett-Packard, Seagate, Qualcomm, and
IBM use Python for hardware testing
 YouTube video sharing service is largely written in
Python
 NASA uses Python for hardware testing and satellite
launching
 ...the list goes on...
Download Python
Download and Install Python

1. Go to Google and search


“python”
www.python.org

2. Go to Google and search


“Anaconda”
www.anaconda.com
Python IDE
1. Python default IDE is ‘IDLE”
2. Spyder
3. Jupyter Notebook
4. PyCharm
5. ……… Many More
Python Online IDE
1. Google Colab
2. IDEOne
3. Programiz
4. OnlineGDB
5. ……. Many More
To start Python IDE
Open “Anaconda Prompt”
Start  Anaconda
To start Python IDE
Write on cmd line  idle
Working with Python IDE
To start Python IDE
Click on File  New File
Write first python program in
the file
Save and run (F5)
Working with Spyder
Click on Start and Write  Spyder
Working with Spyder
Click on Start and Write  Spyder
Write python program in file, save and
run (F5)
Working with Jupyter
Notebook
Open Jupyter  Method 1
Click on Start and Write  Jupyter
Notebook
Working with Jupyter
Notebook
Open Jupyter  Method 2
Click on Start and Write  Anaconda
Navigator
 Launch Jupytor
Working with Jupyter
Notebook
1. Click on Start and Write  Jupyter
Notebook
Jupyter will open in Brower
Working with Jupyter
Notebook
1. Click on Start and Write  Jupyter
Notebook
Jupyter will open in Brower
Click on  New  Python 2/3
Working with Jupyter
Notebook

To execute cell  press “ctrl + enter”


Install Python Package
Two ways to install  pip or conda
 Go to Anaconda Prompt and write 
pip install <packageName>
conda install <packageName>
Than
ks
Learning by Doing

raju3131.pal@gmail.
com
BRIEF HISTORY OF PYTHON

Popular version : Python 2.7 –July 4, 2010


Current running : Python 3.6 - December 23, 2016
Latest release : Python 3.7 - June 27, 2018

24
WHAT’S PYTHON BUZZ?

 General purpose programming language


 Named after Monty Python-British comedy
group
 Used to do things from testing microchips at
Intel
 Used to powering Instagram
 building video games ,popular in IoT, Data
Science ,Big Data, AI and so on….
 Followed by millions of users worldwide

25
WHY PROGRAM?
Pre Packaged software available to analyse a model for
your data
Limits the types of analysis
Deviate your research agenda
Can do anything that you want
Limit is your imagination

26
WHY PYTHON?
 Fast, lower learning-curve, user-friendly
 Plays well with others
 Runs everywhere
 Known for rich-ecosystem & utilities
 Major advantage is its breadth
 Has thousands of third-party modules and libraries
 Libraries/frameworks are mature and tested for 10+ years

27
WHY PYTHON?

Image source: IEEE Spectrum Aug 2018

28
PYTHON V/S OTHER
LANGUAGES
 On an average Python code is smaller than JAVA/C++
codes by 3.5 times owing to Pythons built in datatyeps
and dynamic typing.
 Dynamically declare and use variables
 Python is interpreted while C/C++, etc. are compiled.
 Compiler : spends a lot of time analyzing and processing the program, faster
program execution
 Interpreter : relatively little time is spent analyzing and processing the
program, slower program execution

29
PYTHON TOOLS FOR
SCIENTIFIC COMMUNITY

30
WHO USES PYTHON?

 Google makes extensive use of Python in its web search


system
 Intel, Cisco, Hewlett-Packard, Seagate, Qualcomm, and
IBM use Python for hardware testing
 YouTube video sharing service is largely written in Python
 NASA uses Python for hardware testing and satellite
launching
 ...the list goes on...

31
Python Basics
START WORKING WITH
PYTHON
 Open the Python IDLE and execute the following
commands. Observe the output.
10 + 15
print("Hello World")
45 - 34
8 * 2
print("Rahul's age is", 45)
print("I have", 10, "mangoes and", 12, "bananas")

33
START WORKING WITH
PYTHON

Writing
Python
v e St
t i Program an
r a c e M da
e
t o d od rd
n
I M e

34
START WORKING WITH
PYTHON

Standard Mode
Interactive Mode 
 Running your program from
Test One Line at a time
start to finish

35
START WORKING WITH
PYTHON

Python Distribution
 Core Python
 Several Packages

Anaconda is one of them


 300+ packages
 Can add some more
 Two different development environment:
Jupyter & Spyder

36
VARIABLES IN PYTHON
 Variable is a container for data.
e. g. a=10
 Open Python IDLE and execute the following commands.
Observe the output.
emp_number = 1233
print("Employee Number:", emp_number)
emp_salary = 16745.50
emp_name = "Jerry Squaris"
print("Employee Salary and Name:", emp_salary, emp_name)
emp_salary = 23450.34
print("Updated Employee Salary:", emp_salary)

37
VARIABLES IN PYTHON

Fig: Variables like containers[1]

38
VARIABLE DECLARATION

• Data type of the variable is


Dynamic dynamically and automatically
assigned
• Create just the right memory needed
Typing – neither less nor more
• e.g. a=10, b=“Me”, c=12.5

• Data type has to be declared before i


Static is used
• e. g. int a=10, float c = 12.5

Typing 39
VARIABLES AND ITS
DIMENSIONS

Fig: Variable Dimensions [1]

40
DATA TYPES IN PYTHON

Category Data Type Example


int 564
Numeric complex 10+ 5j
float 345.67
Textual string “Python”
Logical boolean True, False

41
DATA STRUCTURE IN PYTHON

• Organization of data in computer so that it can be used


efficiently.
• Provide methods to access and manipulate data.
• Some built-in Data Structures in Python:
 List
 Tuples
 Sets
 Dictionaries

42
VARIABLE NAMING
CONVENTIONS

• Try 1_rollnumber=10
 What is result?
• Variable name must start with an underscore (_) or an
alphabet(upper/lower) followed by any number of
occurrences of alphabets, digits or underscores (_).
• Variable names are case-sensitive.
• Variable name cannot match any of Python's reserved
words(keywords)

43
TEST YOURSELF

1. _age
2. b: _1234
3. c: in
4. d: length (white spaces appended before the
word length)
5. e: 100_emp
6. abc$

44
BUILT-IN FUNCTION type()

 Used to identify data type of any variable


 Try following code:

var1 = 10
print(“Type of var1:”,type(var1))
var2 = “10”
print(“Type of var2:”,type(var2))
var3 = 10.5
print(“Type of var3:”,type(var3))

45
COMPLEX EXAMPLE

complex1 = 10 + 45.6j
Temp = complex1.img +10
print(“Output_1:”,complex1.real)
print(“Output_2:”,Temp)

Output:
Output_1:?
Output_2:?

46
OBJECTS

 Every variable in Python is an object that has:


 Its type
 Its Value
 Its identity (id)

 Object contains either data, functions or both. Called attribute; Data and method
The id() function returns identity of the object (an integer value) which is unique for given object and
remains constant during its lifetime.
id(5)
6406896
 Python variables are references to objects.
 In Python, multiple assignments can be made in a single
statement as follows:
a, b, c = 5, 3.2, "Hello"

47
MEMORY MANAGEMENT
 Code and data are always present in RAM for execution
 Main memory is partitioned into; code, stack, heap
 All objects are in heap and reference variables are in stack
a = 10
b = 20
a 10
c = 10
b
c 20

48
TRY IT
a = 10
b = a
print( “ Value of a and b before
increment”)
print(“id of a: “, id(a))
print(“id of b: “, id(b))
b = a + 1
print( “ Value of a and b after increment”)
print(“id of a: “, id(a))
print(“id of b: “, id(b))

49
VARIABLES IN PYTHON
 Mutable: Mutable object can be changed after it is created.
When you alter the item, the id will be still the same.
Dictionary, List
b = []
id(b) = 140675605442000
b.append(3)
b = [3]
id(b)= 140675605442000 #SAME!
 Immutable: Immutable object can not be changed after it is
created. String, Integer, float, Tuple
a=4
id(a) = -6406896
a=a+1
id(a) = -6406872 # DIFFERENT!
50
PRINT IN PYTHON
 Print method prints the given text message or expression value on
the console, and moves the cursor down to the next line. syntax
o print('Write any message')
 Prints several messages and/or expressions on the same line.
o print (Item1, Item2, ..., ItemN)
 Output formatting
o print('The value of x is {} and y is
{}'.format(5,10))
Here the curly braces fg are used as placeholders. We can specify the
order in which it is printed by using numbers(tupleindex).
 C-like syntax can also be used.
o print("%s %s" %('hello', 'world'))

51
EXERCISE 1
 WAP to print your name two times
 WAP to add three numbers and print result
 WAP to print the following string in a specific format
 Sample String : "Twinkle, twinkle, little star, How I wonder what you are! Up
above the world so high, Liek a diamond in the sky. Twinkle, twinkle, little star,
How I wonder what you are"
Output :

52
COMMENTS IN PYTHON

 For single line comment hash (#) symbol is used.


 For multi-line comments use triple quotes, either "' or
""".
"""This is also a
perfect example of
multi-line comments"""

53
INDENTATION IN PYTHON
Try it:
print(“Python uses indentation”)
print(“will it work?”)
 Python uses indentation instead of braces to determine the
scope of expressions.
 All lines must be indented the same amount to be part of
the scope (or indented more if part of an inner scope).
 This forces the programmer to use proper indentation since
the indenting is part of the program.

54
USER INPUT IN PYTHON

 The input(string) method returns a line of user input as a


string
 Example:
name = input(“Enter player name”)
print(“Player:”,name)
 Try It:
number = input(“Enter player name”)
result = number + 2
print(“Result:”,result)

55
USER INPUT IN PYTHON

Example:

Output:

56
EXERCISE 2

Write a Python program for the following requirements:

Prompt the user to input two numbers num1 and num2

Increment num1 by 4 and num2 by 6

Find and print the sum of new values of num1 and num2

57
PYTHON BASIC OPERATORS

Arithmetic Operators +, -, /, *, %, //

Assignment Operators =, +=, -=, /=, //=, %=

Relational Operators ==, !=, >, <, <=, >=

Logical Operators and, or, not

Bitwise Operators &, |, ^, ~, <<, >>

Membership Operators in, not in


58
TEST YOURSELF
Try it:
x,y,z = 10, “Python”,True
print(x,y,z)

 Output:
 10 Python True
 Syntax Error

59
TEST YOURSELF
Which of the following will give the output as 23?
(Choose all applicable)

1. int("20") + 3
2. "20" + str(3)
3. int(20) + int("3")
4. str(20 + 3)

60
TEST YOURSELF
 What will be the output?
x = 2+3/4%5-2**3**2/5+10//2
print(x)

 Which of the following returns True? (Select all applicable)


Assume: x = 1, y = 4

1. x == 1 and y <= 4
2. True and (x * 4 == y)
3. not(y > x)
4. x <= 1 and y - 2 > x or True
5. not(x - y > 0) or (1 != 1)
6. False or True and False

61
EXERCISE 3

Jack and his three friends have decided to go for a trip by sharing the expenses of the fuel
equally.

Write a Python program to calculate the amount (in Rs) each of them need to put in for the
complete (both to and fro) journey.

The program should also display True, if the amount to be paid by each person is divisible
by 5, otherwise it should display False.

(Hint: Use the relational operators in print statement.)

Assume that mileage of the vehicle, amount per litre of fuel and distance for one way are
given.

62
_ OPERATOR
Returns last accessed object
Works in interactive mode

63
PYTHON MODULE AND
METHODS
Module is set of library functions
Can include entire module or a single function if required

64
PYTHON MODULE AND
METHODS

65
help() AND dir()

 dir(module/object) returns all


available methods of module or
object.
 help(method) returns
documentation of method.

66
Basic Data Types
BASIC DATA TYPES
 Integers (default for numbers).
z=5
Range of int in python is equivalent of a C long
Long Integer an unbounded integer value.
 Floats
z=5.2
 Strings - strings are enclosed within either single quotes or (‘ ') or double
quotes (\ ").
z='python'
z="python"
Use triple double quotes for multi line strings or strings than
contain both ' and " inside of them:
“””python is ' open source
" language"
"""
68
SEQUENCES
Collection of elements
Perform common operation (in addition some specific)
Sequences are:
String
List
Tuple
Dictionaries
Sets

69
REPRESENTATION OF
SEQUENCES

Positive Indices [0] [1] [2] [3] [4]


Circle Rectangle Triangle Square Cube Shapes
Negative Indices [-5] [-4] [-3] [-2] [-1]

Shapes[2] => Triangle


Shapes[3] => Square
Shapes[-2] => Square

70
SLICING IN SEQUENCES
To extract a chunk of elements from a sequence
General Syntax:
Sequence[start : stop]
Returns elements from sequence[start] to sequence[stop-
1]
e. g. Shapes[2:4]
[Triangle
Square]

71
STRING

72
STRING-SLICING
 Which of the following will give an output as "Python"
(Multiple options can be correct):
text ="I love Python“
1. text[7:13]
2. text[8:13]
3. text[7:]
4. text[-6:-1]
5. text[-6:]

73
STRING ESCAPING

74
STRING-CHANGE OR DELETE
 Try it:
S = “Sample”
S[1] = ‘i’
print(S)

 Strings are immutable. This means that elements of a


string cannot be changed once it has been assigned. We
can simply reassign different strings to the same name.

75
STRING-CHANGE OR DELETE
 Try it:
S = “Sample”
S + “Collected”
print(S)

76
STRING-OPERATORS
 + and * can be applied on String objects
 Try It:
s1=“Hello”
s2=“Learners”
print(s1+s2) s1=“Hello”

print(s1*3)

77
STRING-METHODS

78
EXERCISE 3
Accept a string as an input from the user. Check if the
accepted string is palindrome or not.
If the string is palindrome, print "String is palindrome",
otherwise print "String is not palindrome".
Also print the actual and the reversed strings.
Note – Ignore the case of characters.
Hint – A palindrome string remains the same if the
characters of the string are reversed

79
PYTHON LIST

 List is an ordered sequence of items. It is one of the most used datatype


in Python and is very flexible. All the items in a list do not need to be of
the same type.
# empty list
mylist = []
# list of integers
mylist = [1, 2, 3]
# list with mixed datatypes
mylist = [1, "Hello", 3.4]
# nested list
mylist = ["mouse", [8, 4, 6], ['a']]

80
LIST-ACCESSING
# list with mixed datatypes
mylist = [1, "Hello", 3.4]
mylist[0] will return 1
# nested list
mylist = ["mouse", [8, 4, 6], ['a']]
mylist [0][0] return m
mylist [0] return mouse

81
LIST-SLICING

82
LIST-OPERATORS
 + and * can be applied on List objects
 Try It:
L1=[1,2,3,4,5]
L2=[6,7]
print(L1+L2)
print(L2*3)

83
LIST-UPDATE
 Lists are mutable i.e. we can change/modify their content
after it is created.
 General Syntax:
List[index] = new Value

L=[6,7,8,9]
L[3]= 10
print(L)

84
LIST-INSERT

List.append(item)
List.insert(index,item)
List.extend[list]
L1=[6,7,8,9]
L2=[1,2]
L1.insert(2,L2)
print(L1)
L1.append(L2)
print(L1)
L1.extend(L2)
print(L1)

85
LIST-DELETE

List.pop(index)-Default last element


List.remove(item)
del List[index]

L1=[1,2,3,4,5,6,7,8,9,1] del L1[3:5]


L1.pop() print(L1)
print(L1)
L1.clear()
L1.pop(3)
print(L1)
print(L1)
L1[:2]=[]
L1.remove(1)
print(L1)
print(L1)
del L1
del L1[3]
print(L1)
print(L1)

86
LIST-METHODS

List.index(item)
List.sort()
List.reverse()
List.count(item)

L1=[1,2,3,4,5,6,7,8,9,1]
print(L1.index(1))
L1.sort()
print(L1)
L1.reverse()
print(L1)
print(L1.count(8))

87
PYTHON TUPLE

 A tuple is similar to a list. The difference between the


two is that we cannot change the elements of a tuple once
it is assigned whereas in a list, elements can be changed.
 Advantages of Tuple over List
Since tuple are immutable, iterating through tuple is faster
than with list. So there is a slight performance boost.
If you have data that doesn't change, implementing it as
tuple will guarantee that it remains write-protected.

88
CREATING A TUPLE

89
CREATING A TUPLE-WITH
ONE ELEMENT
T=(“Python”)
print(type(T))

T=(“Python”,)
print(type(T))

--Parenthesis are optional. It can be used anywhere.

90
TUPLE-OPERATORS
 + and * can be applied on Tuple objects
 Try It:
T1=(1,2,3,4,5)
T2=(6,7)
print(T1+T2)
print(T2*3)

91
TUPLE-ACCESSING ELEMENT

92
TUPLE-CHANGE, INSERT AND
DELETE

Tuples are immutable which means you cannot update or


change the values of tuple elements. You are able to take
portions of existing tuples to create new tuple.

93
TUPLE-FUNCTIONS

94
SET IN PYTHON
 A set is an unordered collection of items. Every element
is unique (no duplicates) and must be immutable (which
cannot be changed).
 However, the set itself is mutable. We can add or remove
items from it.
 Sets can be used to perform mathematical set operations
like union, intersection, symmetric deference etc.

95
SET-CREATING SET

96
SET-CREATING EMPTY SET

• Try it:
T={}
print(type(T))

97
SET-ADDING ELEMENT

98
SET-REMOVE ELEMENT
 A particular item can be removed from set using
methods, discard() and remove().
 The only difference between the two is that, while using
discard() if the item does not exist in the set, it remains
unchanged. But remove() will raise an error in such
condition.

99
SET-REMOVE ELEMENT

100
SET-OPERATION

# Use & operator or intersection() for intersection


Print (A & B)
#Output: {4, 5}
A.intersection(B)
#Output: {4, 5}

101
PYTHON DICTIONARY
 Dictionary is an unordered collection of key-value pairs. It is generally
used when we have a huge amount of data. Dictionaries are optimized
for retrieving data.
 Creating a dictionary

102
PYTHON DICTIONARY

 Access elements from a dictionary  change or add elements in a dictionary


mydict = {‘name':'Jack', 'age': 26} mydict = {name':'Jack', 'age': 26}
# Output: Jack # update value
mydict['age'] = 27
print(mydict['name'])
# Output: {age': 27, 'name': 'Jack‘}
# Output: 26
print(mydict)
print(mydict.get('age'))
# add item
mydict['address'] = 'Downtown'
# Output: {address': 'Downtown', 'age': 27,
'name': 'Jack’}

103
DICTIONARY-DELETE OR
REMOVE ELEMENT

104
DICTIONARY-NESTING

105
TRY IT
dic={“name”:”xyz”,”Roll_No”:123456,”age”:18}
print(dic.keys())
print(dic.values())
print(dic.items())

Output?

106
RANGES
 Immutable sequence of integers
 General Syntax:

range(start,stop,interval)
print(list(range(10))
print(list(range(5,10))
print(list(range(1,10,2))

107
Control Flow
Statements
STATEMENTS
 Use to compute and assign values

 More specialized statement like return, break, pass, etc.

 Compound statements contain multiple statements and


create block.

109
USE OF INDENTATION
 Uses indentation for block (Compound statements)
 Delimiter for blocks in Python is a colon (:) followed by
indented spaces or tabs

110
CONTROL FLOW IN
PYTHON- SELECTION
 The if else statement is used in Python for decision making

if test expression:
statement(s)
else:
statement(s)
 To test more than one condition following syntax is used
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
111
CONTROL FLOW IN
PYTHON- SELECTION
 Observe the following Python code. Find the value of num3 if the
output of the program is 6.
Num1=2
Num2=5
Num3=?
if(Num2!=5 or abs(Num1-Num3)==6)):
Num2 += 1
elif(Num2-Num3*Num1 == -11):
Num2 +=22
else:
Num2 *= 2
print(Num2)
112
TRUE AND FALSE IN PYTHON
 Things that are False
The boolean value False
The numbers 0 (integer), 0.0 (oat) and 0j (complex).
The empty string "".
The empty list [], empty dictionary and empty set().
 Things that are True
The boolean value True
All non-zero numbers.
Any string containing at least one character.
A non-empty data structure.

113
CONTROL FLOW IN PYTHON-
ITERATION/LOOPING

1. while loop

2. for loop

114
CONTROL FLOW IN
PYTHON- WHILE LOOP

115
CONTROL FLOW IN
PYTHON- FOR LOOP
The for loop in Python is used to iterate over a sequence
(list, tuple, string) or other iterable objects.

 General Syntax

for val in sequence:


Body of for loop

116
CONTROL FLOW IN
PYTHON- FOR LOOP

117
NESTED LOOPING

Nested For Loop


for var1 in sequence:
for var2 in sequence:
statements1
statements2
Nested while Loop
while expression:
Output? while expression:
statement1
statement2

118
BREAK STATEMENT

 The break statement terminates the loop containing it. Control of the
program follows to the statement immediately after the body of the
loop.
 If break statement is inside a nested loop (loop inside another loop),
break will terminate the innermost loop.

119
CONTINUE STATEMENT
The continue statement is used to skip the rest of the code
inside a loop for the current iteration only. Loop does not
terminate but continues on with the next iteration.

120
LOOP WITH ELSE CLAUSE

121
TEST YOURSELF
 What is the value of "a", if the output of the program is 0 0 1?
a = ?
i = 0
while i < a:
print(i)
i += 1
if i == 2:
break
else:
print(0)
Answer- 4, 3, 2 or 1
122
EXERCISE 4

 WAP to add all the numbers from 1 to n and n is given by

user.
 Python Program to Find the Second Largest Number in a

List
 Python Program to check number is prime or not.

 Display all even numbers between 50 and 80 (both

inclusive) using "for" loop.


123
LIST COMPREHENSIONS

numbers = range(10)

l=[]

for i in numbers:
l.append(i**2)

print(l)

124
LIST COMPREHENSIONS

numbers = range(10)

l=[x**2 for x in numbers]

print(l)

Output?

125
EXERCISE 5

 Create a list L that receives N numbers from user. Using

list comprehension compose two lists L1 and L2


containing all even and odd numbers of L respectively.
 Write a Python program to add two matrices.

126
Functions
FUNCTIONS

 Are blocks of organized, reusable code used to perform single or

related set of actions.


 Provide better modularity and high degree of reusability.

128
FUNCTIONS IN PYTHON
 To use a function you always write its name, followed by
some arguments in parentheses ().
 The word argument basically means an input to the function. Then,
the function does some action depending on its arguments.
 When there are multiple arguments to a function, you separate them
with commas (,).
x=3
print(x, x + x , x * x)

129
FUNCTIONS IN PYTHON
 A function may also give back a value (like an output).
For example the function max() (short for maximum)
gives back the largest out of all of its arguments, which
must be numbers.
print(max(42, 17))
print(max(128,281,812))

130
FUNCTIONS IN PYTHON

In-built functions

User defined functions

x = min(max(13, 7), 9)
print(x)

131
There is a single road between the two cities. The road has three bridges
with weight limits a, b, c, as shown in the picture below:
In order to drive along the route, your truck needs to drive first over the
bridge with weight limit a, then the one with weight limit b, then the one
with weight limit c. Your truck will crash if you overload any of the three
weight limits. Write a program that prints out the maximum weight that
can be transported along this road. Your code should assume that the
variables a, b, and c already contain the bridge weight limits.

132
Now we will tell you the whole story. There is also a second
route consisting of two bridges, the first with weight limit d, and the
second with weight limit e, as illustrated below.

Your truck can take either route. Write a program that prints out the
maximum weight that can be transported between the two cities.
Assume that the variables a, b, c, d, and e contain the bridge weight
limits.

133
FUNCTIONS IN PYTHON

 General Syntax:
def functionname(parameters):
statement(s)

134
DEFINING FUNCTIONS

135
FUNCTIONS-EXAMPLE

136
EXERCISE 6

Define following functions:


Area_rect(l,b)
Area_circle(r)
Area_sq(a)
Area_tri(side)

137
TYPES OF FUNCTION
ARGUMENTS

Different types of function arguments:


Required arguments
Keyword arguments
Default arguments
Variable – length arguments

139
FUNCTION-REQUIRED ARGUMENTS

def printinfo(name,age):
print (“Name:”,name)
print(“Age:”,age)

printinfo(29,“Kushagra”)
printinfo(“Kushgra”,29)

140
FUNCTION-KEYWORD ARGUMENTS

def printinfo(name,age):
print (“Name:”,name)
print(“Age:”,age)

printinfo(29,“Kushagra”)
printinfo(age=29,name=“Kushgra”)

141
FUNCTION-DEFAULT ARGUMENTS

142
FUNCTION-VARIABLE LENGTH
ARGUMENTS

143
SCOPE OF VARIABLE

 Determines accessibility of a variable at various portions of the program

• Defined inside a function


Local • Can be accessed only inside
the function
• Defined outside the functions
Global • Can be accessed throughout
the program

144
SCOPE OF VARIABLE

145
SCOPE OF VARIABLE

146
SCOPE OF VARIABLE
 Which of the following code snippets gives the output as:
2
3

147
RECURSION IN PYTHON
 Recursion is the process of defining something in terms
of itself.

148
LAMBDA FUNCTION
 To create an anonymous function in the form of an expression, use the
lambda statement:
Syntax
lambda args : expression
 args is a comma-separated list of arguments, and expression is an
expression involving those arguments. For example:
a = lambda x, y : x+y
print a(2,3) # produces 5

149
PYTHON MODULE
 Modules refer to a file containing Python statements and definitions.
 A file containing Python code, for e.g.: example.py, is called a module
and its module name would be example.
 First create a module example.py

150
MODULE-IMPORT
Use import module to import the definition of module

import example
example.add(4,5.5)

151
MODULE-IMPORT STATEMENT

152
MODULE-IMPORT STATEMENT

153
EXERCISE 6
 Write a Python function that takes two lists and returns
True if they have at least one common member.
 Write a Python program to print a specified list after
removing the 0th, 4th and 5th elements.
 Python Program to sum all the Items in a Dictionary.

154
FILE HANDLING IN PYTHON
 File is a named location on disk to store related information. It is used to
permanently store data in a non-volatile memory (e.g. hard disk).
 File operations
- Open a file
- Read or write (perform operation)
- Close the file

155
FILE HANDLING IN PYTHON

fileObject = open(file_name [,access_mode]


[,buffering])

156
FILE OPERATION

157
FILE OPERATIONS
 Unlike other languages, the character 'a' does not imply the number
97 until it is encoded using ASCII (or other equivalent encodings).
 Moreover, the default encoding is platform dependent. In windows, it
is 'cp1252' but 'utf-8' in Linux.
 Hence, when working with files in text mode, it is highly
recommended to specify the encoding type.
f = open("test.txt", mode = 'r', encoding = 'utf-8')
 In case any exception occurs use a try...finally block.
try:
f = open("test.txt",encoding = 'utf-8')
# perform le operations
finally:
f.close()

158
FILE ATTRIBUTES

 Once a file is opened following list of attributes can get information


related to file:

159
FILE ATTRIBUTES

 Once a file is opened following list of attributes can get information


related to file:

160
FILE ATTRIBUTES

161
WRITE TO AND READ FROM
A FILE

162
WRITE TO AND READ FROM
A FILE

163
Writing

164
165
EXERCISE 7
 Python Program to Count the Number of Words in a Text File.
 Python Program to Read a String from the User and Append it into a
File.

166

You might also like