LH Python
LH Python
COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
CSE I / II
Course Name with Code : 21GES08&Python Programming
WHAT IS PROGRAMMING:
Program - Sequence of instructions that specifies how to perform a computation. The computation
may be mathematical symbolic computation.
Example:
# Python Program - Get String Input from User
str = input("Enter any string: ")
print(str)
Input - Data from the keyboard, a file,the network or some other device.
Example :>>> n=int(input(“enter the number”))
Output - Display data on the screen, save it in a file, transaferred over the network etc.
Example :>>> print('Hello, world!')
math - Basic mathematical operations like addition and multiplications.
Example: 1
1. # Store input numbers:
2. num1 = input('Enter first number: ')
3. num2 = input('Enter second number: ')
4. # Add two numbers
5. sum = float(num1) + float(num2)
6. # Subtract two numbers
7. min = float(num1) - float(num2)
8. # Multiply two numbers
9. mul = float(num1) * float(num2)
10. #Divide two numbers
11. div = float(num1) / float(num2)
12. # Display the sum
13. print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
14. # Display the subtraction
15. print('The subtraction of {0} and {1} is {2}'.format(num1, num2, min))
16. # Display the multiplication
17. print('The multiplication of {0} and {1} is {2}'.format(num1, num2, mul))
18. # Display the division
19. print('The division of {0} and {1} is {2}'.format(num1, num2, div))
Example:2
20. # Python Program to find the area of triangle
21. a = float(input('Enter first side: '))
22. b = float(input('Enter second side: '))
23. c = float(input('Enter third side: '))
24. # calculate the semi-perimeter
25. s = (a + b + c) / 2
26. # calculate the area
27. area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
28. print('The area of the triangle is %0.2f' %area)
Conditional execution - Check for certain conditional and run the appropriate code.
Example:1
# User enters the number
number =int(input("Enter number: "))
# checking the number
if number <0:print("The entered number is negative.")elif number >0:
print("The entered number is positive.")
elif number ==0:
print("Number is zero.")
else:
print("The input is not a number")
Example:2
# User enters the year
year = int(input("Enter Year: "))
Example:1
# taking input from user
number = int(input("Enter any number: "))
# prime number is always greater than 1
if number > 1:
for i in range(2, number):
if (number % i) == 0:
print(number, "is not a prime number")
break
else:
print(number, "is a prime number")
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING
COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
L-2
LECTURE HANDOUTS
CSE I / II
Course Name with Code : 21GES08&Python Programming
Debugging- Programming errors are called as bugs, and the process of tracking them down is called as
debugging.
Example:1
Python program to add two numbers
num1 =15
num2 =12
# Adding two nos
sum=num1 +num2
# printing values
print("Sum of {0} and {1} is {2}".format(num1, num2, sum))
Example:2
# Python swap program
x = input('Enter value of x: ')
y = input('Enter value of y: ')
# create a temporary variable and swap the values
temp = x
x=y
y = temp
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))
Example:3
Example 4:
1. #Collect input from the user
2. celsius = float(input('Enter temperature in Celsius: '))
3. # calculate temperature in Fahrenheit
4. fahrenheit = (celsius * 1.8) + 32
5. print('%0.1f Celsius is equal to %0.1f degree Fahrenheit'%(celsius,fahrenheit))
Example 5:
6. import calendar
7. # Enter the month and year
8. yy = int(input("Enter year: "))
9. mm = int(input("Enter month: "))
# display the calendar
print(calendar.month(yy,mm))
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING
COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
CSE I / II
Course Name with Code : 21GES08&Python Programming
Introduction :
The languages are of two types Formal and Natural Languages.
Natural languages evolve naturally and formal languages are languages designed by people to
solve specific applications.
Programming languages like C, C++, , Python are formal languages.
Natural Languages: Natural Languages are the languages spoken by the people such as English,
Spanish etc, They are not designed by the people, the natural languages evolve naturally.
Formal languages: Languages designed by people for specific applications. Programming languages
are formal languages that are designed to impress computations.
Eg: Notations used by mathematicians to denote relationships among numbers and symbols
Chemists the formal language to represent the chemical structure of mole
Formal language has strict syntax rules that govern the structure of statements. Syntax rules are
different for token and structure. Tokens are the basic demands of the language such as words,
members and chemical demands,
Examining the program and analyzing the syntactic structure is called are passing.
Formal languages
Example:1
1. age = int (input("Enter your age? "))
2. if age>=18:
3. print("You are eligible to vote !!");
4. else:
5. print("Sorry! you have to wait !!");
Example:2
1. num = int(input("enter the number?"))
2. if num%2 == 0:
3. print("Number is even...")
4. else:
5. print("Number is odd...")
Example:3
1. a = int(input("Enter a? "))
2. b = int(input("Enter b? "))
3. c = int(input("Enter c? "))
4. if a>b and a>c:
5. print("a is largest")
6. if b>a and b>c:
7. print("b is largest")
8. if c>a and c>b:
9. print("c is largest")
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING
COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
CSE I / II
Course Name with Code : 21GES08&Python Programming
3. Interpreted languages- An interpreter is a program that reads and executes code. This includes source
code, pre-compiled code, and scripts. Common interpreters include Perl, Python,
and Ruby interpreters, which execute Perl, Python, and Ruby code respectively.
4. Cross- platform languages- python runs on different platforms such as window, unix, linux etc,
5.Free and open sources- ptthon languages and its sources code is freely available- The term "open
source" refers in general to something that can be modified and shared because its design is publicly
accessible. An open source programming language is thus one in which the source code to the
language's compiler or interpreter is accessible for viewing, modifying and redistributing to the world.
6. object oriented languages-python is also an object-oriented language since its beginning. Python is
an object-oriented programming language. It allows the users to develop applications using an Object
Oriented approach. In Python, classes and objects can be created easily.
10.Extensible
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING
COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
LECTURE HANDOUTS
L-5
CSE I / II
Course Name with Code : 21GES08&Python Programming
2. Ensure that the Install launcher for all users (recommended) and the Add Python 3.7 to
PATH checkboxes at the bottom are checked.
If the Python Installer finds an earlier version of Python installed on your computer, the Install
Now message may instead appear as Upgrade Now (and the checkboxes will not appear).
3. Highlight the Install Now (or Upgrade Now) message, and then click it.
When run, a User Account Control pop-up window may appear on your screen. I could not
capture its image, but it asks, Do you want to allow this app to make changes to your device.
A new Python 3.7.4 (64-bit) Setup pop-up window will appear with a Setup Progress message
and a progress bar.
During installation, it will show the various components it is installing and move the progress bar
towards completion. A new Python 3.7.4 (64-bit) Setup pop-up window will appear with a Setup was
successfuly message.
5. Click the Close button.
Video Content / Details of website for further learning (if any):
https://www.youtube.com/watch?v=K2ah7wxHlzg
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING
COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
L-6
LECTURE HANDOUTS
CSE I / II
Course Name with Code : 21GES08&Python Programming
Topic of Lecture: Running Python programs, Modes Demo, Python modes Demo
Introduction :
Python runs on different platforms. Once the python programs are typed and saved they are
executed.
Python program upon execution provides the output.
Short cut key for running python programs are F5. Python runs in two modes.
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
CSE
I/II
Course Name with Code : 21GES08&Python Programming
Avalueisoneofthebasicthingsaprogramworkswith,likealetteroranumber.
Example: 2 is an integer, 42.0 is a floating-point number and 'Hello, World!' is a string.
The interpreter tells the type of value
Example:1
>>> type(2)
<class 'int'>
>>> type(42.0)
<class 'float'>
>>> type('Hello, World!')
<class 'str'>
Example:2
>>> type('2')
<class 'str'>
>>> type('42.0')
<class 'str'>
They’re strings.
Value:
Value can be any letter ,number or string.
Eg,Valuesare2,42.0,and'Hello,World!'.(Thesevaluesbelongtodifferent 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 NumericalValues.
Thisdatatypeisimmutable[i.e.values/itemscannotbechanged].
Pythonsupportsintegers,floatingpointnumbersandcomplexnumbers.They are definedas,
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
CSE
I/II
Course Name with Code : 21GES08&Python Programming
Lists are represented by boxes with the word “list” outside and the elements of the list inside. cheeses
refers to a list with three elements indexed 0, 1 and 2. numbers con‐ tains two elements; the diagram
shows that the value of the second element has been reassigned from 123 to 5. empty refers to a list
with no elements.
Expressions and Statements
An expression is a combination of values, variables, and operators. A value all by itself is considered an
expression, and so is a variable, so the following are all legal expressions:
Example
>>> 42
42
>>> n 17
>>> n + 25 42
When an expression is typed at the prompt, the interpreter evaluates it, which means that it finds the
value of the expression. In this example, n has the value 17 and n + 25 has the value 42.
A statement is a unit of code that has an effect, like creating a variable or displaying a value.
>>> n = 17
>>> print(n)
17
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.
Video Content / Details of website for further learning (if any):
https://www.w3schools.com/python/
Important Books/Journals for further learning including the page nos.:
Guido van Rossum and Fred L. Drake Jr, An Introduction to Python, Network Theory Ltd, 2011,
Page no 83-85
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
CSE I/II
1 **
Exponentiation (raise to the power)
2 ~+-
Complement, unary plus and minus (method names for the last
two are +@ and -@)
3 * / % //
Multiply, divide, modulo and floor division
4 +-
Addition and subtraction
5 >><<
Right and left bitwise shift
6 &
Bitwise 'AND'
7 ^|
Bitwise exclusive `OR' and regular `OR'
8 <= <>>=
Comparison operators
9 <> == !=
Equality operators
10 = %= /= //= -= += *= **=
Assignment operators
11 is is not
Identity operators
12 in not in
Membership operators
13 not or and
Logical operators
Comments
As programs get bigger and more complicated, they get more difficult to read. Formal languages
are dense, and it is often difficult to look at a piece of code and figure out what it is doing, or why.
For this reason, it is a good idea to add notes to your programs to explain in natural language what
the program is doing. These notes are called comments, and they start with the # symbol:
# compute the percentage of the hour that has elapsed percentage = (minute * 100) / 60
In this case, the comment appears on a line by itself. You can also put comments at the end of a
line:
percentage = (minute * 100) / 60 # percentage of an hour
Everything from the # to the end of the line is ignored—it has no effect on the execu‐ tion of the
program.
Comments are most useful when they document non-obvious features of the code. It is reasonable
to assume that the reader can figure out what the code does; it is more useful to explain why.
This comment is redundant with the code and useless:
v = 5 # assign 5 to v
This comment contains useful information that is not in the code:
v = 5 # velocity in meters/second.
Good variable names can reduce the need for comments, but long names can make complex
expressions hard to read, so there is a trade-off.
Video Content / Details of website for further learning (if any):
https://www.w3schools.com/python/
Important Books/Journals for further learning including the page nos.:
Guido van Rossum and Fred L. Drake Jr, An Introduction to Python, Network Theory Ltd, 2011,
Page no 83-85
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
CSE I/II
Course Name with Code : 21GES08&Python Programming
Introduction :
The decision, in most cases, depends on the value of variables or arithmetic expressions are
evaluated using the Boolean True or False values.
The instructions for decision making are called conditional statements, executed under the given
conditions.
In many cases there are two code parts: One which will be executed, if the condition is True, and
another one, if it is False.
In other words, a branch determines which of two (or even more) program parts (alternatives)
will be executed depending on one (or more) conditions.
Conditional statements and branches belong to the control structures of programming languages,
because with their help a program can react to different states that result from inputs and
calculations.
BOOLEAN VALUES:
Boolean:
Boolean data type have two values. They are 0 and 1.
0 represents False
1 represents True
True and False are keyword.
Example:
>>> 3==5
False
>>> 6==6
True
>>>True+True
2
>>>False+True
1
>>> False*True
0
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:
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators
Arithmetic operators:
// Floor Division - The division of operands where the result is the 5//2=2
quotient in which the digits after the decimal point are removed
> If the value of left operand is greater than the value of right (a > b) is not
operand, then condition becomes true. true.
< If the value of left operand is less than the value ofrightoperand, then (a < b) is true.
condition becomes true.
>= If the value of left operand is greater than or equal to the value (a >= b) is not
of right operand, then condition becomes true. 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.
Assignment Operators
Assignment operators are used in Python to assign values to variables.
Operator Description Example
= Assigns values from right side operands to leftside c = a + b assignsvalue
operand of a + b into c
+= Add AND It adds right operand to the left operand andassign the c += a is equivalentto
result to left operand c=c+a
-= Subtract AND It subtracts right operand from the left operand c -= a is equivalentto c
and assign the result to left operand =c-a
*= Multiply and assign the result to left operand c *= a is equivalentto c
AND =c*a
/= Divide AND It divides left operand with the right operand andassign c /= a is equivalentto c
the result to left operand = c / ac /= a
isequivalent to c = c/ a
%= Modulus It takes modulus using two operands and assignthe result c %= a isequivalent to
AND to left operand c = c% a
Bitwise Operators:
Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
Membership Operators:
Evaluates to find a value or a variable is in the specified sequence of string, list, tuple,
dictionary or not.
To check particular element is available in the list or not
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.
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
CSE I/II
Course Name with Code : 21GES08&Python Programming
Example:
1. Program to provide flat rs 500, if the purchase amount is greater than 2000.
2. Program to provide bonus mark if the category is sports.
Flowchart:
Examples:
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
L-9
LECTURE HANDOUTS
CSE I/II
Course Name with Code : 21GES08&Python Programming
Introduction :
In many cases there are two code parts: One which will be executed, if the condition is True, and
another one, if it is False.
In other words, a branch determines which of two (or even more) program parts (alternatives)
will be executed depending on one (or more) conditions.
Conditional statements and branches belong to the control structures of programming languages,
because with their help a program can react to different states that result from inputs and
calculations.
If the condition1 is False, it checks the condition2 of the elif block. If all the
conditions are False, then the else part is executed.
The elif is short for else if.This is used to check more than one condition.If the condition1 is
False, it checks the condition2 of the elif block. If all the conditions are False, then the else part
is executed.Among the several if...elif...else part, only one part is executed according to the
condition
The if block can have only one else block. But it canmultiple elif blocks.The way to express a
computation like that is a chained condition
syntax:
Flowchart:
Example:
student mark system
traffic light system
compare two numbers
roots of quadratic equation
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
CSE I/II
Course Name with Code : 21GES08&Python Programming
Introduction :
Iteration statements or loop statements allow us to execute a block of statements as long as the
condition is true.
Loops statements are used when we need to run same code again and again, each time with a
different value
Prerequisite knowledge for Complete understanding and learning of Topic:
( Max. Four important topics)
values and types
precedence of operators
Boolean values and operators
Flowchart
ITERATION/CONTROL STATEMENTS/LOOPs:
state
while
for
break
continue
pass
State:
Transition from one process to another process under specified condition with in a time is
called state.
While loop:
• While loop statement in Python is used to repeatedly executes set of statement as long as a
given condition is true.
• In while loop, test expression is checked first. The body of the loop isentered only if the
test_expression is True.
• After one iteration, the test expression is checked again. Thisprocess continues until the
test_expression evaluates to False.
• In Python, the body of the while loop is determined through indentation.
• The statements inside the while starts with indentation and the first unindented line marks the
end.
Syntax:
For loop:
Flowchart:
for in range:
We can generate a sequence of numbers using range() function.
o range(10) will generate numbers from 0 to 9 (10 numbers).
In range function have to define the start, stop and step size as range(start,stop,step size). Step
Size defaults to 1 if not provided.
Syntax
Flowchart:
For in sequence
The for loop in Python is used to iterate over a sequence (list, tuple, string).
Iterating over a sequence is called traversal. Loop continues until we reach thelast element in the
sequence.
The body of for loop is separated from the rest of the code using indentation
Examples:
print nos divisible by 5 not by 10:
Program to print fibonacci series.
Program to find factors of a given number
check the given number is perfect number or not
check the no is prime or not
Print first n prime numbers
Program to print prime numbers in range
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
CSE I/II
Course Name with Code : 21GES08&Python Programming
example Output
for i in "welcome": w
if(i=="c"): e
break l
print(i)
CONTINUE
It terminates the current iteration and transfer the control to the next iteration in the loop.
Syntax:Continue
Flowchart
PASS
It is used when a statement is required syntactically but you don’t want any code to execute.
It is a null statement, nothing happens when it is executed.
Syntax:
Example Output
for i in “welcome”: w
if (i == “c”): e
pass l
print(i) c o m e
Difference between break and continue
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
CSE I/II
Course Name with Code : 21GES08&Python Programming
A function can be defined as the organized block of reusable code which can be called whenever required.
Python allows dividing a large program into the basic building blocks known as function. The function
contains the set of programming statements enclosed by {}. A function can be called multiple times to
provide reusability and modularity to the python program.
Function Defnition
In python, def keyword is used to define the function. The syntax to define a function in python is given
below.
Syntax
1. def my_function():
2. function-suite
3. return <expression>
The function block is started with the colon (:) and all the same level block statements remain at the same
indentation.A function can accept any number of parameters that must be the same in the definition and
function calling.
In python, a function must be defined before the function calling otherwise the python interpreter gives an
error. Once the function is defined, the function can be called from another function or from the python
prompt. Function is called by the function name followed by the parentheses.
A simple function that prints the message "Hello Word" is given below.
Example
1. def hello_world():
2. print("hello world")
Output
3. hello_world()
4. Uses of Functions in Python
o By using functions, user’s can avoid rewriting same logic/code again and again in a program.
o User’s can call python functions any number of times in a program and from any place in a
program.
o user can track a large python program easily when it is divided into multiple functions.
o Reusability is the main achievement of python function.
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
CSE I/II
Course Name with Code : 21GES08&Python Programming
Example 1:
def func (name):
print("Hi ",name);
func("Ram")
Output: Hi Ram
Example 2:
def hello():
print("hello world")
python()
def python():
print("testing main")
if __name__ == "__main__":
hello()
Output:
hello world
testing main
Video Content / Details of website for further learning (if any):
https:https://www.youtube.com/watch?v=fAw8pM_dQP4
Important Books/Journals for further learning including the page nos.:
Allen B. Downey,Think Python: How to Think Like a Computer Scientist,O’Reilly Publishers,
2016 Page no 3-4
Guido van Rossum and Fred L. Drake Jr, An Introduction to Python, Network Theory Ltd,
2011, Page no 83-85
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
L-12
LECTURE HANDOUTS
CSE I/II
Course Name with Code : 21GES08&Python Programming
Introduction :
Example 1:
Root=sqrt(25)
Example 2:
defadd():
a=10 b=20
c=a+b returnc
c=add() print(c)
i.Returnvalues
Example 2:
1. def simple_interest(p,n,r):
2. return (p*n*r)/100
3. print("Simple Interest: ",simple_interest(n=10,r=10,p=1900))
ii. Parameters
Parameters are the variables which used in the function definition. Parameters are inputs to functions.
Parameter receives the input from the function call.
Typesofparameters/Arguments:
1.Required/Positionalparameters
2.Keywordparameters
3.Defaultparameters
4. Variablelengthparameters
Example Output:
defstudent( name,roll): George98 print(name,roll)
student(“George”,98)
2. Keywordparameter:
Example:
def student(name,roll,mark):
print(name,roll,mark)
student(90,102,"bala")
Output: 90102bala
3. Default Parameter
Pythonallowsfunctionparametertohavedefault values;ifthefunctioniscalled
withouttheargument,theargumentgetsitsdefault valueinfunctiondefinition.
Example
defstudent( name,age=17):
print(name,age)
student(“Kumar”):
student(“Ajay”):
Output:
Kumar 17
Ajay 17
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
L-13
LECTURE HANDOUTS
CSE I/II
Course Name with Code : 21GES08&Python Programming
A variable is only available from inside the region it is created. This is called scope
The scope of a variable in python is that part of the code where it is visible.
Variables can be declared locally or globally
Variables defined inside a function or class, are local. Only the function or class can see the
variable
A variable at the top level of script or module is called as global variable
The scopes of the variables depend upon the location where the variable is being declared. The variable
declared in one part of the program may not be accessible to the other parts.
In python, the variables are defined with the two types of scopes.
1. Global variables
2. Local variables
The variable defined outside any function is known to have a global scope whereas the variable defined
inside a function is known to have a local scope.
Example 1:
def print_message():
message = "hello !! I am going to print a message."
print(message)
print_message()
Output:
Example 2:
def calculate(a):
sum = sum +arg
print("The sum is",sum)
sum=0
calculate(10)
print("Value of sum outside the function:",sum)
Output:
The sum is 10
Value of sum outside the function: 0
Video Content / Details of website for further learning (if any):
https: https://www.youtube.com/watch?v=NSbOtYzIQI0
Important Books/Journals for further learning including the page nos.:
Allen B. Downey,Think Python: How to Think Like a Computer Scientist,O’Reilly Publishers,
2016 Page no 3-4
Guido van Rossum and Fred L. Drake Jr, An Introduction to Python, Network Theory Ltd, 2011,
Page no 83-85
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
CSE I/II
Course Name with Code : 21GES08&Python Programming
A function can be called within another function. The ability to build functions by using other functions is
called Functioncomposition.
Example Output
defsum(a,b): entera:4
sum=a+b enterb:8
avg(sum) the avgis6.0
defavg(sum):
avg=sum/2returnavg
a=eval(input("entera:"))
b=eval(input("enterb:")) sum=sum(a,b)
avg=avg(sum)
print("theavgis",avg)
v. Recursion
When a function call itself is knows as recursion. Recursive function is called by some external code. If
the base condition is met then the program does something meaningful and exits. Otherwise, function
does some required processing and then calls itself to continue recursion.
Factorialofn Output
deffact(n): enterno. tofindfact:5
if(n==1): Factis120
return1
else:
returnn*fact(n-1)
n=eval(input("enterno. to find fact:"))
fact=fact(n)
print("Factis",fact)
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
CSE I/II
Course Name with Code : 21GES08&Python Programming
Introduction :
Strings are amongst the most popular types in Python.
Strings can be created simply by enclosing characters in quotes.
Python treats single quotes the same as double quotes.
Creating strings is as simple as assigning a value to a variable.
Characters in the strings can be accessed using index values
Prerequisite knowledge for Complete understanding and learning of Topic:
Strings
String declaration
Accessing strings
Detailed content of the Lecture:
Astringis asequenceofcharacters.
Example
my_string='Hello'
my_string="Hello"
my_string='''Hello'''
i. String slices
print('str=',str)
#firstcharacter
print('str[0]=',str[0])
#lastcharacter
print('str[-1]=',str[-1])
#slicing2ndto5thcharacter
print('str[1:5]=',str[1:5])
#slicing6thto2ndlastcharacter
print('str[5:-2]=',str[5:-2])
slice()Parameters
slice()mainlytakes threeparameters
start-startingintegerwheretheslicingoftheobjectstarts
stop-integeruntilwhichtheslicingtakes place.Theslicingstops atindexstop-1.
step-integervaluewhichdetermines theincrementbetweeneachindexforslicing. Ifasingleparameteris
passed,startandsteparesettoNone.
Returnvalue fromslice()
slice()returns asliceobjectusedtosliceasequenceinthegivenindices.
Example:
Pystring=”python”
# contains indices (0, 1, 2)
# i.e. P, y and t
sObject = slice(3)
print(pyString[sObject])
Output:
pyt
Example:
yh
Strings are immutable, which means you cannot change an existing string. The best is to create a new
string that is a variation on the original.
Example
greeting = "Hello, world!"
newGreeting = 'J' + greeting[1:]
print(newGreeting)
print(greeting)
Video Content / Details of website for further learning (if any):
https: www.youtube.com/watch?v=LTw5-5tx5wg
Important Books/Journals for further learning including the page nos.:
1. Allen B. Downey,Think Python: How to Think Like a Computer Scientist,O’Reilly Publishers,
2016 Page no 3-4
2. Guido van Rossum and Fred L. Drake Jr, An Introduction to Python, Network Theory Ltd,
2011, Page no 83-85
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
CSE I/II
Course Name with Code : 21GES08&Python Programming
Introduction :
Python has quite a few methods that string objects can call to perform frequently occurring
task(related to string).
The String class need to be imported to use the appropriate string functions
String module is collection of string constants, functions and class
String functions returns values
String classes can be used to define own formats for the strings
Prerequisite knowledge for Complete understanding and learning of Topic:
Strings
String declaration
Accessing strings
Detailed content of the Lecture:
Strings are also objects. Each string instance has its own attributes and methods. The most important
attribute of the string is the collection of characters. There are a wide variety of methods.
capitalize none Returns a string with first character capitalized, the rest lower
strip none Returns a string with the leading and trailing whitespace removed
replace old, new Replaces all occurrences of old substring with new
find item Returns the leftmost index where the substring item is found, or -1 if
not found
rfind item Returns the rightmost index where the substring item is found, or -1 if
not found
Example
ss = "Hello, World"
print(ss.upper())
tt = ss.lower()
print(tt)
Output
HELLO, WORLD
hello, world
Example
ss = " Hello, World "
els = ss.count("l")
print(els)
print("***" + ss.strip() + "***")
print("***" + ss.lstrip() + "***")
print("***" + ss.rstrip() + "***")
news = ss.replace("o", "***")
print(news)
Output
3
***Hello, World***
Hell***, W***rld
String Module
It’s a built-in module and we have to import it before using any of its constants and classes.
a. String Module Constants
import string
# string module constants
print(string.ascii_letters)
print(string.ascii_lowercase)
print(string.ascii_uppercase)
print(string.digits)
print(string.hexdigits)
print(string.whitespace) # ' \t\n\r\x0b\x0c'
print(string.punctuation)
Output
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789
0123456789abcdefABCDEF
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
Python string module contains a single utility function – capwords(s, sep=None). This function split the
specified string into words using str.split(). Then it capitalizes each word using str.capitalize() function.
Finally, it joins the capitalized words using str.join().
If the optional argument sep is not provided or None, then leading and trailing whitespaces are removed
and words are separated with single whitespace. If it’s provided then the separator is used to split and join
the words.
Example
Output
Welcome To Journaldev
Formatter
It behaves exactly same as str.format() function. This class becomes useful when own format string syntax
need to be defined.
Example
Output
Welcome to JournalDev
Welcome to JournalDev
d. Template
This class is used to create a string template for simpler string substitutions as described in PEP 292. It’s
useful in implementing internationalization (i18n) in an application where there is no need of complex
formatting rules.
Example
Output
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
L-17
LECTURE HANDOUTS
CSE I/II
Course Name with Code : 21GES08&Python Programming
Introduction :
List is a collection of items of different data types
Arrays are collection of items of same datat ypes
Arrays are imported from num py package
Elements in the list are accessed sequentially
Elements in the array can be using index positions
Prerequisite knowledge for Complete understanding and learning of Topic:
Arrays
Lists
Numpy Package
Detailed content of the Lecture:
a =[1,3.5,"Hello"]
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
L-18
LECTURE HANDOUTS
CSE I/II
Introduction :
List is a collection of items of different datatypes
Arrays are collection of items of same datatypes
Arrays are imported from numpy package
Elements in the list are accessed sequentially
Elements in the array can be using index positions
Prerequisite knowledge for Complete understanding and learning of Topic:
Arrays
Lists
Numpy Package
Detailed content of the Lecture: Examples
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
CSE I / II
Introduction :
List is an ordered sequence of items.
Values in the list are called elements/ items.
It can be written as a list of comma-separated items(values)between square brackets[].
Items in the lists can be of different data types.
Items in the list are indexed.
Operations on List
Indexing –index values are used to locate the elements in the list
Slicing- used to extract a portion of the list
Concatenation-joins two list
Repetition- contents of the lists are repeated specified number of times
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
L-20
LECTURE HANDOUTS
CSE I / II
Course Name with Code : 21GES08&Python Programming
Python provides methods that operate on lists. For example, append adds a new element to the end of a
list:
>>> print t
List methods are all void; they modify the list and return None
List Loop
The most common way to traverse the elements of a list is with a for loop. The syntax is the same as
for strings:
Example 1
Example 2
for i in range(len(numbers)):
numbers[i] = numbers[i] * 2
This loop traverses the list and updates each element . len returns the number of elements in the
list. range returns a list of indices from 0 to n−1, where n is the length of the list. Each time through
the loop i gets the index of the next element. The assignment statement in the body uses i to read the
old value of the element and to assign the new value.
for x in []:
print 'This never happens.'
Although a list can contain another list, the nested list still counts as a single element. The length of
this list is four:
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
L-21
LECTURE HANDOUTS
CSE I / II
Course Name with Code : 21GES08&Python Programming
Mutability
Lists are mutable. When the bracket operator appears on the left side of an assignment, it identifies the
element of the list that will be assigned.
>>> numbers = [17, 123]
>>> numbers[1] = 5
>>> print numbers
[17, 5]
The one-eth element of numbers, which used to be 123, is now 5.
Aliasing
If a refers to an object and if b = a, then both variables refer to the same object:
>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True
The association of a variable with an object is called a reference. In this example, there are two
references to the same object.
An object with more than one reference has more than one name, so we say that the object is aliased.
If the aliased object is mutable, changes made with one alias affect the other:
>>> b[0] = 17
>>> print a
[17, 2, 3]
Although this behavior can be useful, it is error-prone. In general, it is safer to avoid aliasing when you
are working with mutable objects.
For immutable objects like strings, aliasing is not as much of a problem. In this example:
a = 'banana'
b = 'banana'
It almost never makes a difference whether a and b refer to the same string or not.
List cloning
Slicing
Extend()
Copy()
List comprehension
Append()
List parameters
When you pass a list to a function, the function gets a reference to the list. If the function modifies a
list parameter, the caller sees the change. For example, delete_head removes the first element from a
list:
def delete_head(t):
del t[0]
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
L-22
LECTURE HANDOUTS
CSE I / II
Course Name with Code : 21GES08&Python Programming
Tuple Assignment
It is often useful to swap the values of two variables. For example, to swap a and b:
>>> temp = a
>>> a = b
>>> b = temp
>>> a, b = b, a
The left side is a tuple of variables; the right side is a tuple of expressions. Each value is assigned to its
respective variable. All the expressions on the right side are evaluated before any of the assignments.
The number of variables on the left and the number of values on the right have to be the same:
>>> a, b = 1, 2, 3
ValueError: too many values to unpack
More generally, the right side can be any kind of sequence (string, list or tuple). For example, to split
an email address into a user name and a domain, you could write:
>>> addr = '[email protected]'
>>> uname, domain = addr.split('@')
The return value from split is a list with two elements; the first element is assigned to uname, the
second to domain.
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
L-23
LECTURE HANDOUTS
CSE I / II
Course Name with Code : 21GES08&Python Programming
A function can only return one value, but if the value is a tuple, the effect is the same as returning
multiple values. For example, if you want to divide two integers and compute the quotient and
remainder, it is inefficient to compute x/y and then x%y. It is better to compute them both at the same
time.
The built-in function divmod takes two arguments and returns a tuple of two values, the quotient and
remainder. You can store the result as a tuple:
>>> t = divmod(7, 3)
>>> print t
(2, 1)
def min_max(t):
return min(t), max(t)
max and min are built-in functions that find the largest and smallest elements of a
sequence. min_max computes both and returns a tuple of two values.
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
L-24
LECTURE HANDOUTS
CSE I / II
Course Name with Code : 21GES08&Python Programming
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
L-25
LECTURE HANDOUTS
CSE I / II
Course Name with Code : 21GES08&Python Programming
The function dict creates a new dictionary with no items. Because dict is the name of a built-in
function, hence variable name can be avoided.
The squiggly-brackets, {}, represent an empty dictionary. To add items to the dictionary, you can use
square brackets:
This line creates an item that maps from the key ’one’ to the value 'uno'. If we print the dictionary
again, we see a key-value pair with a colon between the key and value:
This output format is also an input format. For example, you can create a new dictionary with three
items:
>>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
The order of the key-value pairs is not the same. In fact, if you type the same example on your
computer, you might get a different result. In general, the order of items in a dictionary is
unpredictable.
But that’s not a problem because the elements of a dictionary are never indexed with integer indices.
Instead, you use the keys to look up the corresponding values:
The len function works on dictionaries; it returns the number of key-value pairs:
>>> len(eng2sp)
3
The in operator works on dictionaries; it tells you whether something appears as a key in the dictionary
(appearing as a value is not good enough).
To see whether something appears as a value in a dictionary, you can use the method values, which
returns the values as a list, and then use the in operator:
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
L-26
LECTURE HANDOUTS
CSE I / II
Course Name with Code :21GES08&Python Programming
List Comprehension:
List comprehensions provide a concise way to apply operations on a list.
It creates a new list in which each element is the result of applying a given operation in a list.
It consists of brackets containing an expression followed by a “for” clause, then a list.
The list comprehension always returns a result list.
Syntax
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
L-27
LECTURE HANDOUTS
CSE I / II
Course Name with Code : 21GES08&Python Programming
List comprehension is an elegant way to define and create list in Python. These lists have often the
qualities of sets, but are not in all cases sets.
List comprehension is a complete substitute for the lambda function as well as the functions map(),
filter() and reduce().
Example 1:
Example 2:
Cross product of two sets
>>> colours = [ "red", "green", "yellow", "blue" ]
>>> things = [ "house", "car", "tree" ]
>>> coloured_things = [ (x,y) for x in colours for y in things ]
>>> print coloured_things
[('red', 'house'), ('red', 'car'), ('red', 'tree'), ('green', 'house'), ('green', 'car'), ('green', 'tree'), ('yellow',
'house'), ('yellow', 'car'), ('yellow', 'tree'), ('blue', 'house'), ('blue', 'car'), ('blue', 'tree')]
>>>
Generator comprehensions were introduced with Python 2.6. They are simply a generator expression
with a parenthesis - round brackets - around it. Otherwise, the syntax and the way of working is like list
comprehension, but a generator comprehension returns a generator instead of a list.
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
LECTURE HANDOUTS
CY L-28
CSE I/II
CCY
Course Name with Code : 21GES08&Python Programming
Binary files
Text files
File operation and file functions
A file is one, which will enable the user to read, write and store a group of related data, without
losing them even if the program is over. To perform these functions there are several basic file
operations as,
Naming a file - It is conventional, and convenient to name files in relation to the data stored.
Opening a file
Reading data from the file
Writing data to the file and
Closing a file
open()
Before going to do any file operation, the concerned file should be pened.
Syntax:
file_object=open(“file_name”,”file_mode”)
The open() function creates a file object. Finally it should be given, as to what purpose the file is
being used. It is also called the file mode.
file_mode Description
R Opens a file for reading purpose and this is the default file opening mode/
W Opens a file for writing purpose
A Opens a file for appending data to it.
r+ Existing file is opened to the beginning for both reading and writing
w+ Opens a file for reading and writing purpose. The file pointer is positioned at the
beginning of the file.
a+ Opens a file for reading and writing purpose. The file pointer is positioned at the end
of the file
Rb Opens a file for reading in binary format and this is the default file opening mode.
Ab Opens a file for appending data in binary format
Wb Opens a file for writing in binary format
rb+ Opens a file for reading and writing purpose in a binary format and the file pointer is
positioned at the beginning of the file
wb+ Opens a file for reading and writing purpose in a binary format. If the file already
exists it overwrites the file. If the file does not exist it will create a new one for both
reading and writing.
ab+ Opens a file for appending and reading data in binary format. Here the file pointer is
positioned at end if the file already exists. It will create a new one if the file does not
exists.
For example, a simple open() function call is as follows.
out=open(“abc.dat”,”w”)
close()
This function closes a file that was opened by a call open().
The general form of the function call to close() is
close(file-object)
(e.g.)
p1=open(“abc.dat”,”w”);
p2=open(“def.dat”,”r”);
———
———
close(p1); close(p2);
Video Content / Details of website for further learning (if any):
https:https://www.youtube.com/watch?v=ixEeeNjjOJ0
Important Books/Journals for further learning including the page nos.:
Allen B. Downey,Think Python: How to Think Like a Computer Scientist,O’Reilly Publishers,
2016 Page no .137-138.
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
CSE I/II
Course Name with Code : 21GES08&Python Programming
Introduction :
Retrieve the data from Files using read( )
Store the data to files using write ( ).
Basic of all input/output functions in file handling
Users can also create their own Files to store data and retrieve data.
File need to be opened before read or Write operation and finally closed.
Prerequisite knowledge for Complete understanding and learning of Topic:
Read File
Write File
Detailed content of the Lecture:
read()andwrite()
These two functions are considered as most basic of all input/output functions in file handling.
The write() function writes characters to a disk file that was previously opened for writing,through
the use of the function open().Similarly read() function is used to read characters from a file opened
in read mode by open().The general format for read() methodis:
file_object.read(no_of_bytes_to_be_read)
The write( ) method is used to write data to a file. This method requires only one parameter,
that must be a string and writes that string into a file. The general for write() method is:
file_object.write(string)
Text file –example:
F1=open(“abc.txt”,”x”)
out=open("abc.dat","w") str=
input("Enter string : ")
out.write(str)
out.close()
out=open("abc.dat","r")
str=out.read() print("File
contains") print(str)
out.close()
Output
Enter string : Welcome to Python file handling
File contains
Welcome to Python filehandling
Read Only Parts of the File
By default the read( ) method returns the whole text, but you can also specify how many
characters you want to return:
f = open("demofile.txt", "r")
print(f.read(5))
Read Lines
Example
f = open("demofile.txt", "r")
print(f.readline())
Write ( )
To write to an existing file, you must add a parameter to the open() function:
Example
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
CSE I/II
Course Name with Code : 21GES08&Python Programming
Command linearguments:
Input can be directly sent as an argument. When the program is running under command
prompt then inputs can be passed directly in the command and can be fetched using "sys" module.
Example program:
import sys
noargs=len(sys.argv)
print ("Number of arguments :%d" %noargs)
arguments= str(sys.argv)
print ("Arguments are : %s" %arguments)
Output
Example
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
CSE I/II
Course Name with Code : 21GES08&Python Programming
Command linearguments:
Input can be directly sent as an argument. When the program is running under command
prompt then inputs can be passed directly in the command and can be fetched using "sys" module.
Example program:
import sys
noargs=len(sys.argv)
print ("Number of arguments :%d" %noargs)
arguments= str(sys.argv)
print ("Arguments are : %s" %arguments)
Output
Example
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
CSE I/II
Course Name with Code : 21GES08&Python Programming
Errors
Types of Errors
Exception
Structure of exception
• Run timeerrors
if a program is free of syntax errors then it runs by the interpreter and the errors occurs during the
run time ofthe program due to logical mistake is called runtimeerrors.
Examples:
Trying to access a file that doesn’texists
Performing the operations like division byzero
Using an identifier which is not defined
(a,b)=(6,0)
try:# simple useoftry-except block for handling errors
g = a/b
exceptZeroDivisionError:
print("This is a DIVIDED BY ZERO error")
Exceptions:
An exception is an event, which occurs during the execution of the program that disrupts the normal flow
of the program.
When the program raises an exception, then python musthandle the exception otherwise it terminates
andquits
Exceptions handling in Python are very similar to Java. The code, which harbours the risk of
an exception, is embedded in a try block. But whereas in Java exceptions are caught by catch clauses, we
have statements introduced by an "except" keyword in Python. It's possible to create "custom-made"
exceptions: With the raise statement it's possible to force a specified exception to occur.
Let's look at a simple example. Assuming we want to ask the user to enter an integer number.
If we use a input(), the input will be a string, which we have to cast into an integer. If the input has not
been a valid integer, we will generate (raise) a ValueError. We show this in the following interactive
session:
>>> n = int(input("Please enter a number: "))
Please enter a number: 23.5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>ValueError: invalid literal for int() with base 10: '23.5'
try:
exceptexception1:
exceptexception2:
Example program:
try:
n=int(input(“enter a value”)) expert:
print(“you didn’t enter the integer input”)
else:
print(“value entered correctly and stored”)
output:
enter a value:5
value entered correctly and stored
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
CSE I/II
Course Name with Code : 21GES08&Python Programming
Introduction :
Disrupts the normal flow of the program.
Handling mechanism are try, except and else blocks.
Python must handle the exception otherwise it terminates and quits
The code that generates exception are given within try block
The exception are handling using exception block
try
exception
else
• An exception is an event, which occurs during the execution of the program that disrupts the
normal flow of the program.
• When the program raises an exception, then python must handle the exception otherwise it
terminates and quits
• try block – suspicious code (code that makes exception) placed here
• except block – code that handles the exception placed here and gets executed during exception
• else block – code that is to be executed if no exception is placed here for normal execution
try:
Example program:
try:
n=int(input(“enter a value”)) expert:
print(“you didn’t enter the integer input”) else:
print(“value entered correctly and stored”)
output:
enter a value:5
value entered correctly and stored
Video Content / Details of website for further learning (if any):
https://www.youtube.com/watch?v=Ia1i5EIGp9k
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
CSE I/II
Course Name with Code : 21GES08&Python Programming
Syntax:
– import module
• When import statement is encountered by the interpreter, the corresponding module is imported.
• import statement
– Example:
• import math
• Print(math.sqrt(25))
• It allows us to import specific attributes from a module into the current namespace.
• Example:
• Example:
– >>> print(sqrt(25))
def add(a,b):
print("result of addition is ",a+b)
return
def sub(a,b):
print("result of subtraction is ",a-b)
return
def mul(a,b):
print("result of multiplication is ",a*b)
return
Save the above program as cal.py. Now cal.py file can be imported as a module in another python source
file and its functions can be called from the new file as below
>>> import cal
>>> cal.add(3,4)
result of addition is 7
Locating modules
• When you import a module, the Python interpreter searches for the module in the following sequences:
– The current directory.
– If the module isn’t found, Python then searches each directory in the shell variable PYTHONPATH.
– If all else fails, Python checks the default path. On UNIX, this default path is normally
/usr/local/lib/python/.
• The module search path is stored in the system module sys as the sys.path variable.
• The sys.path variable contains the current directory, PYTHONPATH, and the installation-dependent
default.
Video Content / Details of website for further learning (if any):
https://www.youtube.com/watch?v=f26nAmfJggw
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
CSE I/II
Course Name with Code : 21GES08&Python Programming
– The __init__.py file is necessary because with this file, Python will know that this directory is a Python
package directory other than an ordinary directory.
def add(a,b):
print("result of addition is ",a+b)
return
def sub(a,b):
print("result of subtraction is ",a-b)
return
def mul(a,b):
print("result of multiplication is ",a*b)
return
__init__.py
from cal import add
from cal import sub
from cal import mul
from week import day1
from week import day2
from week import day3
from week import day4
from week import day5
from week import day6
from week import day7
Week.py
def day1():
print("sunday")
def day2():
print("monday")
def day3():
print("tuesday")
def day4():
print("wednesday")
def day5():
print("thursday")
def day6():
print("friday")
def day7():
print("saturday")
Main program – sample.py
import mypack
mypack.day1()
mypack.add(2,3)
Video Content / Details of website for further learning (if any):
https://www.youtube.com/watch?v=qmsTqQbcBNM
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
CSE I/II
Course Name with Code :21GES08&Python Programming
Introduction :
Packages are a way of structuring many packages and modules.
Packages help in a well-organized hierarchy of data set, making the directories and modules easy to
access.
Packages help us in storing other sub-packages and modules, so that it can be used by the user
when necessary.
__init__.py implies subpackages within package .
__init__.py file can be left blank or can be coded with the initialization code for the package
Prerequisite knowledge for Complete understanding and learning of Topic:
Objects
Classes
Modules
def bar():
print("Hello, function 'bar' from module 'a' calling")
def foo():
print("Hello, function 'foo' from module 'b' calling")
>>> from simple_package import a, b
>>> a.bar()
Hello, function 'bar' from module 'a' calling
>>> b.foo()
Hello, function 'foo' from module 'b' calling
>>>
>>> import simple_package
>>>
>>> simple_package.a.bar()
Hello, function 'bar' from module 'a' calling
>>>
>>> simple_package.b.foo()
Hello, function 'foo' from module 'b' calling
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
L-36
LECTURE HANDOUTS
CSE I/II
read()andwrite()
These two functions are considered as most basic of all input/output functions in file handling.
The write() function writes characters to a disk file that was previously opened for writing,through
the use of the function open().Similarly read() function is used to read characters from a file opened
in read mode by open().The general format for read() methodis:
file_object.read(no_of_bytes_to_be_read)
The write( ) method is used to write data to a file. This method requires only one parameter,
that must be a string and writes that string into a file. The general for write() method is:
file_object.write(string)
Text file –example:
F1=open(“abc.txt”,”x”)
out=open("abc.dat","w") str=
input("Enter string : ")
out.write(str)
out.close()
out=open("abc.dat","r")
str=out.read() print("File
contains") print(str)
out.close()
Output
Enter string : Welcome to Python file handling
File contains
Welcome to Python filehandling
Read Only Parts of the File
By default the read( ) method returns the whole text, but you can also specify how many
characters you want to return:
f = open("demofile.txt", "r")
print(f.read(5))
Read Lines
Example
f = open("demofile.txt", "r")
print(f.readline())
Write ( )
To write to an existing file, you must add a parameter to the open() function:
Example
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
LECTURE HANDOUTS
L-37
LECTURE HANDOUTS
CY
CY
CSE I/II
I/II
CCY
Course Name with Code : 21GES08&Python Programming
TensorFlow is an open source library for numerical computation and large-scale machine
learning.
TensorFlow bundles together a slew of machine learning and deep learning (aka neural
networking) models and algorithms and makes them useful by way of a common metaphor.
The goal of this article is to define and solve pratical use cases with TensorFlow. To do so, we will solve.
An optimization problem
And we will end solving the “Hello World” of Deep Learning classification projects with the MINST
Dataset.
PROGRAM:
import numpy as np
import tensorflow as tfx = tf.Variable(initial_value=tf.random_uniform([1], 34, 35),name=’x’)
y = tf.Variable(initial_value=tf.random_uniform([1], 0., 50.), name=’y’)# Loss function
s = tf.add(tf.add(632.0, tf.multiply(8.0, y)), tf.divide(2400.0, y), ‘s’)opt =
tf.train.GradientDescentOptimizer(0.05)
train = opt.minimize(s)sess = tf.Session()init = tf.initialize_all_variables()
sess.run(init)old_solution = 0
tolerance = 1e-4
for step in range(500):
sess.run(train)
solution = sess.run(y)
if np.abs(solution — old_solution) < tolerance:
print(“The solution is y = {}”.format(old_solution))
break
old_solution = solution
if step % 10 == 0:
print(step, “y = “ + str(old_solution), “s = “ + str(sess.run(s)))
TensorFlow :
TensorFlow Applications:
The APIs in languages other than Python are not yet covered by the API stability promises.
Python
JavaScript
C++
Java
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
CSE I/II
Course Name with Code : 21GES08&Python Programming
Introduction :
"A computational graph (or graph in short) is a series of TensorFlow operations arranged into a
graph of nodes".
Basically, it means a graph is just an arrangement of nodes that represent the operations in your
model.
Prerequisite knowledge for Complete understanding and learning of Topic:
Read File
Write File
Detailed content of the Lecture:
In the previous three guides, you ran TensorFlow eagerly. This means TensorFlow operations are
executed by Python, operation by operation, and returning results back to Python.
While eager execution has several unique advantages, graph execution enables portability outside
Python and tends to offer better performance.
Graph execution means that tensor computations are executed as a TensorFlow graph, sometimes
referred to as a tf.Graph or simply a "graph.
"Graphs are data structures that contain a set of tf.Operation objects, which represent units of
computation; and tf.Tensor objects, which represent the units of data that flow between
operations. They are defined in a tf.Graph context.
Since these graphs are data structures, they can be saved, run, and restored all without the original
Python code.This is what a TensorFlow graph representing a two-layer neural network looks like
when visualized in TensorBoard.
Taking advantage of graphs
Traffic Prediction, rumor and fake news detection, modeling disease spread, physics simulations,
and understanding why molecules smell.
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
L-39
LECTURE HANDOUTS
CSE I/II
Course Name with Code : 21GES08&Python Programming
# Later, launch the model, initialize the variables, do some work, save the
# variables to disk.
with tf.Session() as sess:
sess.run(init_op)
# Do some work with the model.
..
# Save the variables to disk.
save_path = saver.save(sess, "/tmp/model.ckpt")
print "Model saved in file: ", save_path
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
CSE I/II
Course Name with Code : 21GES08&Python Programming
GPU drivers
CUDA Toolkit: CUDA 9.0.
NCCL 2.2 (optional)
cuDNN SDK (7.2 or higher)
TensorRT for improved latency and throughput.
To install TensorFlow, it is important to have “Python” installed in your system. Python version 3.4+ is
considered the best to start with TensorFlow installation.
Consider the following steps to install TensorFlow in Windows operating system.
Step 1 − Verify the python version being installed.
Step 2 − A user can pick up any mechanism to install TensorFlow in the system. We recommend “pip”
and “Anaconda”. Pip is a command used for executing and installing modules in Python.
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
CSE I/II
Course Name with Code : 21GES08&Python Programming
backend module
backend module is used for keras backend operations. By default, keras runs on top of TensorFlow
backend. If you want, you can switch to other backends like Theano or CNTK. Defualt backend
configuration is defined inside your root directory under .keras/keras.json file.
Keras backend module can be imported using below code
>>> from keras import backend as k
If we are using default backend TensorFlow, then the below function returns TensorFlow based
information as specified below −
>>> k.backend()
'tensorflow'
>>> k.epsilon()
1e-07
>>> model.summary() Model: "sequential_10"
_________________________________________________________________
Layer (type) Output Shape Param
#================================================================
dense_13 (Dense) (None, 32) 288
_________________________________________________________________
dense_14 (Dense) (None, 64) 2112
_________________________________________________________________
dense_15 (Dense) (None, 8) 520
=================================================================
Total params: 2,920
Trainable params: 2,920
Non-trainable params: 0
_________________________________________________________________
>>>
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
CSE I/II
Course Name with Code : 21GES08&Python Programming
from keras.models import Sequential from keras.layers import Activation, Dense from keras import
initializers from keras import regularizers from keras import constraints
model = Sequential()
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
CSE I/II
Course Name with Code : 21GES08&Python Programming
Theano is an open source deep learning library that allows you to evaluate multi-dimensional arrays
effectively. We can easily install using the below command −
pip install theano
By default, keras uses TensorFlow backend. If you want to change backend configuration from
TensorFlow to Theano, just change the backend = theano in keras.json file. It is described below −
keras.json
{
"image_data_format": "channels_last",
"epsilon": 1e-07,
"floatx": "float32",
"backend": "theano"
}
Now save your file, restart your terminal and start keras, your backend will be changed.
>>> import keras as k
using theano backend.
number of input units for mode = fan_in
number of out units for mode = fan_out
average number of input and output units for mode = fan_avg
Similarly, it finds the limit for uniform distribution using below formula and then find the weights using
uniform distribution,
limit = sqrt(3 * scale / n)
placeholder
It is used instantiates a placeholder tensor. Simple placeholder to hold 3-D shape is shown below −
>>> data = k.placeholder(shape = (1,3,3))
>>> data
<tf.Tensor 'Placeholder_9:0' shape = (1, 3, 3) dtype = float32>
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
LECTURE HANDOUTS L-44
CSE I/II
Course Name with Code : 21GES08&Python Programming
model = Sequential()
model.add(MyCustomLayer(32, input_shape = (16,)))
model.add(Dense(8, activation = 'softmax')) model.summary()
Here,
Our MyCustomLayer is added to the model using 32 units and (16,) as input shape
Running the application will print the model summary as below −
Model: "sequential_1"
_________________________________________________________________
Layer (type) Output Shape Param
#================================================================
my_custom_layer_1 (MyCustomL (None, 32) 512
_________________________________________________________________
dense_1 (Dense) (None, 8) 264
=================================================================
Total params: 776
Trainable params: 776
Non-trainable params: 0
_________________________________________________________________
Course Faculty
Verified by HOD
MUTHAYAMMAL ENGINEERING COLLEGE
(An Autonomous Institution)
(Approved by AICTE, New Delhi, Accredited by NAAC & Affiliated to Anna University)
Rasipuram - 637 408, Namakkal Dist., Tamil Nadu
CSE I/II
Course Name with Code : 21GES08&Python Programming
line_length: Total length of printed lines (e.g. set this to adapt the display to different terminal
window sizes).
positions: Relative or absolute positions of log elements in each line. If not provided, defaults
to [.33, .55, .67, 1.].
print_fn: Print function to use. Defaults to print. It will be called on each line of the summary. You
can set it to a custom function in order to capture the string summary.
expand_nested: Whether to expand the nested models. If not provided, defaults to False.
show_trainable: Whether to show if a layer is trainable. If not provided, defaults to False.
If name and index are both provided, index will take precedence. Indices are based on order of horizontal
graph traversal (bottom-up).
Arguments
Course Faculty
Verified by HOD