0% found this document useful (0 votes)
5 views58 pages

Python Module 01 Notestd

The document discusses the importance of learning programming, highlighting its role in solving real-time problems and the need for creativity and logical thinking in programming. It covers the basic architecture of computer hardware, the fundamentals of programming, and the characteristics of Python as a high-level, interpreted language. Additionally, it outlines the building blocks of programs, common errors in programming, and the features that make Python an accessible and versatile language for developers.

Uploaded by

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

Python Module 01 Notestd

The document discusses the importance of learning programming, highlighting its role in solving real-time problems and the need for creativity and logical thinking in programming. It covers the basic architecture of computer hardware, the fundamentals of programming, and the characteristics of Python as a high-level, interpreted language. Additionally, it outlines the building blocks of programs, common errors in programming, and the features that make Python an accessible and versatile language for developers.

Uploaded by

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

Python Application Programming – 18EC646

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.1 Creativity and Motivation


• When a person starts programming, he himself will be both the programmer and the end- user.
Because, he will be learning to solve the problems.
• But, later, he may become a proficient programmer. A programmer should have logical thinking
ability to solve a given problem. He/she should be creative in analyzing the given problems, finding
the possible solutions, optimizing the resources available and delivering the best possible results
to the end-user. Motivation behind programming may be a job-requirement and such other
prospects. But, the programmer should follow certain ethics in delivering the best possible output
to his/her clients.

1
Python Application Programming – 18EC646

• The responsibilities of a programmer includes developing a feasible, user-friendly software with


very less or no hassles.
• The user is expected to have only the abstract knowledge about the working of software, but not
the implementation details. Hence, the programmer should strive hard towards developing most

1.2 Computer Hardware Architecture


To understand the art programming, it is better to know the basic architecture of computer hardware.
The computer system involves some of the important parts as shown in Figure 1.1 These parts are as
explained below:

• 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.

1.3 Understanding Programming

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.

1.4 Words and Sentences

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.

Table 1.1 Keywords in Python

3
Python Application Programming – 18EC646

1.5 Conversing with Python


Once Python is installed, one can go ahead with working with Python. Use the IDE of your choice for
doing programs in Python. After installing Python (or Anaconda distribution), if you just type
‘python’ in the command prompt, you will get the message as shown in Figure 1.4. The prompt >>>
(usually called as chevron) indicates the system is ready to take Python instructions. If you would
like to use the default IDE of Python, that is, the IDLE, then you can just run IDLE and you will get
the editor.

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 –

>>> print(“Hello World”) #type this and press enter key


Hello World #output displayed
>>> #prompt returns again
Here, after typing the first line of code and pressing the enter key, we could able to get the output of
that line immediately. Then the prompt (>>>) is returned on the screen. This indicates, Python is ready
to take next instruction as input for processing

Once we are done with the program, we can close or terminate Python by giving quit() command
as shown –

>>> quit() #Python terminates

4
Python Application Programming – 18EC646

1.6 Terminology: Interpreter and Compiler


All digital computers can understand only the machine language written in terms of zeros and ones.
But, for the programmer, it is difficult to code in machine language. Hence, we generally use high
level programming languages like Java, C++, PHP, Perl, JavaScript etc. Python is also one of the high
level programming languages. The programs written in high level languages are then translated to
machine level instruction so as to be executed by CPU. How this translation behaves depending on the
type of translators viz. compilers and interpreters.

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

Consider an example of adding two numbers –

>>> 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.

1.7 Writing a Program


As Python is interpreted language, one can keep typing every line of code one after the other (and
immediately getting the output of each line) as shown in previous section. But, in real-time scenario,
typing a big program is not a good idea. It is not easy to logically debug such lines. Hence, Python
programs can be stored in a file with extension .py and then can be run. Programs written within a file
are obviously reusable and can be run whenever we want. Also, they are transferrable from one
machine to other machine via pen-drive, CD etc.

5
Python Application Programming – 18EC646

1.8 What is a Program?


A program is a sequence of instructions intended to do some task. For example, if we need to count
the number of occurrences of each word in a text document, we can write a program to do so. Writing
a program will make the task easier compared to manually counting the words in a document.
Moreover, most of the times, the program is a generic solution. Hence, the same program may be
used to count the frequency of words in another file. The person who does not know anything
about the programming also can run this program to count the words.

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.

