Module1 Vtu Python Notes
Module1 Vtu Python Notes
Module1 Vtu Python Notes
PROGRAMMING (PAP)
Sub Code : 15CS664
IA Marks : 20
Hours per Week : 3 Hours
Exam Marks : 80
Lecture Hours : 40
Exam Hours : 3 Hours
Credit : 3
Assignment : 3
Quiz : 3
Seminar :01
Dr THYAGU
SYLLABUS
Module – 1 : Why should you learn to write programs, Variables, expressions and
statements, Conditional execution, Functions –8 Hours
Module – 2 : Iteration, Strings, Files –8 Hours
Module – 3 : Lists, Dictionaries, Tuples, Regular Expressions–8 Hours
Module – 4 : Classes and objects, Classes and functions, Classes and methods–8 Hours
Module – 5 : Networked programs, Using Web Services, Using databases and SQL–8 Hours
Dr THYAGU
Python Introduction
Dr THYAGU
Features of Python
• Simple
• Easy to Learn
• Free and Open Source
• High-level Language
• Python is a Beginner's Language
• Portable
• Interactive
• Interpreted
• Object Oriented
• Extensible
• Embeddable
• Extensive Libraries
• Databases
• GUI Programming
• Scalable
Dr THYAGU
Programming Editors
Dr THYAGU
Some Python Packages/Libraries
• Numpy • Tornado • Ansible
• Scipy • Web2py • Salt
• Pandas • Json • OpenStack
• Matplotlib • tKinter • Keras
• Seaborn • OpenCV • Tensor Flow
• Bokeh • PyGObject • Theano
• Scikit Learn • PyQt • nltk
• Pygames • wxPython • Spacy
• dJango • Kivy • TextBlog
• Flask • Buildozer • ScikitLearn
• Bottle • Buildbot • Pattern
• Pyramid • Trac • SQLalchemy
• PyBrain • Roundup • pyMySql
• PyMongo •
Dr THYAGU
Different Modes
Dr THYAGU
Module 1
Dr THYAGU
Why should you learn to Write
programs
Dr THYAGU
Creativity and Motivation
Dr THYAGU
Question
Dr THYAGU
Computer hardware architecture
Dr THYAGU
Different Parts of Hardware architecture and
their High Level Definitions:
• The Central Processing Unit (or CPU) is the part of the computer that is built to be
obsessed with “what is next?” If your computer is rated at 3.0 Gigahertz, it means that
the CPU will ask “What next?” three billion times per second. You are going to have to
learn how to talk fast to keep up with the CPU.
• The Main Memory is used to store information that the CPU needs in a hurry. The main
memory is nearly as fast as the CPU. But the information stored in the main memory
vanishes when the computer is turned off.
• The Secondary Memory is also used to store information, but it is much slower than the
main memory. The advantage of the secondary memory is that it can store information
even when there is no power to the computer. Examples of secondary memory are disk
drives or flash memory (typically found in USB sticks and portable music players).
• The Input and Output Devices are simply our screen, keyboard, mouse, microphone,
speaker, touchpad, etc. They are all of the ways we interact with the computer.
• These days, most computers also have a Network Connection to retrieve information
over a network. We can think of the network as a very slow place to store and retrieve
data that might not always be “up”. So in a sense, the network is a slower and at times
unreliable form of Secondary Memory.
Dr THYAGU
Job of Programmer
Dr THYAGU
What is Program ?
Dr THYAGU
What is Programming ?
Dr THYAGU
Who is Programmer?
Dr THYAGU
Two skills to be a programmer
• First, you need to know the programming language (Python)
- you need to know the vocabulary and the grammar. You
need to be able to spell the words in this new language
properly and know how to construct well-formed “sentences”
in this new language.
• Second, you need to “tell a story”. In writing a story, you
combine words and sentences to convey an idea to the reader.
There is a skill and art in constructing the story, and skill in
story writing is improved by doing some writing and getting
some feedback. In programming, our program is the “story”
and the problem you are trying to solve is the “idea”.
Dr THYAGU
Words
•Word is a fundamental unit of python programming language . Word may be reserved or
unreserved words. The Python vocabulary is called the “reserved words”. These are words
that have very special meaning to Python.
•Variables are the words made by the programmer as per need based.
Keywords
False class finally is return
None continue for lambda try
Dr THYAGU
Sentence
Dr THYAGU
Conversing with Python
Dr THYAGU
What is High Level Language ?
Dr THYAGU
What is Machine Language ?
Dr THYAGU
Portability
Dr THYAGU
Programming language translators
Dr THYAGU
1. Interpreter
• An interpreter reads the source code of the program as written by the
programmer, parses the source code, and interprets the instructions on the fly.
• Python is an interpreter and when we are running Python interactively, we can
type a line of Python (a sentence) and Python processes it immediately and is
ready for us to type another line of Python.
Example :
>>> x = 6
>>> print(x)
6
>>> y = x * 7
>>> print(y)
42
>>>
Dr THYAGU
2.Compiler
• It translates a program written in a high-level language into a low-
level language all at once, in preparation for later execution.
• A compiler needs to be handed the entire program in a file, and
then it runs a process to translate the high-level source code into
machine language and then the compiler puts the resulting
machine language into a file for later execution.
• In Windows, the executable machine code for Python itself is
likely in a file with a name like:
• C:\Python35\python.exe
Dr THYAGU
Exercise
Dr THYAGU
Execute the following program
name = input('Enter file:')
handle = open(name,'r')
counts = dict()
for line in handle:
words = line.split()
for word in words:
counts[word] = counts.get(word, 0) + 1
bigcount = None
bigword = None
for word, count in list(counts.items()):
if bigcount is None or count > bigcount:
bigword = word
bigcount = count
print(bigword, bigcount)
Dr THYAGU
What are the building blocks of
programs?
1. INPUT : Get data from the “outside world”. This might be reading data from a file,
or even some kind of sensor like a microphone or GPS. In our initial programs, our
input will come from the user typing data on the keyboard.
2. OUTPUT : Display the results of the program on a screen or store them in a file or
perhaps write them to a device like a speaker to play music or speak text.
3. SEQUENTIAL EXECUTION : Perform statements one after another in the order they
are encountered in the script.
4. CONDITIONAL EXECUTION : Check for certain conditions and then execute or skip
a sequence of statements.
5. REPEATED EXECUTION : Perform some set of statements repeatedly, usually with
some variation.
6. REUSE : Write a set of instructions once and give them a name and then reuse
those instructions as needed throughout your program.
Dr THYAGU
Three general types of errors:
1. Syntax errors : These are the first errors you will make and the easiest to
fix. A syntax error means that you have violated the “grammar” rules of
Python.
2. Logic errors: A logic error is when your program has good syntax but
there is a mistake in the order of the statements or perhaps a mistake in
how the statements relate to one another.
3. Semantic errors: A semantic error is when your description of the steps
to take is syntactically perfect and in the right order, but there is simply a
mistake in the program. The program is perfectly correct but it does not
do what you intended for it to do.
Dr THYAGU
M1.2 Variables, Expressions and
Statements
Dr THYAGU
What are Values and types?
Dr THYAGU
What are the different Data Types?
1. Numbers: Number data types store numeric values. Number objects
are created when you assign a value to them.
2. Strings: Strings in Python are identified as a contiguous set of
characters represented in the quotation marks. Python allows either
pair of single or double quotes.
3. Lists: Lists are the most versatile of Python's compound data types. A
list contains items separated by commas and enclosed within square
brackets ([ ]).
4. Tuples: A tuple is another sequence data type that is similar to the
list. A tuple consists of a number of values separated by commas.
Unlike lists, however, tuples are enclosed within parenthesis.
5. Dictionary: Python's dictionaries are kind of hash-table type. They
work like associative arrays or hashes found in Perl and consist of key-
value pairs. A dictionary key can be almost any Python type, but are
usually numbers or strings. Values, on the other hand, can be any
arbitrary Python object. Dictionaries are enclosed within curly braces.
Dr THYAGU
Numbers
Dr THYAGU
To check the number type
• type(-75)
• type(5.0)
• type(12345678901)
• type(-1+2j)
• complex(2,3)
• type("This is a string")
• type( [1,3,4,1,6] )
• type(True)
• type(False)
Dr THYAGU
What are Variables ?
Dr THYAGU
Variables
• A variable is a name that refers to a value.
Example : x, si , area_of _Circle ,etc
• To know the type of the variable one can use type() function . Ex: type(p)
Dr THYAGU
Statements
• A statement is a unit of code that the Python
interpreter can execute. Each statement is a set
of words ( reserved/unreserved and special
symbols ).
• Types of statements :
– Expression statement Ex: a + 2
– Assignment statement Ex: a = 1
• Print statement , if statement, for statement,
while statement etc
Dr THYAGU
•
Multi-Line Statement
In Python, end of a statement is marked by a newline character. But we can make a
statement extend over multiple lines with the line continuation character (\). For
example:
a=1+2+3+\
4+5+6+\
7+8+9
This is explicit line continuation. In Python, line continuation is implied inside parentheses ( ),
brackets [ ] and braces { }. For instance, we can implement the above multi-line statement as
a = (1 + 2 + 3 +
4+5+6+
7 + 8 + 9)
Here, the surrounding parentheses ( ) do the line continuation implicitly. Same is the case
with [ ] and { }. For example:
colors = ['red',
'blue',
'green']
We could also put multiple statements in a single line using semicolons, as follows
a = 1; b = 2; c = 3
Dr THYAGU
Operators and operands
• Operators are special symbols that represent computations
like addition and multiplication. The values the operator is
applied to are called operands.
Dr THYAGU
Expressions
• Example :
17 , x , x + 17 , 1 + 1 , x**2, x**2 + y **2
Dr THYAGU
Order of operations
• // is Quotient operator .
Example : 7 // 3 yields 2
Example : r = 7 % 3 yields 1
Dr THYAGU
String operations with +
Dr THYAGU
Comments
• Adding notes to the programs to explain in natural
language about what the program is doing are called
comments, and in Python they start with the # symbol:
• Example 1:
# compute the percentage of the hour
percentage = (minute * 100) / 60
• Example 2:
percentage = (minute * 100) / 60 # percentage of an hour
• Example 3: (This comment is redundant with the code and useless:)
v=5 # assign 5 to v
• Example 4: (This comment contains useful information )
• v=5 # velocity in meters/second.
Dr THYAGU
Asking the user for input
In order to get the input from the user
through the keyboard Python provides a built-
in function called input. When this function is
called, the program stops and waits for the
user to type something. When the user
presses Return or Enter, the program resumes
and input returns what the user typed as a
string.
Dr THYAGU
Example
Dr THYAGU
Python Program to Add Two
Numbers
• # This program adds two numbers
• num1 = 1.5
• num2 = 6.3
• # Add two numbers
• sum = float(num1) + float(num2)
• # Display the sum
• print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
Dr THYAGU
Dr THYAGU
Add Two Numbers Provided by
The User
• # Store input numbers
• num1 = input('Enter first number: ')
• num2 = input('Enter second number: ')
• # Add two numbers
• sum = float(num1) + float(num2)
• # Display the sum
• print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
Dr THYAGU
Dr THYAGU
Exercise
• Assume that we execute the following assignment
statements:
width = 17 height = 12.0
For each of the following expressions, write the value of the expression and the type
(of the value of the expression).
1. width//2
2. width/2.0
3. height/3
4. 1 + 2 * 5
Dr THYAGU
Exercise
1. Write a program that uses input to prompt a user for their name and
then welcomes them.
2. Write a program to prompt the user for hours and rate per hour to
compute gross pay.
3. Write a program to read the following input from user and display
Name :
USN :
Roll NO:
Mobile No:
E-Mail id :
Percentage of Marks :
Dr THYAGU
Choosing mnemonic/ meaningful variable
a = 35.0
names
b = 12.50
c=a*b
print(c)
hours = 35.0
rate = 12.50
pay = hours * rate
print(pay)
x1q3z9ahd = 35.0
x1q3z9afd = 12.50
x1q3p9afd = x1q3z9ahd * x1q3z9afd
print(x1q3p9afd)
Dr THYAGU
Examples
Dr THYAGU
M1.3 Conditional Execution
Dr THYAGU
Explain the following with
examples
• Boolean Expression
• Logical Operators
• Conditional Execution : if
• Alternative Execution: if else
• Chained Conditionals : if elif else
• Nested Conditionals : if else if else
• Catching exception using try and except
• Short circuit evaluation of logical circuits
Dr THYAGU
Boolean Expression
• A boolean expression is an expression that is
either true or false.
• Example :
>>> 5 == 5
True
>>> 5 == 6
False
Dr THYAGU
The == operator is one of the comparison operators;
the others are:
• x != y # x is not equal to y
• x > y # x is greater than y
• x < y # x is less than y
• x >= y # x is greater than or equal to y
• x <= y # x is less than or equal to y
• x is y # x is the same as y
• x is not y # x is not the same as y
Dr THYAGU
Special operators
Dr THYAGU
Identity operators
• is and is not are the identity operators in Python.
• They are used to check if two values (or variables) are located on
the same part of the memory.
• Two variables that are equal does not imply that they are identical.
Dr THYAGU
Example #4: Identity operators
in Python
• x1 = 5
• y1 = 5
• x2 = 'Hello‘
• y2 = 'Hello‘
• x3 = [1,2,3]
• y3 = [1,2,3]
• print(x1 is not y1) # Output: False
• print(x2 is y2) # Output: True
• print(x3 is y3) # Output: False
Dr THYAGU
Membership operators
• in and not in are the membership operators in Python.
• They are used to test whether a value or variable is found
in a sequence (string, list, tuple, set and dictionary).
• In a dictionary we can only test for presence of key, not the
value.
Operator Meaning Example
True if value/variable is found in the
in 5 in x
sequence
True if value/variable is not found
not in 5 not in x
in the sequence
Dr THYAGU
Example #5: Membership
operators in Python
• x = 'Hello world‘
• y = {1:'a',2:'b'}
• print('H' in x) # Output: True
• print('hello' not in x) # Output: True
• print(1 in y) # Output: True
• print('a' in y) # Output: False
Dr THYAGU
Logical operators
Dr THYAGU
Example #3: Logical Operators
in Python
• x = True
• y = False
• print('x and y is', x and y) # Output: x and y is False
• print('x or y is', x or y) # Output: x or y is True
• print('not x is', not x) # Output: not x is False
Dr THYAGU
Summary 2
• Why one Should write Program?
• Program , Programming , Hardware Architecture of Computer, Interpreter and
Compiler.
• Building Blocks of Program
• Types of Errors
• Variables , Expressions and Statements , order of operations
• Reading input from the user through keyboard
• Special Operators ( identity (is , is not) and membership (in , not in) operators)
• Boolean Expressions , Logical Operators
• Conditional Executions (Conditional Execution : if , Alternative Execution: if
else Chained Conditionals : if elif else , Nested Conditionals : if else if else
Catching exception using try and except and Short circuit evaluation of logical
circuits )
Dr THYAGU
Conditional execution
• The simplest form is the
conditional if statement:
if x > 0 :
print('x is positive')
• The boolean expression after
the if statement is called the
condition. We end the
• if statement with a colon
character (:) and the line(s)
after the if statement are
indented.
Dr THYAGU
Alternative execution
• A second form of the if
statement is alternative
execution, in which there
are two possibilities and
the condition determines
which one gets executed.
The syntax looks like this:
if x%2 == 0 :
print('x is even')
else :
print('x is odd')
Dr THYAGU
Exercise
1. Write a program to prompt the user for hours
and rate per hour to compute gross pay. Also to
give the employee 1.5 times the hourly rate for
hours worked above 40 hours.
Dr THYAGU
Chained conditionals
Sometimes there are more than two
possibilities and we need more than two
branches. One way to express a computation
like that is a chained conditional:
if x < y:
print('x is less than y')
elif x > y:
print('x is greater than y')
else:
print('x and y are equal')
Note : elif is an abbreviation of “else if.” Again, exactly
one branch will be executed.
Dr THYAGU
Note
Dr THYAGU
Example
if choice == 'a':
print('Bad guess')
elif choice == 'b':
print('Good guess')
elif choice == 'c':
print('Close, but not correct')
Dr THYAGU
Exercise
Dr THYAGU
Nested conditionals
• One condition can also be
nested within another. We
could have written the
three-branch example like
this:
if x == y:
print('x and y are equal')
else:
if x < y:
print('x is less than y')
else:
print('x is greater than y')
Dr THYAGU
Note
• Logical operators often provide a way to simplify nested conditional
statements. For example, we can rewrite the following code using a
single conditional:
if 0 < x:
if x < 10:
print('x is a positive single-digit number.')
Dr THYAGU
Catching exceptions using try
and except
• There is a conditional execution structure built
into Python to handle these types of expected
and unexpected errors called “try / except”.
• The idea of try and except is that you know
that some sequence of instruction(s) may
have a problem and you want to add some
statements to be executed if an error occurs.
• These extra statements (the except block) are
ignored if there is no error.
Dr THYAGU
Example
Dr THYAGU
Short-circuit evaluation of
logical expressions
• x=6
• y=0
• x >= 2 and y != 0 and (x/y) > 2
• x=6
• y=0
• x >= 2 and (x/y) > 2 and y != 0
Dr THYAGU
Exercise
1. Write a program to prompt the user for hours
and rate per hour to compute gross pay. Also to
give the employee 1.5 times the hourly rate for
hours worked above 40 hours.
2. Rewrite the above program using try and except
so that your program handles non-numeric
input gracefully by printing a message and
exiting the program.
Dr THYAGU
M1.4 Functions
Dr THYAGU
Explain the following with example
1. Functions
2. Function Call
3. Built in Function
4. Type Conversion Functions
5. Random Numbers
6. Math Functions
7. Adding new Functions
8. Defining and using the new functions
9. Flow of execution
10. Parameter and Arguments
11. Fruitful and void Functions
12. Advantages of Functions
Dr THYAGU
Functions
• In the context of programming, a function is a named sequence of
statements that performs a computation to do particular task.
• Syntax for Defining a function :
fun_name(parameter list)
Dr THYAGU
Parameters and arguments
• Parameters are temporary variable names within functions. The argument can be
thought of as the value that is assigned to that temporary variable.
• Function Definition :
def cube(number):
return number**3
• 'number' here is the parameter for the function 'cube'. This means that anywhere we
see 'number' within the function will act as a placeholder until number is passed an
argument.
• Function Call :
– cube(3)
• Here 3 is the argument. The parameters are used as place holder or arguments.
• Parameters are used in function definition and arguments are used in function call.
Dr THYAGU
Working of function
Dr THYAGU
Example 1:
Output
# Defining a Function Rajashree
def print_Address(): D.NO 07
print(“Rajashree") Ajit Nagara
print(‘ D.NO 07 ') Ujire -574240
print (‘ Ajit Nagara’)
print(‘Ujire -574240’)
# Function Call
print_Address()
Dr THYAGU
Example 2 :
def print_lyrics():
print(“First Line of a Song") Output
print(‘Second Line of a Song') First Line of a Song
Second Line of a Song
def repeat_lyrics(): First Line of a Song
print_lyrics() Second Line of a Song
print_lyrics()
repeat_lyrics()
Dr THYAGU
Example 3
Output :
Eric, the half a bee.
Eric, the half a bee.
Dr THYAGU
Types of Functions based on return
• void Function
• fruitful Function
Dr THYAGU
void function does not return a value
def print_name():
print(“RAHUL MODI”);
Dr THYAGU
Fruitful functions returns a value
x = addtwo(3, 5)
print(x)
Dr THYAGU
Example for Fruitful Functions
• radians =30
• x = math.cos(radians)
• math.sqrt(5)
2.23606797749979
• golden = (math.sqrt(5) + 1) / 2
Dr THYAGU
Why functions?
• Function gives you an opportunity to name a group of
statements,
• Which makes your program easier to read, understand,
and debug.
• Functions can make a program smaller by eliminating
repetitive code.
• Dividing a long program into functions allows to debug
the parts one at a time and then assemble them into a
working whole.
• Well-designed functions are often useful for many
programs. Once you write and debug one, you can
reuse it
Dr THYAGU
Categories of Functions
Dr THYAGU
1.Built in Functions
• The Python interpreter has a number of functions that are always
available for use. These functions are called built-in functions. For
example, print() function prints the given object to the standard output
device (screen) or to the text stream file.
Dr THYAGU
Built-in functions
• Python provides a number of important built-in functions that we can use
without needing to provide the function definition. The creators of
Python wrote a set of functions to solve common problems and included
them in Python for us to use.
• max('Hello world')
w
• min('Hello world')
‘‘
• len('Hello world')
11
Dr THYAGU
2.User Defined Function
• Functions that we define ourselves to do certain specific task are referred
as user-defined functions. Functions that readily come with Python are
called built-in functions. If we use functions written by others in the form
of library, it can be termed as library functions. All the other functions that
we write on our own fall under user-defined functions. So, our user-
defined function could be a library function to someone else.
• Example of a user-defined function
def add_numbers(x,y):
sum = x + y
return sum
num1 = 5
num2 = 6
print("The sum is", add_numbers(num1, num2))
Dr THYAGU
Math Functions and constants
Function name Description Constant Description
abs(value) absolute value e 2.7182818...
ceil(value) rounds up pi 3.1415926...
cos(value) cosine, in radians
floor(value) rounds down
log10(value) logarithm, base 10
max(value1, value2) larger of two values
min(value1, value2) smaller of two values
round(value) nearest whole number
sin(value) sine, in radians
sqrt(value) square root
Dr THYAGU
Math functions example
• import math
• print(math)
• ratio = signal_power / noise_power
• decibels = 10 * math.log10(ratio)
• radians = 0.7
• height = math.sin(radians)
• radians = degrees / 360.0 * 2 * math.pi
• math.sin(radians)
• math.sqrt(2) / 2.0
Dr THYAGU
Type conversion functions: used to convert one form to other
Dr THYAGU
Random numbers
Dr THYAGU
Output
0.14350103211784326
0.11775378050385343
0.593629658284786
0.8866024608748476
0.6316710639256297
0.871088071436763
0.05665609859315035
0.5586754374930559
0.6952228377929273
0.009905091780000652
Dr THYAGU
Other randoms
• random.randint(5, 10)
Output : Any random number between 5 to 10
• t = [1, 2, 3]
random.choice(t)
Output : Any random number between 1 to 3
Dr THYAGU
Exercise
Dr THYAGU
Glossary
• algorithm : A general process for solving a category of problems.
• Argument: A value provided to a function when the function is called. This value is
assigned to the corresponding parameter in the function.
• body :The sequence of statements inside a function definition.
• composition :Using an expression as part of a larger expression, or a statement as part of
a larger statement.
• Deterministic: Pertaining to a program that does the same thing each time it runs, given
the same inputs.
• dot notation: The syntax for calling a function in another module by specifying the
module name followed by a dot (period) and the function name.
• flow of execution :The order in which statements are executed during a program run.
• fruitful function: A function that returns a value.
• function :A named sequence of statements that performs some useful operation.
Functions may or may not take arguments and may or may not produce a result.
Dr THYAGU
Glossary
• function call A statement that executes a function. It consists of the function name
followed by an argument list.
• function object A value created by a function definition. The name of the function
is a variable that refers to a function object.
• header The first line of a function definition.
• import statement A statement that reads a module file and creates a module
object.
• module object A value created by an import statement that provides access to the
data and code defined in a module.
• parameter A name used inside a function to refer to the value passed as an
argument.
• pseudorandom Pertaining to a sequence of numbers that appear to be random,
but are generated by a deterministic program.
• return value The result of a function. If a function call is used as an expression, the
return value is the value of the expression.
• void function A function that does not return a value.
Dr THYAGU
Exercise 4: What is the purpose of the “def” keyword in
Python?
Dr THYAGU
What will the following
Python program print out?
def fred():
print("Zap")
def jane():
print("ABC")
jane()
fred()
jane()
Dr THYAGU
End of Modul1
Dr THYAGU