Python Module 01 Notestd
Python Module 01 Notestd
Module 01
Chapter 01
WHY SHOULD YOU LEARN TO WRITE PROGRAMS?
Programs are generally written to solve the real-time arithmetic/logical problems. Nowadays,
computational devices like personal computer, laptop, and cell phones are embedded with operating
system, memory and processing unit. Using such devices one can write a program in the language
(which a computer can understand) of one’s choice to solve various types of problems. Humans are
tend to get bored by doing computational tasks multiple times. Hence, the computer can act as a
personal assistant for people for doing their job!! To make a computer to solve the required problem,
one has to feed the proper program to it. Hence, one should know how to write a program!!
There are many programming languages that suit several situations. The programmer must be able to
choose the suitable programming language for solving the required problem based on the factors like
computational ability of the device, data structures that are supported in the language, complexity
involved in implementing the algorithm in that language etc.
Here is an example showing that how the computer is always ready to accept the task from the user.
1
Python Application Programming – 18EC646
• Central Processing Unit (CPU): It performs basic arithmetic, logical, control and I/O
operations specified by the program instructions. CPU will perform the given tasks with a
tremendous speed. Hence, the good programmer has to keep the CPU busy by providing
enough tasks to it.
• Main Memory: It is the storage area to which the CPU has a direct access. Usually, the
programs stored in the secondary storage are brought into main memory before the execution.
The processor (CPU) will pick a job from the main memory and performs the tasks.
Usually, information stored in the main memory will be vanished when the computer is
turned-off.
• Secondary Memory: The secondary memory is the permanent storage of computer. Usually,
the size of secondary memory will be considerably larger than that of main memory. Hard
disk, USB drive etc can be considered as secondary memory storage.
• I/O Devices: These are the medium of communication between the user and the computer.
Keyboard, mouse, monitor, printer etc. are the examples of I/O devices.
• Network Connection: Nowadays, most of the computers are connected to network and hence
they can communicate with other computers in a network. Retrieving the information from
other computers via network will be slower compared to accessing the secondary memory.
Moreover, network is not reliable always due to problem in connection.
2
Python Application Programming – 18EC646
The programmer has to use above resources sensibly to solve the problem. Usually, a programmer
will be communicating with CPU by telling it ‘what to do next’. The usage of main memory,
secondary memory, I/O devices also can be controlled by the programmer.
To communicate with the CPU for solving a specific problem, one has to write a set of instructions.
Such a set of instructions is called as a program.
A programmer must have skills to look at the data/information available about a problem, analyze it
and then to build a program to solve the problem. The skills to be possessed by a good programmer
includes –
• Thorough knowledge of programming language: One needs to know the vocabulary and
grammar (technically known as syntax) of the programming language. This will help in
constructing proper instructions in the program.
• Skill of implementing an idea: A programmer should be like a ‘story teller’. That is, he must
be capable of conveying something effectively. He/she must be able to solve the problem
by designing suitable algorithm and implementing it. And, the program must provide
appropriate output as expected.
Thus, the art of programming requires the knowledge about the problem’s requirement and the
strength/weakness of the programming language chosen for the implementation. It is always
advisable to choose appropriate programming language that can cater the complexity of the problem
to be solved.
Every programming language has its own constructs to form syntax of the language. Basic constructs
of a programming language includes set of characters and keywords that it supports. The keywords
have special meaning in any language and they are intended for doing specific task. Python has a finite
set of keywords as given in Table 1.1.
A programmer may use variables to store the values in a program. Unlike many other programming
languages, a variable in Python need not be declared before its use.
3
Python Application Programming – 18EC646
After understanding the basics of few editors of Python, let us start our communication with Python,
by saying Hello World. The Python uses print() function for displaying the contents. Consider the
following code –
Once we are done with the program, we can close or terminate Python by giving quit() command
as shown –
4
Python Application Programming – 18EC646
A compiler translates the source code of high-level programming language into machine level
language. For this purpose, the source code must be a complete program stored in a file (with
extension, say, .java, .c, .cpp etc). The compiler generates executable files (usually with extensions
.exe, .dll etc) that are in machine language. Later, these executable files are executed to give the output
of the program.
On the other hand, interpreter performs the instructions directly, without requiring them to be pre-
compiled. Interpreter parses (syntactic analysis) the source code ant interprets it immediately. Hence,
every line of code can generate the output immediately, and the source code as a complete set,
need not be stored in a file. That is why, in the previous section, the usage of single line print(“Hello
World”) could able to generate the output immediately
>>> x=10
>>> y=20
>>> z= x+y
>>> print(z)
30
Here, x, y and z are variables storing respective values. As each line of code above is processed
immediately after the line, the variables are storing the given values. Observe that, though each line is
treated independently, the knowledge (or information) gained in the previous line will be retained by
Python and hence, the further lines can make use of previously used variables. Thus, each line that we
write at the Python prompt are logically related, though they look independent.
5
Python Application Programming – 18EC646
Programming languages like Python will act as an intermediary between the computer and the
programmer. The end-user can request the programmer to write a program to solve one’s problem.
There are certain low-level conceptual structures to construct a program in any programming
language. They are called as building-blocks of a program and listed below.
• Input: Every program may take some inputs from outside. The input may be through keyboard,
mouse, disk-file etc. or even through some sensors like microphone, GPS etc.
• Output: Purpose of a program itself is to find the solution to a problem. Hence, every
program must generate at least one output. Output may be displayed on a monitor or can be
stored in a file. Output of a program may even be a music/voice message.
• Sequential Execution: In general, the instructions in the program are sequentially executed
from the top.
• Conditional Execution: In some situations, a set of instructions have to be executed based on
the truth-value of a variable or expression. Then conditional constructs (like if) have to be
used. If the condition is true, one set of instructions will be executed and if the condition is false,
the true-block is skipped.
• Repeated Execution: Some of the problems require a set of instructions to be repeated
multiple times. Such statements can be written with the help of looping structures like for, while
etc.
• Reuse: When we write the programs for general-purpose utility tasks, it is better to write
them with a separate name, so that they can be used multiple times whenever/wherever
required. This is possible with the help of functions.
The art of programming involves thorough understanding of the above constructs and using them
legibly.
It is obvious that one can do mistakes while writing a program. The possible mistakes are categorized
as below –
6
Python Application Programming – 18EC646
• Syntax Errors: The statements which are not following the grammar (or syntax) of the
programming language are tend to result in syntax errors. Python is a case- sensitive
language. Hence, there is a chance that a beginner may do some syntactical mistakes while
writing a program. The lines involving such mistakes are encountered by the Python when
you run the program and the errors are thrown by specifying possible reasons for the error.
The programmer has to correct them and then proceed further.
• Logical Errors: Logical error occurs due to poor understanding of the problem.
Syntactically, the program will be correct. But, it may not give the expected output. For
example, you are intended to find a%b, but, by mistake you have typed a/b. Then it is a
logical error.
• Semantic Errors: A semantic error may happen due to wrong use of variables, wrong
operations or in wrong order. For example, trying to modify un-initialized variable etc.
Note that, some of textbooks/authors refer logical and semantic error both as same, as the distinction
between these two is very small.
In Python, we don’t need to declare the type of variable because it is a dynamically typed language.
For example, x = 10
Features in Python
There are many features in Python, some of which are discussed below –
1. Easy to code:
Python is a high-level programming language. Python is very easy to learn the language as compared
to other languages like C, C#, Javascript, Java, etc. It is very easy to code in python language and
anybody can learn python basics in a few hours or days. It is also a developer-friendly language.
Since it is open-source, this means that source code is also available to the public. So you can download
it as, use it as well as share it.
3. Object-Oriented Language:
One of the key features of python is Object-Oriented programming. Python supports object-oriented
language and concepts of classes, objects encapsulation, etc.
7
Python Application Programming – 18EC646
Graphical User interfaces can be made using a module such as PyQt5, PyQt4, wxPython, or Tk in
python. PyQt5 is the most popular option for creating graphical apps with Python.
5. High-Level Language:
Python is a high-level language. When we write programs in python, we do not need to remember the
system architecture, nor do we need to manage the memory.
6. Extensible feature:
Python is a Extensible language. We can write us some Python code into C or C++ language and also
we can compile that code in C/C++ language.
Python language is also a portable language. For example, if we have python code for windows and if
we want to run this code on other platforms such as Linux, Unix, and Mac then we do not need to
change it, we can run this code on any platform.
Python is also an Integrated language because we can easily integrated python with other languages
like c, c++, etc.
9. Interpreted Language:
Python is an Interpreted Language because Python code is executed line by line at a time. like other
languages C, C++, Java, etc. there is no need to compile python code this makes it easier to debug our
code. The source code of python is converted into an immediate form called bytecode.
Python has a large standard library which provides a rich set of module and functions so you do not
have to write your own code for every single thing. There are many libraries present in python for such
as regular expressions, unit-testing, web browsers, etc.
Python is a dynamically-typed language. That means the type (for example- int, double, long, etc.) for
a variable is decided at run time not in advance because of this feature we don’t need to specify the
type of variable.
8
Python Application Programming – 18EC646
Module 01
Chapter 02
VARIABLES, EXPRESSIONS, AND STATEMENTS
2.1 Values and types
Value
A value is one of the basic things a program works with, like a letter or a number. For example, 1,2 and
“Hello, World!”. Where ‘1’ and ‘2’ are the variables and “Hello, World!” is a string of letters.
Code : Result:
print (4) 4
If you want to find the data type, the interpreter will give you
Code : Result:
print(type("Hello, World!")) <class 'str'>
print(type(5)) <class 'int'>
print(type(5.00)) <class 'float'>
Code : Result:
age = 32 <class 'str'>
name = "kohli" <class 'int'>
height = 1.75 <class 'float'>
print(type(age))
print(type(name))
print(type(height))
Code : Result:
var_strng_num = "18.3" <class 'float'>
print(type(var_strng_num))
Code : Result:
var_strng_num = "18.3" <class 'float'>
print(type(var_strng_num))
Code : Result:
x = 1,00,000 (1, 0, 0)
print(x)
9
Python Application Programming – 18EC646
In the above example the value of x is considered as the 1,0,0 array, not as a whole number 100000.
Python interprets 1,000,000 as a comma separated sequence of integers, which it prints with spaces
between.
semantic error: the code runs without producing an error message, but it doesn’t do the “right” thing.
Variables
A variable is a name that refers to a value. the most powerful feature of a programming language is
the ability to manipulate variables. An assignment statement creates new variables and gives them
values. For example
Code : Result:
message = 'And now for something completely 17
different' 3.141592653589793
n = 17 And now for something completely different
pi = 3.1415926535897931
print(n)
print(pi)
print(message)
This example makes three assignments. The first assigns a string to a new variable named message; the
second assigns the integer 17 to n; the third assigns the (approximate) value of π to pi.
Code : Result:
age = 32 <class 'str'>
name = "kohli" <class 'int'>
height = 1.75 <class 'float'>
print(type(age))
print(type(name))
print(type(height))
The datatypes that are relative to the data are printed here.
Variable names
Programmers generally choose names for their variables that are meaningful and document what the
variable is used for. Variable names can be arbitrarily long
10
Python Application Programming – 18EC646
• Variable names are case-sensitive (age, Age and AGE are three different variables)
pythnvar = "Anaconda"
pythn_var = "Spyder"
_pythn_var = "Anaconda"
pythnVar = "Spyder"
PYTHNVAR = "Anaconda"
pythnvar2 = "Spyder"
Wrong way of interpreting variables are
3rd_umpire = “Mahinda”
SyntaxError: invalid syntax
3rd_umpire is illegal because it begins with a number.
more@ = 1000000
SyntaxError: invalid syntax
more@ is illegal because it contains an illegal character, @.
class = 'ECE sixth Sem students”
SyntaxError: invalid syntax
The class is one of Python’s keywords. The interpreter uses keywords to recognize the structure of the
program, and they cannot be used as variable names.
Key words.
2.3 Statements
A statement is a unit of code that the Python interpreter can execute. We have seen two kinds of
statements: print being an expression statement and assignment.
When you type a statement in interactive mode, the interpreter executes it and displays the result, if
there is one
A script usually contains a sequence of statements. If there is more than one statement, the results
appear one at a time as the statements execute. For example, the script
Code : Result:
print(1) 1
x=2 2
11
Python Application Programming – 18EC646
print(x)
The assignment statement “x=2” produces no output.
Code : Result:
a=43
b=12 55
print (a + b) 31
print (a - b) -31
print (-a + b) 3.5833333333333335
print (a / b) 3
print (a // b) 516
print (a * b) 7
print (a % b)
2.5 Expressions
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 (assuming that the variable
x has been assigned a value):
the interpreter evaluates the expression and displays the result. But in a script, an expression all by
itself doesn’t do anything. For Example
5 #value
x=5 #Variable assignment expression
x+1 #Operator
12
Python Application Programming – 18EC646
P Parentheses first
E Exponents (Powers and Square Roots, etc.)
MD Multiplication and Division (left-to-right)
AS Addition and Subtraction (left-to-right)
• Parentheses have the highest precedence and can be used to force an expression to evaluate in
the order you want. Since expressions in parentheses are evaluated first, 2 * (3-1) is 4, and
(1+1)**(5-2) is 8. You can also use parentheses to make an expression easier to read, as in (minute
* 100) /60, even if it doesn’t change the result.
• Exponentiation has the next highest precedence, so 2**1+1 is 3, not 4, and 3*1**3 is 3, not 27.
• Multiplication and Division have the same precedence, which is higher than Addition and
Subtraction, which also have the same precedence. So, 2*3-1 is 5, not 4, and 6+4/2 is 8.0, not 5.
• Operators with the same precedence are evaluated from left to right. So, the expression 5-3-1 is
1, not 3, because the 5-3 happens first and then 1 is subtracted from 2.
When in doubt, always put parentheses in your expressions to make sure the computations are
performed in the order you intend.
Code : Result:
q = 7//2 3
print(q) 1
r = 7%2
print (r)
Code :
r = int(input("enter a number : "))
q= number // 6
r = number % 6
if (r) == 0:
print("the number is divisible by 6, and quotient is {0}".format(q))
else:
print("the number is not divisible by 6 the remainder is {0}".format(r))
Result:
13
Python Application Programming – 18EC646
Result 1
enter a number: 4569
the number is not divisible by 6 the remainder is 3
result 2
enter a number: 54
the number is divisible by 6, and quotient is 9
Code : Result:
first = 10 25
second = 15
print(first + second)
Code : Result:
first = '100' 100150
second = '150'
print(first + second)
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.
Code : Result:
name = input() BRCE
print(name) BRCE
Code : Result:
age = input("Enter your age: ") Enter your age: Twenty
print(age) Twenty
Code : Result:
age = int (input("Enter your age: ")) Enter your age: 23
print(age) 23
14
Python Application Programming – 18EC646
In the above code int(input(“………”), helps to read only the numbers as input.
Code : Result:
name = input("Enter Your name : \n") Enter Your name :
print(name) 12354
12354
Code : Result:
name = str(input("Enter Your name : \n")) Enter Your name :
print(name) CHARLES
CHARLES
“\n” makes the code to print in new line.
Write a code to read the airspeed velocity of unladen swallow (it’s a bird).
Code :
prompt = 'What is the airspeed velocity of an unladen swallow?\n'
speed = input(prompt)
print()
print("the Speed is : {0}". format(speed))
Result:
What is the airspeed velocity of an unladen swallow?
I never Measured it.!
float(input( ............. ))
Code :
prompt = 'What is the airspeed velocity of an unladen swallow?\n'
speed = float(input(prompt))
print()
print("the Speed is : {0}". format(speed))
Result:
What is the airspeed velocity of an unladen swallow?
123.665
15
Python Application Programming – 18EC646
speed = float(input(prompt))
ValueError: could not convert string to float: 'three'
The same holds good for the string inputs.
2.10 Comments
As programs get bigger and more complicated, they get more difficult to read. It is often difficult to
look at a piece of code and figure out what it is doing, or why. 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 in Python they start with the # symbol:
Example of comments
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, say
velocity = 5
Multiline comments are represented as
‘’’
………..
prompt = 'What is the airspeed velocity of an unladen swallow?\n'
speed = float(input(prompt))
print() ……….
‘’’
16
Python Application Programming – 18EC646
Interpreter sees all three of these programs as exactly the same but humans see and understand these
programs quite differently. Humans will most quickly understand the intent of the second program
because the programmer has chosen variable names that reflect their intent regarding what data will
be stored in each variable.
variable names “mnemonic variable names”. The word mnemonic2 means “memory aid”. We choose
mnemonic variable names to help us remember why we created the variable in the first place.
2.12 Debugging
At this point, the syntax error you are most likely to make is an illegal variable name, like class and
yield, which are keywords, or odd~job and US$, which contain illegal characters. If you put a space in
a variable name, Python thinks it is two operands without an operator:
bad name = 5
SyntaxError: invalid syntax
month = 09
File "<stdin>", line 1
month = 09
SyntaxError: invalid token
For syntax errors, the error messages don’t help much. The most common messages are SyntaxError:
invalid syntax and SyntaxError: invalid token, neither of which is very informative. The runtime error
you are most likely to make is a “use before def;” that is, trying to use a variable before you have
assigned a value. This can happen if you spell a variable name wrong:
principal = 327.68
interest = principle * rate
NameError: name 'principle' is not defined
17
Python Application Programming – 18EC646
Variables names are case sensitive, so LaTeX is not the same as latex. At this point, the most likely cause
of a semantic error is the order of operations. For example, to evaluate 1/2, you might be tempted to
write
1.0 / 2.0 * pi
But the division happens first, so you would get 1/2, which is not the same thing! There is no way for
Python to know what you meant to write, so in this case you don’t get an error message; you just get
the wrong answer.
Exercise
1. Write a program that uses input to prompt a user for their name and then
welcomes them.
Code :
promt ="Enter Your name: \n\t"
name = str(input(promt))
print("Welcome to Python classes {0}!!".format(name))
Result:
Enter Your name:
Virat Kohli
Welcome to Python classes Virat Kohli!!
2. Write a program to prompt the user for hours and rate per hour to compute
gross pay.
Enter Hours: 35
Pay: 96.25
Code :
promt ="Enter Your name: \n\t"
name = str(input(promt))
hours = float(input("Enter the number of hours worked in the office this week : "))
rate = float(input("Enter the rate per hour: "))
pay = hours * rate
print("The gross pay for {0}, \n considering {1} as the rate per hour is calculated as {2} ".
format(name,rate,pay))
Result:
Enter Your name:
Jerry
Enter the number of hours worked in the office this week : 42
18
Python Application Programming – 18EC646
4. Write a program which prompts the user for a Celsius temperature, convert
the temperature to Fahrenheit, and print out the converted temperature.
9
F = 5 C+32; Is the formula to convert Celsius to Fahrenheit.
Code :
promt = "Enter the temperature in Celsius for conversion: "
celcs = float(input(promt))
frnht = ((9/5)*celcs)+32
print("{0} degree Celsius is equal to {1} degree Fahrenheit" .format (celcs,frnht))
Result:
Enter the temperature in Celsius for conversion: 36
36.0 degree Celsius is equal to 96.8 degree Fahrenheit
19
Python Application Programming – 18EC646
Module 01
Chapter 03
CONDITIONAL EXECUTION
3.1 Boolean expressions
A boolean expression is an expression that is either true or false. The following examples use the
operator ==, which compares two operands and produces True if they are equal and False otherwise:
if 6 == 6
elif 6==9
Code :
condtn = False # F is always capital.
pass_da_exm = True # T is always capital
print(type(condtn))
print(type(pass_da_exm))
Result:
<class 'bool'>
<class 'bool'>
The Boolean operators 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
x == y # is x equal to y.
For example, x > 0 and x < 10, is true only if x is greater than 0 and less than 10. n%2 == 0 or n%3 == 0 is
true if either of the conditions is true.
Finally, the not operator negates a boolean expression, so not (x > y) is true if x > y is false; that is, if x
is less than or equal to y. Python is not very strict. Any nonzero number is interpreted as “true”
20
Python Application Programming – 18EC646
Code :
17 and True
Result:
True
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. The figure 3.1 is the flow of the IF
logic.
If the logical condition is true, then the indented statement gets executed. If the logical condition is
false, the indented statement is skipped.
Statement consists of a header line that ends with the colon character (:) followed by an indented block.
Statements like this are called compound statements because they stretch across more than one line.
There is no limit on the number of statements that can appear in the body, but there must be at least
21
Python Application Programming – 18EC646
one. Occasionally, it is useful to have a body with no in that case, you can use the pass statement, which
does nothing.
if marks > 35 :
pass # need to handle negative values!
If you enter an if statement in the Python interpreter, the prompt will change from three stripes to three
dots to indicate you are in the middle of a block of statements, as shown below:
x=3
if x < 35:
…
print(“Fail”)
…
Fail
if x%2 == 0 :
print('x is even')
else :
print('x is odd')
If the remainder when x is divided by 2 is 0, then we know that x is even, and the program displays a
message to that effect. If the condition is false, the second set of statements is executed.
22
Python Application Programming – 18EC646
The condition must either be true or false, exactly one of the alternatives will be executed. The
alternatives are called branches, because they are branches in the flow of execution.
23
Python Application Programming – 18EC646
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')
elif is an abbreviation of “else if.” Again, exactly one branch will be executed.
There is no limit on the number of elif statements. If there is an else clause, it has to be at the end, but
there doesn’t have to be one.
if choice == 'a':
print('Bad guess')
elif choice == 'b':
print('Good guess')
elif choice == 'c':
print('Close, but not correct')
24
Python Application Programming – 18EC646
Each condition is checked in order. If the first is false, the next is checked, and so on. If one of them is
true, the corresponding branch executes, and the statement ends. Even if more than one condition is
true, only the first true branch executes.
Write a program to award grade for the marks scored by a student according to
the table below.
Marks Grade
0 – 34 Fail
35 – 59 Second Class
60 -100 First Class
Code :
marks = int(input("Enter your Marks: "))
if 0<marks<=34 :
print ("Sorry !! You Failed the Exam ! ")
elif 35 <marks <= 59:
print ("Good!! You have achived Second Class")
else:
print("Congratulations!! You secured First Class")
Result:
Enter your Marks: 58
Good!! You have achived Second Class
Enter your Marks: 34
Sorry !! You Failed the Exam !
Enter your Marks: 66
Congratulations!! You secured First Class
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')
The outer conditional contains two branches. The first branch contains a simple statement. The second
branch contains another if statement, which has two branches of its own. Those two branches are
both simple statements, although they could have been conditional statements as well.
25
Python Application Programming – 18EC646
Although the indentation of the statements makes the structure apparent, nested conditionals become
difficult to read very quickly. In general, it is a good idea to avoid them when you can. 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.')
The print statement is executed only if we make it past both conditionals, so we
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')
Result:
Enter first (x) number : 39
Enter Second (y)33 number : 33
x is greater than y
Enter first (x) number : 33
Enter Second (y) number : 33
x and y are equal
Enter first (x) number : 33
26
Python Application Programming – 18EC646
Code :
prompt = "What is the airspeed velocity of an unladen swallow?\n"
speed = input(prompt)
spd = int(speed)
Result:
\ spd = int(speed)
python fahren.py
Enter Fahrenheit Temperature:72
22.22222222222222
python fahren.py
Enter Fahrenheit Temperature:fred
Traceback (most recent call last):
File "fahren.py", line 2, in <module>
fahr = float(inp)
ValueError: could not convert string to float: 'fred'
So, we make use of the try and except statements.
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.
Code :
27
Python Application Programming – 18EC646
try:
frn = float(inp)
cel = (frn - 32.0) * 5.0 / 9.0
print(cel)
except:
print('Please enter a number')
Result: When try block is executed.
Enter number : 33.33
0.7388888888888879
Result: When Except block is executed.
Enter number : fifty
Please enter a number
Python starts by executing the sequence of statements in the try block.
If an exception occurs in the try block, Python jumps out of the try block and executes the sequence of
statements in the except block.
When Python detects that there is nothing to be gained by evaluating the rest of a logical expression, it
stops its evaluation and does not do the computations in the rest of the logical expression.
When the evaluation of a logical expression stops because the overall value is already known, it is
called short-circuiting the evaluation. While this may seem like a fine point, the short-circuit behaviour
leads to a clever technique called the guardian pattern. Consider the following code sequence in the
Python interpreter:
Code :
x=6
y=2
z = x >= 2 and (x/y) > 2
print (z)
Result:
True
Code :
x=6
y=2
28
Python Application Programming – 18EC646
Code :
x=6
y=0
z = x >= 2 and (x/y) > 2
print (z)
Result:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
The third calculation failed because Python was evaluating (x/y) and y was zero, which causes
a runtime error. But the second example did not fail because the first part of the expression x
>= 2 evaluated to False so the (x/y) was not ever executed due to the short-circuit rule and there
was no error. We can construct the logical expression to strategically place a guard evaluation
just before the evaluation that might cause an error as follows:
Code :
x=1
y=0
z = x >= 2 and y != 0 and (x/y) > 2
print (z)
Result:
False
Code :
x=6
y=0
z = x >= 2 and y != 0 and (x/y) > 2
print (z)
Result:
False
Code :
x=6
y=0
z = x >= 2 and (x/y) > 2 and y != 0
print (z)
Result:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
29
Python Application Programming – 18EC646
In the first logical expression, x >= 2 is False so the evaluation stops at the and. In the second logical
expression, x >= 2 is True but y != 0 is False so we never reach (x/y).
In the third logical expression, the y != 0 is after the (x/y) calculation so the expression fails with an
error.
In the second expression, we say that y != 0 acts as a guard to insure that we only execute (x/y) if y is
non-zero.
3.9 Debugging
The traceback Python displays when an error occurs contains a lot of information, but it can be
overwhelming. The most useful parts are usually:
Where it occurred.
Syntax errors are usually easy to find, but there are a few gotchas. Whitespace errors can be tricky
because spaces and tabs are invisible and we are used to ignoring them.
x=5
y=6
File "<stdin>", line 1
y=6
IndentationError: unexpected indent
In this example, the problem is that the second line is indented by one space. But the error message
points to y, which is misleading. In general, error messages indicate where the problem was
discovered, but the actual error might be earlier in the code, sometimes on a previous line. In general,
error messages tell you where the problem was discovered, but that is often not where it was caused.
Exercise
1. Rewrite your pay computation to give the employee 1.5 times the hourly rate
for hours worked above 40 hours.
Enter Hours: 45
Enter Rate: 10
Pay: 475.0
Code :
promt ="Enter Your name: "
name = str(input(promt))
hours = int(input("Enter the number of hours worked in the office this week:"))
rate = float(input("Enter the rate per hour: "))
if hours <=40:
pay = hours * rate
30
Python Application Programming – 18EC646
else:
pay = (40 * rate) + ((hours - 40) * rate * 1.5)
print("The gross pay for {0} for {1} hours is calculated as INR {2}". format(name,hours,pay))
Result: 40 or less hours
Enter Your name: Rama
Enter the number of hours worked in the office this week: 40
Enter the rate per hour: 10
The gross pay for Rama for 40 hours is calculated as INR 400.0
Result: above hours
Enter Your name: Rama
Enter the number of hours worked in the office this week: 45
Enter the rate per hour: 10
The gross pay for Rama for 45 hours is calculated as INR 475.0
2. Rewrite your pay program using try and except so that your program handles
non-numeric input gracefully by printing a message and exiting the program.
The following shows two executions of the program:
Enter Hours: 20
Enter Rate: nine
Error, please enter numeric input
try:
hrs = int (hours)
rte = int (rate)
if hours <=40:
pay = hours * rate
else:
pay = (40 * rate) + ((hours - 40) * rate * 1.5)
print("The gross pay for {0} for {1} hours is calculated as INR {2} ". format(name,hours,pay))
except:
print("Error!! Enter a number! ")
Result: 40 or less hours
31
Python Application Programming – 18EC646
3. Write a program to prompt for a score between 0.0 and 1.0. If the score is out
of range, print an error message. If the score is between 0.0 and 1.0, print a
grade using the following table:
Score Grade
>= 0.9 A
>= 0.8 B
>= 0.7 C
>= 0.6 D
< 0.6 F
Enter score: perfect
Bad score
Run the program repeatedly as shown above to test the various different
values for input.
Code :
while 1:
inp = input("enter your score :")
try:
score = float(inp)
32
Python Application Programming – 18EC646
33
Python Application Programming – 18EC646
Write a code to calculate the Income tax of an individual of age below 60 years as per the table
Income tax slab rate applicable for New Tax regime – FY 2020-21.
New Regime Income Tax Slab Rates for FY 2020-21
Income Tax Slab
(Applicable for All Individuals & HUF)
Rs 0.0 – Rs 2.5 Lakhs NIL
Rs 2.5 lakhs- Rs 5.00 Lakhs 5% (tax rebate u/s 87a is available)
Rs. 5.00 lakhs- Rs 7.5 Lakhs 10%
Rs 7.5 lakhs – Rs 10.00 Lakhs 15%
Rs 10.00 lakhs – Rs. 12.50 Lakhs 20%
Rs. 12.5 lakhs- Rs. 15.00 Lakhs 25%
> Rs. 15 Lakhs 30%
Code:
Income tax SLabs
'''
def tax_5per(amount):
print("In Slab 1 tax amount is ", 5*amount/100)
return(5*amount/100)
def tax_10per(amount):
print("In Slab 2 tax amount is ", 10*amount/100)
return(10*amount/100)
34
Python Application Programming – 18EC646
def tax_15per(amount):
print("In Slab 3 tax amount is ", 15*amount/100)
return(15*amount/100)
def tax_20per(amount):
print("In Slab 4 tax amount is ", 20*amount/100)
return(20*amount/100)
def tax_25per(amount):
print("In Slab 5 tax amount is ", 25*amount/100)
return(25*amount/100)
def tax_30per(amount):
print("In Slab 6 tax amount is ", 30*amount/100)
return(30*amount/100)
35
Python Application Programming – 18EC646
Result:
enter your income: 500500
In Slab 1 tax amount is 12500.0
In Slab 2 tax amount is 50.0
The tax on your income is 12550.0
enter your income: 1010000
In Slab 1 tax amount is 12500.0
In Slab 2 tax amount is 25000.0
In Slab 3 tax amount is 37500.0
In Slab 4 tax amount is 2000.0
The tax on your income is 77000.0
enter your income: 5000000
In Slab 1 tax amount is 12500.0
In Slab 2 tax amount is 25000.0
In Slab 3 tax amount is 37500.0
In Slab 4 tax amount is 50000.0
In Slab 5 tax amount is 62500.0
In Slab 6 tax amount is 1050000.0
The tax on your income is 1237500.0
enter your income: 220000
You income is tax free
The tax on your income is 0
36
Python Application Programming – 18EC646
Module 01
Chapter 04
FUNCTIONS
Why Functions?
Functions are defined to perform the particular operation on data. Functions can make a program
smaller by eliminating repetitive code if any.
• Creating a new 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. Later, if you make a change,
you only have to make it in one place.
• Dividing a long program into functions allows you 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.
A function is a named sequence of statements that performs a computation. Functions are defined to
perform the particular operation on data. The functions are Called to execute the operation.
print()
int()
type()
these are the function calls that are used to call the functions to perform the operations.
In the above example the function names are int, print and type. Function names are always followed
by the parenthesis (). If we need to send any data to the functions, we can send the data as arguments.
The function takes the arguments and returns the result to the user as return value. Sometimes the
function may not return anything.
37
Python Application Programming – 18EC646
There are 69 built-in functions in Python 3.9.4 Few of the functions that are commonly used are
mentioned below.
max() : this function returns the largest value amongst the arguments. We can use for both numeric
and string values also
big_word = max('Python_Application_Programing')
print(big_word)
y
min(): this function returns the smallest value amongst the arguments. We can use for both numeric
and string values also.
tiny_word = min('Python_Application_Programing')
print(tiny_word)
A
len(): this returns the length of the string or data fed in to the arguments. We can use for both numeric
and string values also.
count = length('Python_Application_Programing')
print(count)
29
38
Python Application Programming – 18EC646
Write a program to read three numbers and find the largest and smallest using
the built-in function min() and max().
Code :
x = int(input("Enter a number : "))
y = int(input("Enter a number : "))
z = int(input("Enter a number : "))
mx = max(x,y,z)
mn = min(x,y,z)
print ("Maximum number is : {} " .format(mx))
print ("Minimum number is : {} ".format(mn))
Result:
Enter a number : 3141
Enter a number : 6727
Enter a number : 9292
Maximum number is : 9292
Minimum number is : 3141
Write a program to the largest and smallest character in the given string, and
also find the length of string.
Code :
promt = "Python Apllicaion Programming"
cnt = len(promt)
mxchar = max(promt)
mnchar = min(promt)
print ("the length of string is : '{}'".format(cnt))
print ("the Maximum Charecter in the string is : '{}'" .format(mxchar))
print ("the minimum Charecter in the string is : '{}'" .format(mnchar))
Result:
the length of string is : '29'
the Maximum Charecter in the string is : 'y'
the minimum Charecter in the string is : 'A'
Python also provides built-in functions that convert values from one type to another. As, we are
aware, the function input() reads all the data as string. So here are the few functions that convert the
type. So they are called as type conversion functions.
int(): it converts the data to integer, the arguments in the paranthesis must be a number. If it is not a
number, an error message is displayed.
int('32')
32
int('Hello')
ValueError: invalid literal for int() with base 10: 'Hello'
39
Python Application Programming – 18EC646
int can convert floating-point values to integers, but it doesn’t round off; it chops off the fraction part:
int(3.99999)
3
int(-2.3)
-2
float(): converts the arguments to floating point number and the return value is always a floating
point number. The arguments are restricted to numeric valves. Alphabets cant be used.
float(32)
32.0
float('3.14159')
3.14159
str (): Converts the arguments to strings.
str(32)
'32'
str(3.14159)
'3.14159'
Making a program truly nondeterministic turns out to be not so easy, but there are ways to make it at
least seem nondeterministic. One of them is to use algorithms that generate pseudorandom numbers.
Pseudorandom numbers are not truly random because they are generated by a deterministic
computation, but just by looking at the numbers it is all but impossible to distinguish them from
random.
The random module provides functions that generate pseudorandom numbers The function random
returns a random float between 0.0 and 1.0. Each time you call random, you get the next number in a
long series.
Code :
import random
for i in range(10):
x = random.random()
print(x)
Result: Result:
0.6314567358576375 0.3790258154387818
0.3257276997298184 0.2743908953431311
0.5380547611457116 0.224275332606506
0.7283551604015127 0.5560913036828098
40
Python Application Programming – 18EC646
0.4422589609606533 0.3002321631594026
0.7513660459019879 0.43561119275272486
0.9471564122650257 0.7023615600143548
0.8221880407503349 0.8326507647564607
0.4670574637453273 0.0806961085355602
0.8832434056299665 0.22016055071806118
Each time we run the code; we get different random values. The result is always between 0.0 and up
to but not including 1.0.
The random function is only one of many functions that handle random numbers. The function randint
takes the parameters low and high, and returns an integer between low and high (including both).
Code :
import random
m = random.randint(5, 10)
print(m)
Result:
9
Result:
5
To choose an element from a sequence at random, you can use choice:
Code :
import random
t = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
m = random.choice(t)
print(m)
Result:
10
Result:
6
The random module also provides functions to generate random values from continuous distributions
including Gaussian, exponential, gamma, and a few more.
Python has a math module that provides most of the familiar mathematical functions. Before we can
use the module, we have to import it:
import math
This statement creates a module object named math. If you print the module object, you get some
information about it:
41
Python Application Programming – 18EC646
print(math)
<module 'math' (built-in)>
The module object contains the functions and variables defined in the module. To access one of the
functions, you have to specify the name of the module and the name of the function, separated by a
dot (also known as a period). This format is called dot notation.
log10(): This take the input argument as integer and float. It returns the float value for the logarithm
of 10.
sin(): this function takes the input as the float or integer. This function returns the sine value
of the given data. the input value should be defined in the radians. The output value is float.
There are sin,cos,tan,sinh,cosh,tanh functions.
radians = 0.7
height = math.sin(radians)
sqrt(): this function returns the square root of the given arguments. The arguments can be
integer and float.
radians(): this is a function to convert the degree value to radians. The input argument can be float
and integer. The result is a floating-point radian value.
x = math.radians(22/7)
print(x)
0.05485320506267893
The first example computes the logarithm base 10 of the signal-to-noise ratio. The math module also
provides a function called log that computes logarithms base e. The second example finds the sine of
radians. The name of the variable is a hint that sin and the other trigonometric functions (cos, tan, etc.)
take arguments in radians. To convert from degrees to radians, divide by 360 and multiply by 2:
42
Python Application Programming – 18EC646
Write a program to find the sine value of 45 degree, using math.pi and
math.sin.
Code :
import math
degrees = 45
radians = degrees / 360.0 * 2 * math.pi
val = math.sin(radians)
print(val)
Result:
0.7071067811865476
It is also possible to add new functions. A function definition specifies the name of a new
function and the sequence of statements that execute when the function is called. Once we
define a function, we can reuse the function over and over throughout our program.
43
Python Application Programming – 18EC646
The above example shows the difference between the calling and the called functions. def: is
the key word to define the function. new_functn is the function name, it follows the same
rule as that of variables. Arguments are the variable values that are sent to the function for
manipulations or calculations. The function may return or may not return anything to the
main function. The function block is indented after the colon.
Here is an example:
def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
print('I sleep all night and I work all day.')
def is a keyword that indicates that this is a function definition. The name of the function is print_lyrics.
The rules for function names are the same as for variable names: letters, numbers and some
punctuation marks are legal, but the first character can’t be a number. You can’t use a keyword as the
name of a function, and you should avoid having a variable and a function with the same name.
The empty parentheses after the name indicate that this function doesn’t take any arguments. Later we
will build functions that take arguments as their inputs. The first line of the function definition is called
the header; the rest is called the body. The header has to end with a colon and the body has to be
indented. By convention, the indentation is always four spaces. The body can contain any number of
statements.
def print_lyrics():
print("Last things last")
print("By the grace of fire and flames")
print("(“You're the face of the future, the blood in my veins, oh-ooh")
print("The blood in my veins, oh-ooh.")
print("I sleep all night and I work all day.")
print(print_lyrics)
print(type(print_lyrics))
print()
print_lyrics()
Result
<function print_lyrics at 0x000001D45D936F70>
<class 'function'>
Last things last
By the grace of fire and flames
You're the face of the future, the blood in my veins, oh-ooh
The blood in my veins, oh-ooh.
I sleep all night and I work all day.
We can also call fuction in a function. Here is an example where repeat_lyrics is a function that calls
the print_lyrics twice in the code.
44
Python Application Programming – 18EC646
def print_lyrics():
print("Last things last")
print("By the grace of fire and flames")
print("(“You're the face of the future, the blood in my veins, oh-ooh")
print("The blood in my veins, oh-ooh.")
print("I sleep all night and I work all day.")
def repeat_lyrics():
print_lyrics()
print()
print_lyrics()
repeat_lyrics()
Result
Last things last
By the grace of fire and flames
You're the face of the future, the blood in my veins, oh-ooh
The blood in my veins, oh-ooh.
I sleep all night and I work all day.
def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
print('I sleep all night and I work all day.')
def repeat_lyrics():
print_lyrics()
print_lyrics()
repeat_lyrics()
In the above code, we have two function definitions, they are print_lyrics and repeat_lyrics. The
execution remains the same but the function objects are created differently. The flow of execution is
here
45
Python Application Programming – 18EC646
• The function block is executed, with the argument values or without based on the function
• If there is any return value, the function returns the value through the statement return() to
the main code.
• Execution always begins at the first statement of the program. Statements are executed one at
a time, in order from top to bottom.
• Function definitions do not alter the flow of execution of the program, but remember that
statements inside the function are not executed until the function is called.
• The control the flow jumps to the body of the function, executes all the statements there, and
then comes back to pick up where it left off.
• one function can call another. While in the middle of one function, the program might have to
execute the statements in another function. But while executing that new function, the
program might have to execute yet another function!
• the program picks up where it left off in the function that called it. When it gets to the end of
the program, it terminates.
46
Python Application Programming – 18EC646
In the above code, the factorial(n) is the function call. The num is called the argument passed. In the
definition of the function, the n is the parameter that takes the value of num to it. Once the function is
invoked, the control executers the function block first and then returns to the main code.
One special property of python is that, we get to write the multiplication operation in the print
statement. Say here are the examples.
print_twice('Spam')
Spam
Spam
print_twice(math.pi)
3.141592653589793
3.141592653589793
print_twice('Spam '*4)
Spam Spam Spam Spam
Spam Spam Spam Spam
The function which returns some result to the calling function after performing a task is known as
fruitful function. (as in the example of the factorial of number)
The built-in functions like mathematical functions, random number generating functions etc. that have
been considered earlier are examples for fruitful functions. One can write a user-defined function so as
to return a value to the calling function as shown in the following example –
def sum(a,b):
return a+b
x=int(input("Enter a number:"))
y=int(input("Enter another number:"))
s=sum(x,y)
print("Sum of two numbers:",s)
Result
Enter a number:3
Enter another number:4
Sum of two numbers: 7
47
Python Application Programming – 18EC646
In the above example, The function sum() take two arguments and returns their sum to the receiving
variable s.
In the print_lyrics() fuction, the functions returns nothing to the called program. So it is a void function.
If we try to read a value form the void function, we get None.
Example
x = print_lyrics()
print(x)
result
None
Exercise
What will the following Python program print out?
def fred():
print("Zap", end = ‘’)
def jane():
print("ABC", end = ‘’)
jane()
fred()
jane()
fred()
jane()
print(" " + jane. name ," "+ fred. name ," " + jane. name )
Result:
Zap ABC jane fred jane
Code :
def fred():
print("Zap", end = ‘’)
def jane():
print("ABC", end = ‘’)
fred()
48
Python Application Programming – 18EC646
jane()
fred()
Result:
Zap ABC Zap
Code :
def fred():
print("Zap", end = ‘’)
def jane():
print("ABC", end = ‘’)
jane()
fred()
print(" " + jane. name )
Result:
ABC Zap jane
Code :
def fred():
print("Zap", end = ‘’)
def jane():
print("ABC", end = ‘’)
jane()
fred()
jane()
Result:
ABC Zap ABC
Rewrite your pay computation with time-and-a-half for overtime and create a
function called computepay which takes two parameters (hours and rate).
Enter Hours: 45
Enter Rate: 10
Pay: 475.0
Code :
def time(hrs:float,rte:float):
pay = hrs * rte
return pay
def computepay(a:float,b:float):
return a+b
49
Python Application Programming – 18EC646
if hours <=40:
pay1 = time(hours,rate)
else:
pay1 = time(40,rate)
pay2 = time(hours-40.0,rate) * 1.5
pay = computepay(pay1,pay2)
print("The gross pay for {0} for {1} hours is calculated as INR {2}". format(name,hours,pay))
Result: 40 or less hours
Enter Your name: Rama
Enter the number of hours worked in the office this week: 40
The gross pay for Rama for 40.0 hours is calculated as INR 400.0
Result: above 40 hours
Enter Your name: Rama
Enter the number of hours worked in the office this week:45
The gross pay for Rama for 45.0 hours is calculated as INR 475.0
Rewrite the grade program from the previous chapter using a function called
computegrade that takes a score as its parameter and returns a grade as a
string.
Score Grade
>= 0.9 A
>= 0.8 B
>= 0.7 C
>= 0.6 D
< 0.6 F
Program Execution:
Enter score: 0.95
A
Enter score: perfect
Bad score
Enter score: 10.0
Bad score
Enter score: 0.75
C
Enter score: 0.5
F
Run the program repeatedly to test the various different values for input.
Code :
def computegrade(score:float):
if score < 0.6:
print("Your Grade is F")
50
Python Application Programming – 18EC646
while 1:
inp = input("enter your score :")
try:
computegrade(float(inp))
except:
print("Bad score")
Result:
enter your score :.33
Your Grade is F
while 1:
inp = input("enter your score :")
try:
score = float(inp)
grade = computergrade(score)
print("{0} is the Grade" .format(grade))
except:
print("Bad score")
Result:
enter your score :0.7
C is the Grade
52
Python Application Programming – 18EC646
53
Python Application Programming – 18EC646
Write a python program to calculate the area of square, rectangle and circle.
Take the input from the user and print the result.
Code :
print("Choose an object to calculate its area: \n 1. Triangle \n 2. Square \n 3. Reactangle ")
choice = int(input("Enter your choice: "))
if choice ==1:
print("Enter the Height and base value in cm.")
h = float(input("Enter the Height: "))
b = float(input("Enter the Base: "))
area = 0.5 * h * b
elif choice ==2 :
print("Enter the measurement of any one side of square in cm.")
h = float(input("Enter the Height: "))
area = h **2
else:
print("Enter the length and width of rectangle: ")
w = float(input("Enter the width: "))
b = float(input("Enter the length: "))
area = w * b
Write a python program to create a user defined function to find the maximum
and minimum letter in a string. Also find the length of string without using
the built-in function.
Code :
def max_char(sttring:str):
return(max(sttring))
def min_char(sttring:str):
return(min(sttring))
54
Python Application Programming – 18EC646
Write a program to check the given year is leap year or not with functions.
HINT:
The year should be divisible by 4 and If it is end of centuries then it should be divisible by 100 and
400
Code :
def check_leap(year):
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
else:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
Write a Python program to find the best of two test average marks out of the
three tests marks accepted from the user.
Code :
a = int(input("Enter test marks in test 1 :"))
b = int(input("Enter test marks in test 2 :"))
c = int(input("Enter test marks in test 3 :"))
avg = (b1+b2)/2
print("The average of {0} and {1} is {2} " .format(b1,b2,avg))
Result:
Enter test marks in test 1 :36
Enter test marks in test 2 :37
Enter test marks in test 3 :39
The average of 39 and 37 is 38.0
55
Python Application Programming – 18EC646
Write a single user defined function named “solve” that returns the remainder
and quotient on the division of two number accepted from the user. Print the
remainder and the quotient separately on the console.
Code :
def solve(a:int,b:int):
q= a//b
r= a%b
return (q,r)
(q,r) = solve(a,b)
56
Python Application Programming – 18EC646
Code :
#Total Marks Calculations
import math
print('the marks shall be alloted in the range 0 to 50')
e1=int(input('Enter the marks obtained in Exam 1: '))
e2=int(input('Enter the marks obtained in Exam 2: '))
s1=int(input('Enter the marks obtained in Sports: '))
a1=int(input('Enter the marks obtained in Activity 1: '))
a2=int(input('Enter the marks obtained in Activity 2: '))
a3=int(input('Enter the marks obtained in Activity 3: '))
57