1.9 The Building Blocks of Programs

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.

1.10 What Could Possibly Go Wrong?

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.

Python and its Salient Features


Python is a dynamic, high level, free open source and interpreted programming language. It supports
object-oriented programming as well as procedural oriented programming.

In Python, we don’t need to declare the type of variable because it is a dynamically typed language.

For example, x = 10

Here, x can be anything such as String, int, etc.

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.

2. Free and Open Source:

Python language is freely available at the official website

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.

4. GUI Programming Support:

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.

7. Python is Portable 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.

8. Python is Integrated language:

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.

10. Large Standard Library

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.

11. Dynamically Typed Language:

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))

Suppose we assign a value 1,00,000 to a variable.

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.

2.2 Variable names and keywords

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

• A variable name must start with a letter or the underscore character


• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )

10
Python Application Programming – 18EC646

• Variable names are case-sensitive (age, Age and AGE are three different variables)

Correct way of declaring a variable is

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.

Keywords are the reserved words . Python reserves 33 keywords:

and del from None True


as elif global nonlocal try
assert else if not while
break except import or with
class False in pass yield
continue finally is raise
def for lambda return

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.

2.4 Operators and operands


Operators are special symbols in Python that carry out arithmetic or logical computation.

The value that the operator operates on is called the operand.

The operators are +, -, *, /, //, and **

Operator Meaning Example


+ Add two operands or unary plus x+y
- Subtract right operand from the left or unary minus x-y
* Multiply two operands x*y
/ Divide left operand by the right one (always results into float) x/y
Modulus - remainder of the division of left operand by the x%y
%
right (remainder of x/y)
Integer division - division that results into whole number
// x // y
adjusted to the left in the number line
** Exponent - left operand raised to the power of right x**y (x to the power y)

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

2.6 Order of Operations


When more than one operator appears in an expression, the order of evaluation depends on the rules
of precedence. For mathematical operators, Python follows mathematical convention. The acronym
PEMDAS is followed in python.

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.

2.7 Modulus operator


The modulus operator works on integers and yields the remainder, when the first operand is divided
by the second. The modulus operator is a percent sign (%).

Code : Result:
q = 7//2 3
print(q) 1
r = 7%2
print (r)

Write a python code to verify the read number is completely divisible by 6.

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

2.8 String operations


The + operator works with strings, but it is not addition in the mathematical sense. Instead, it
performs concatenation, which means joining the strings by linking them end to end. For
example:

Code : Result:
first = 10 25
second = 15
print(first + second)

Code : Result:
first = '100' 100150
second = '150'
print(first + second)

2.9 Asking the user for input


Sometimes we would like to take the value for a variable from the user via their keyboard. Python
provides a built-in function called input that gets input from the keyboard.

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

Write a Program to read an integer, using input function.

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.

Write a Program to read your name, using input function.

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.!

the Speed is: I never Measured it.!


Velocity is an integer, but here the statement can read the string also. To avoid this use

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

the Speed is : 123.665


Result:
What...is the airspeed velocity of an unladen swallow?
three
Traceback (most recent call last):

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

# compute the percentage of the hour that has elapsed


percentage = (minute * 100) / 60
percentage = (minute * 100) / 60 # percentage of an hour
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 much more useful to explain why.

Some of the examples for useless comment is

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() ……….
‘’’

2.11 Choosing mnemonic variable names


As long as you follow the simple rules of variable naming, and avoid reserved words, you have a lot
of choice when you name your variables. For example, the following three programs are identical in
terms of what they accomplish, but very different when you read them and try to understand them.

a = 35.0 hours = 35.0 x1q3z9ahd = 35.0


b = 12.50 rate = 12.50 x1q3z9afd = 12.50
c=a*b pay = hours * rate x1q3p9afd = x1q3z9ahd * x1q3z9afd
print(c) print(pay) print(x1q3p9afd)

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.

for word in words:


print(word)
Which of the tokens (for, word, in, etc.) are reserved words and which are just variable names? Does
Python understand at a fundamental level the notion of words? Beginning programmers have trouble
separating what parts of the code must be the same as this example and what parts of the code are
simply choices made by the programmer.

for slice in pizza:


print(slice)
It is easier for the beginning programmer to look at this code and know which parts are reserved words
defined by Python and which parts are simply variable names chosen by the programmer. It is pretty
clear that Python has no fundamental understanding of pizza and slices and the fact that a pizza
consists of a set of one or more slices. But if our program is truly about reading data and looking for
words in the data, pizza and slice are very un-mnemonic variable names.

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

Enter Rate: 2.75

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

Enter the rate per hour: 2.75


The gross pay for Jerry,
considering 2.75 as the rate per hour is calculated as 115.5

3. 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
Result :
8
8.5
4.0
11

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

condtn = False # F is always capital.


pass_da_exm = True # T is always capital
True and False are special values that belong to the class bool;

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

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
x == y # is x equal to y.

3.2 Logical operators


There are three logical operators: and, or, and not.

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

3.3 Conditional execution


To check conditions and change the behavior of the program accordingly. Conditional statements give
us this ability.

The general structure of IF block:

The simplest form is the 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. 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

Write a code to verify the number is negative


Code :
num = int(input("Enter an integer: "))
if num<0:
print ("The entered integer is negative ")
Result:
Enter an integer: -66
The entered integer is negative

3.4 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')
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.

Write a code to verify the number is positive or negative.


Code :
num = int(input("Enter an integer: "))
if num<0:
print ("The entered interger is negative ")
else:
print ("The entered interger is Positve ")
Result:
Enter an integer: 5
The entered interger is Positive
Enter an integer: -5
The entered interger is negative

Write a code to verify the number is odd or Even


Code :
num = int(input("Enter an number: "))
if num%2 != 0:
print ("The entered integer is ODD ")
else:
print ("The entered integer is EVEN ")
Result:
Enter an integer: 4
The entered integer is EVEN
Enter an integer: 5
The entered integer is ODD

3.5 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:

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

3.6 Nested conditionals


One conditional 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')
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

can get the same effect with the and operator:

if 0 < x and x < 10:


print('x is a positive single-digit number.')

Write a code to compare two numbers using nested if condition.


Code :
x = int(input("Enter first (x) number : "))
y = int(input("Enter Second (y)33 number : "))

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

Enter Second (y) number : 39


x is less than y

3.7 Catching exceptions using try and except


Earlier we saw a code segment where we used the input and int functions to read and parse an integer
number entered by the user. We also saw how treacherous doing this could be:

Code :
prompt = "What is the airspeed velocity of an unladen swallow?\n"
speed = input(prompt)
spd = int(speed)
Result:
\ spd = int(speed)

ValueError: invalid literal for int() with base 10: 'int(speed)'


When we are executing these statements in the Python interpreter, we get a new prompt from the
interpreter, think “oops”, and move on to our next statement. However if you place this code in a
Python script and this error occurs, your script immediately stops in its tracks with a traceback. It does
not execute the following statement.

Here is a sample program to convert a Fahrenheit temperature to a Celsius temperature:

inp = input('Enter Fahrenheit Temperature: ')


fahr = float(inp)
cel = (fahr - 32.0) * 5.0 / 9.0
print(cel)
If we execute this code and give it invalid input, it simply fails with an unfriendly error message:

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.

If the try block is executed, the except is not executed.

If try is not executed then except is executed.

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.

We can rewrite our temperature converter as follows:

Code :

27
Python Application Programming – 18EC646

inp = input("Enter number : ")

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 all goes well, it skips the except block and proceeds.

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.

Handling an exception with a try statement is called catching an exception.

3.8 Short-circuit evaluation of logical expressions


When Python is processing a logical expression such as x >= 2 and (x/y) > 2, it evaluates the expression
from left to right. Because of the definition of and, if x is less than 2, the expression x >= 2 is False and
so the whole expression is False regardless of whether (x/y) > 2 evaluates to True or False.

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

z = x >= 2 and (x/y) > 2


print (z)
Result:
False

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:

What kind of error it was, and

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

Enter Hours: forty


Error, please enter numeric input
Code :
promt ="Enter Your name: "
name = str(input(promt))
hours = input("Enter the number of hours worked in the office this week:")
rate = input("Enter the rate per hour: ")

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

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: twenty
Enter the rate per hour: thirty
Error!! Enter a number!

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

Enter score: 10.0


Bad score

Enter score: 0.75


C

Enter score: 0.5


F

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

if score < 0.6:


print("Your Grade is F")
elif 0.6 <= score < 0.7:
print("Your Grade is D")
elif 0.7 <= score < 0.8:
print("Your Grade is C")
elif 0.8 <= score < 0.9:
print("Your Grade is B")
elif 0.9 <= score <=1.0:
print("Your Grade is A")
else:
print("Bad score")
except:
print("Bad score")
Result:
enter your score :.33
Your Grade is F

enter your score :.66


Your Grade is D

enter your score :.99


Your Grade is A

enter your score :GOOD


Bad score

enter your score :BAD


Bad score

enter your score :BEST


Bad score

enter your score :66


Bad score

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)

income = int(input("enter your income: "))

if income <= 250000:


print("You income is tax free ")

elif 250000< income <= 500000:


tax = tax_5per(income-250000)

elif 500000 < income <= 750000:


tax = tax_5per(250000) + tax_10per(income - 500000)

elif 750000 < income <= 1000000:


tax = tax_5per(250000) + tax_10per(250000) + tax_15per(income - 7500000)

elif 1000000 < income <= 1250000:


tax = tax_5per(250000) + tax_10per(250000)+ tax_15per(250000)+ tax_20per(income - 1000000)

35
Python Application Programming – 18EC646

elif 1250000 < income <= 1500000:


tax = tax_5per(250000) + tax_10per(250000) + tax_15per(250000) + tax_20per(250000) + tax_25per(income - 1250000)
elif income > 1500000:
tax = tax_5per(250000) + tax_10per(250000) + tax_15per(250000) + tax_20per(250000) + tax_25per(250000) + tax_30per(income -
1500000)
print("The tax on your income is {} ".format(tax))

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.

4.1 Function calls

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

4.2 Built-in functions

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'

4.3 Type conversion functions

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'

4.4 Random numbers


In gaming, always there are unpredictable outputs. So we need random data for the verification and
the calculations. That is unpredictable inputs and outputs.

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.

To see a sample, run this loop:

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.

4.5 Math functions

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.

Here are few examples for math functions in python

log10(): This take the input argument as integer and float. It returns the float value for the logarithm
of 10.

ratio = signal_power / noise_power


decibels = 10 * math.log10(ratio)

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.

#to find the value of 1/


√2
math.sqrt(2) / 2.0
0.7071067811865476

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

4.6 Adding new functions

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.

General structure of the function definition is

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.

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.

4.7 Definitions and uses


If all the codes are put together, then it looks like

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

• First the function call is executed.


• The interpreter moves the control to the function now, the arguments are passed.

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.

4.8 Flow of execution

• 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.

4.9 Parameters and arguments


Consider the following example “A code to find the factorial of a number”

def factorial(n: int):


if n <= 1:
return 1;
else:
for i in range (1,n):
n=n*i
return n
num = int(input("enter the value to find factorial: "))
fact = factorial(num)
print("the factorial of the number {} is {}" format(num,fact))

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

We can also call a function in a function like


print_twice(math.cos(math.pi))
-1.0
-1.0

4.10 Fruitful functions and void functions


A function that performs some task, but do not return any value to the calling function is known as
void function. (just as the example we see above print_lyrics())

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()

a) Zap ABC jane fred jane


b) Zap ABC Zap
c) ABC Zap jane
d) ABC Zap ABC
e) Zap Zap Zap
Code :
def fred():
print("Zap", end = ‘’)
def jane():
print("ABC", end = ‘’)

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

promt ="Enter Your name: "


name = str(input(promt))
hours = float(input("Enter the number of hours worked in the office this week:"))
rate = 10.0
pay1 = pay2 = 0

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

elif 0.6 <= score < 0.7:


print("Your Grade is D")
elif 0.7 <= score < 0.8:
print("Your Grade is C")
elif 0.8 <= score < 0.9:
print("Your Grade is B")
elif 0.9 <= score <=1.0:
print("Your Grade is A")
else:
print("Bad score")

while 1:
inp = input("enter your score :")
try:
computegrade(float(inp))
except:
print("Bad score")
Result:
enter your score :.33
Your Grade is F

enter your score :.66


Your Grade is D

enter your score :.99


Your Grade is A

enter your score :GOOD


Bad score

enter your score :BAD


Bad score

enter your score :BEST


Bad score

enter your score :66


Bad score
Python Application Programming – 18EC646

Questions from Exam


Rewrite the grade program form the chapter 1, using a function called
computergrade. Take the score as a parameter and return the grade as a string.
Code :
def computergrade(grade:float):
if score < 0.6:
return "F"
elif 0.6 <= score < 0.7:
return "D"
elif 0.7 <= score < 0.8:
return "C"
elif 0.8 <= score < 0.9:
return "B"
elif 0.9 <= score <=1.0:
return "A"
else:
return "Bad Score!"

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

enter your score :0.22


F is the Grade

enter your score :33


Bad Score! 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

print("The area of given geometric figure is {} cubic cm " .format(area))


Result:
Choose an object to calculate its area:
1. Triangle
2. Square
3. Reactangle

Enter your choice: 1


Enter the Height and base value in cm.

Enter the Height: 8

Enter the Base: 2


The area of given geometric figure is 8.0 cubic cm

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

string = str(input("Enter a String: "))

print("Max of string is {0}" .format(max_char(string)))


print("Max of string is {0}" .format(min_char(string)))

#to find the length of string


count = 0
for i in string:
count +=1
print("the Length of String is {0}" .format(count))
Result:
Enter a String: Jalappa
Max of string is p
Max of string is J
the Length of String is 7

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))

year = int(input("enter the year: "))


check_leap(year)
Result:
Enter the year: 2200
Its not a leap Year!!
Enter the year: 2000
Its a leap year!

Check if the number is positive, negative or zero.


Code :
54
Python Application Programming – 18EC646

num = int(input("Enter a Number : "))


if num < 0:
print("Num is Negative")
elif num >0:
print("Num is Positive")
else:
print("number in Zero")
Result:
Enter a Number : -3
Num is Negative
Enter a Number : 0
number in Zero

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 :"))

if a>=b and a>=c:


b1 = a
if b>=c:
b2=b
else:
b2=c
elif b>=a and b>=c:
b1=b
if a>=c:
b2=a
else:
b2=c
else:
b1=c
if a>=b:
b2=a
else:
b2=b

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)

print(" a/b --- here a is dividend and b is divisor ")


a = int(input("Enter test dividend (a): "))
b = int(input("Enter test divisor(b): "))

(q,r) = solve(a,b)

print("{0} is the quotient and {1} is the remainder " .format(q,r ))


Result:
Enter test dividend (a): 105
Enter test divisor (b): 6
17 is the quotient and 3 is the remainder

56
Python Application Programming – 18EC646

Write a python program to calculate student result based on 2 exam, 1 sport


event and 3 activities conducted in a college with weightage of the activity
=20% and sports =20% for 50 marks.
Two exams (E1,E2) are Conducted for 50 marks each, 1 Sports event (S1) for 50 marks and 3
activities (A1,A2,A3) for 50 marks each.
Assuming the finalised marks shall also be 50 marks.
E1 + E1 is for 60%
S1 is for 20%
A1+A2+A3 for 20 %
The formula is derived to be
Total=[((E1+E2) * 0.6) + ((S1)*0.2) + ((A1+A2+A3)*0.2)]/2

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: '))

total = (((e1+e2) * 0.6) + ((s1)*0.2) + ((a1+a2+a3) * 0.2))/2


total=math.ceil(total)

print('The total marks of student is {0}' .format(total))


Result:
the marks shall be alloted in the range 0 to 50
Enter the marks obtained in Exam 1: 41
Enter the marks obtained in Exam 2: 45
Enter the marks obtained in Sports: 46
Enter the marks obtained in Activity 1: 48
Enter the marks obtained in Activity 2: 47
Enter the marks obtained in Activity 3: 49
The total marks of student is 45

57

You might also like