0% found this document useful (0 votes)
99 views

Python: Your First Impression On

1) The document introduces Python programming by discussing data abstraction and objects. Everything in Python is treated as an object with an ID, type, and value. 2) Real-world examples are used to explain data abstraction - a set of features that define an entity like a car or dog. In Python, objects abstract data and can represent simple or complex data. 3) The key concepts of Python programming - objects, IDs, types, and values - are explained using examples. Any data value is represented by an object, and relationships between objects are important.

Uploaded by

Jaffar Shariff
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)
99 views

Python: Your First Impression On

1) The document introduces Python programming by discussing data abstraction and objects. Everything in Python is treated as an object with an ID, type, and value. 2) Real-world examples are used to explain data abstraction - a set of features that define an entity like a car or dog. In Python, objects abstract data and can represent simple or complex data. 3) The key concepts of Python programming - objects, IDs, types, and values - are explained using examples. Any data value is represented by an object, and relationships between objects are important.

Uploaded by

Jaffar Shariff
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/ 37

3

74 3 - YOUR FIRST IMPRESSION ON PYTHON

Your First Impression on python

3.0 INTRO ...


That’s the reason, I want to create a Great and unparalleled First Impression to
you on Python Programming through this chapter. It will have tremendous impact
on you to learn and master Python.
Before starting your formal study of Python, you are enabled to write solid Python
programs and learn all the corresponding concepts formally, in this chapter. I
have designed this chapter for realizing the following objectives:
By writing these programs on the Day-ONE itself, your interest towards learning
Python should be multiplied and also enables you to overcome the Starting
Troubles normally arise in the learning of a new technology.
If you continue the same spirit for a few more days, you start enjoying Python
Programming. “Wherever you Enjoy Yourself - there you never get Tired”. And
ultimately it leads to evolve you as a professional Python programmer. It’s very
true: “ No good ending may not be possible in the absence of the Right
beginning “. That’s why, it is said that a good beginning is half - the Success.

74
3 - YOUR FIRST IMPRESSION ON PYTHON 75

In fact, you can sustain your interest in a subject by getting instant results in it,
because Results act as a driving force in you. Usually, in the formal learning
procedure, initially lots of theory is dumped on the students. Since this is an
application-oriented subject, lots of theory without the corresponding
applications, annoys the ordinary students, and obviously they form a negative
impression on the subject, label it as ‘complex’, ‘difficult’ or ‘boring’ one. If such
a negative impression is formed once, it is very difficult, or almost impossible,
to turn it as the positive impression. My strong belief is that many students feel
programming studies are difficult, only because their first teacher or book failed
to create a first impression to them on the programming studies.
Now you are going to study the world’s most popular, in-demand and
easy-to-learn Programming language, Python. As I have developed this as 100%
doubt-free system, no doubt will obstruct your study. Go ahead with self-
confidence, and Finish this book within a Predefined time frame. This will help
you a lot to evolve as an Industry-ready Programmer, and choose a rewarding I.T
career on your own.
3.1 DATA ABSTRACTION IN PYTHON
In Python, Objects are abstraction for Data. This means, everything in Python is
an Object. In other words, Python Programs deal only with Objects. That’s the
reason, Python is known as an Object-oriented programming (OOP) language.
More specifically, Python treats all data elements, namely Numbers, Strings,
Files, Collections, as well as Functions as Objects.
Simply, you can understand that an Object as a memory container (box) with
minimum three features: an ID (unique address), a Type and a Value. If you are a
beginner programmer, you must go a long way to understand this concept
thoroughly. Don’t worry about it. I will explain these concepts number of times
in a piecemeal manner contextually. I assure you that you will master this concept
before the end of this book.
First let us understand the phrase “Data Abstraction”. You can understand this
concept easily through the real life examples. Suppose I told you that I purchased
a new Car? Obviously, every Car has a set of properties, such as Brand, Name, CC,
Number, Color, Number of seats, Type of fuel etc. Without knowing all these
details, you could understand, my statement. Because the abstraction “CAR”
indicates you that it is a 4-wheeler and other allied general features.
76 3 - YOUR FIRST IMPRESSION ON PYTHON
So a set of abstract features and characteristics together form something called
CAR. That is an Object. One more example - I told you that I have a pet Dog.
Every pet dog has a name, a color, height, weight, breed etc. Without knowing
all these features, you could understand my statement. There are abstract set of
features and characteristics, which together form something called the ‘DOG’.
This is also an Object. So, understand that in OOP, ‘Abstaraction’ is the most
basic and key concept.
3.2 UNDERSTANDING OBJECTS PRACTICALLY
We write programs to manipulate data and generate results. For example, the
program to produce your Marks report, manipulates your marks in the exams
and generates your Marks report with the necessary details, such as percentage
of marks, Pass / Fail, Grade etc. Data comes in different forms, such as numbers,
text, images, audio or video. Even this chapter, you are reading at this moment is
just a text file, which is a data. Data may be simple or complex. For example, it
may represent your ‘age’, this is a simple data or it may represent your ‘biodata’,
this is a complex data. Therefore, a data may be either a single object or a
collection of objects. Data can even be about data, which is known as Metadata,
that describes the design of other data structures or data that describes the data
of an application.
As I explained in the previous topic, in Python “Objects” are abstraction for data.
Python provides a wide range of data structures, so as to serve all our
programming needs. We can create our customized data structures, suitable to
our specific needs, by combining the
predefined data structures. Now let us Fig 3.1
consider the statement, “Everything is
an Object in Python” analytically. This age object
knowledge is the core for the entire study of 25
Python.
int
Let us write an instruction: age = 25
As the result of this, an Object is created. This
object has three characteristics: ID (name), Type and Value, and you can visualize
them in the alongside diagram. In this case, the ID is ‘age’, Type is int (Integer
type) and the Value is 25. Now we can access the Value 25, using its ID: age
Object: The gist of this explanation is that all data values in a Python program
are represented by objects and relationships among objects. An object is a
3 - YOUR FIRST IMPRESSION ON PYTHON 77

computer-memory representation of a value, belongs to a specific data type.


Each object is characterized by its ID, Type and Value.
ID (IDentifier / name): This is a unique name of an Object. This is the location in
the computer memory (or memory address), where the Object is stored. For
instance, you named your house as “Sweet Home”, that name represents the
location of your house.
Type: The Type of an object represents its characteristics and behaviour. This
means, the type of Value it can represent, and the set of Operations that can be
performed on it. In this example, the type is: int means integer, that can represent
only whole numbers and we can perform
arithmetic, relational and logical
operations on it.
Fig 3.2
Value: This is the value of an object a
belong to a specific data type. In this case, a = 123 123
123
the value: 25 is of int type. Some other
object, for example, height may hold the b
value 5.8, that belongs to float (floating- b = 45 45

point) type.
Let us learn little more about objects. c
c=a+b 168
Consider the following instructions and
corresponding diagrams:
This code creates three objects. By
a 25 int
default, each of their type is int. Unlike
other programming languages, Python
provides data types by default, based on Variable Object Object Type
the type of the value we assign. The first Name Reference
and second objects: a and b are assigned
the literals 123 and 45 respectively.
But We assigned an expression (a + b) to c, instead of assigning a literal.
Then, Python calculated the sum of a and b of objects, and assigned the sum to
c. With reference to this, I explain introduce new terminology to you.
Variable: Understand this as Object’s Reference Variable. This holds the memory
address of the actual object.
Object: This is the real memory container for holding value.
78 3 - YOUR FIRST IMPRESSION ON PYTHON
3.3 UNDERSTANDING BASIC TERMINOLOGY
Now I explain the basic terminology in a practical manner, which enables you
to understand the Programs, element-wise meticulously. Understand every term
with reference to following figure:
1. Object
An object is an in-Computer-Memory representation of a Value belong to a
specific Data Type.
Fig 3.3
Every object has three characteristics:
i. Name / ID ii. Type iii. Value a 123

In the above figure, you can find that the object


Variable ID O bject O bject
holds the int type Literal 123. ( name) Reference
2. Data Type
A data type represents a set of values, and a set of operations allowed to be
performed on those values. For example, one of the Python built-in types is
Integer, which is represented by the word, int. Therefore, the data type int
represents all whole (integral) numbers. E.g. 0, -123, 123456789 (Zero, Positive,
and Negative)
Operations: On the values of int type, we can perform all types of arithmetic,
relational and logical operations.
3. Literal
A literal is a Python-Code representation of a data type value. Every object
contains a literal. In the above figure, the object contains the literal 123 of int
type. Every literal, depending on its nature, belongs to one data type. Some
examples for literals are: 9576, 3.14159,‘Python’, 1.234e5, True, False. Understand
that all these literals belong to different data types.
4. Classification of Data Types (Literals)
Classification Of Built-In Data Types
Data Type Coverage Operations Allowed Examples
int Integers(whole  Arithmetic 0, 45, 123456789
Numbers)  Relational
 Logical
float floating point numbers -1.23 45.678 3.4e5
bool True, False values and or not True, False

str A string of characters + * 'OK', ' 3.14 @#$ '


3 - YOUR FIRST IMPRESSION ON PYTHON 79
5. Object Reference
An object reference is the representation of the identity of an object. More clearly,
you may understand it as this is the memory address of an object. Python Programs
uses an object reference for accessing the object, retrieving the value stored in
it, and manipulating the same. These are like printer variables in C.
6. Variable
A variable is a name for an object reference. In the above diagram ‘a’ is the
variable, which represents the object’s reference. We use the variables to access
the value in the objects, retrieve and manipulate them.
7. Operators
An Operator is a Python code-representation of an operation on a data type. In
the above table, we listed out the operations allowed on each built-in data type.
We can perform only such operation on the data type.
For example, arithmetic operations, such as +, -, *, / % etc. are allowed only on
the int and float types. It is not possible to use them on the bool type. But the ‘ +
‘ operator can be used on a string type variable as a concatenating operator,
while ‘ * ‘ operator is used on strings to repeat it multiple times as specified.
8. Identifiers
We use various types of elements in a Python program, such as variables,
Functions, Modules etc. An identifier is a Python code representation of the name
of the program element. There are a set of rules and conventions for defining
identifiers. We will discuss them in the next chapter in detail.
9. Keywords
Python reserved 33 keywords as the language-oriented identifiers. By their nature,
they are classified into the following three groups.
i. Literals : False, True, None
ii. Operators : and, or, not
iii.Code-builders : as, assert, break, class, continue, def, del, elif, else, except,
finally , for, from, global, if, import, in, is, lambda, nonlocal,
pass, raise, return, try, while, with, yield
Python has given a specific meaning and purpose for each of these keywords.
They must be used exactly for the same purpose in Python programs. They should
not be used as (user-defined) identifiers.
80 3 - YOUR FIRST IMPRESSION ON PYTHON
10. Expressions
An expression is a combination of literals, variables, function calls and operators,
that Python evaluates to produce a single value.
E.g. (a + b) / 4, x * y / (a + b - 3)
Note that operators act upon operands. Operands may be either variables, literals
or expressions. We will discuss all these concepts in detail in the next chapters.
This basic knowledge helps us to understand the following programs formally.
3.4 UNDERSTANDING COMPUTER PROGRAM

As we are going to write computer programs, first let us see the definition of a
Computer Program.
A Computer program is:
i. a set of computer instructions,
ii. to manipulate a set of given data,
iii. to achieve a pre-defined task, and
iv. which is executed on a computer.
Understand this definition through the following example:
a) Task of the program : To Prepare and Print a Marks Report of a Student
b) Set of Instructions
i. Start the Program
ii. Read the Marks in 5 papers from Keyboard
iii. Find the Total Marks (Adding the Marks of 5 papers)
iv. Calculate the Average Marks
v. Display the Marks Report
vi. Stop the Program
c) Set of Data : Marks in 5 Papers
With this example, you can understand the meaning and purpose of a computer
program. The set of instructions (6 nos.), acts upon the set of data (i.e.: Marks in
5 papers), to achieve the Pre-defined task (i.e. displaying marks report). This
program is executed on a Computer, as it is a computer program. If you analyze
the above definition, you can find two core elements, namely Data and Instructions.
3 - YOUR FIRST IMPRESSION ON PYTHON 81

So, if you want to evolve as a professional programmer, you must master


two elements :
1. All the possible ways of Instructing a Computer efficiently.
2. All the Types of Data structures and their nature, strengths and
limitations, and Selecting the right one in every situation.

Since a computer can’t understand the human language instructions as described


above, we must give such a set of instructions in a programming language, such
as Python. Like a human language, such as English, Hindi etc. all Computer
languages, such as C, Java, Python etc. have Semantics (words and meanings) and
Syntax rules (grammar rules). So in order to learn a programming language and
evolve as a Programmer, we need to learn Vocabulary and the Grammar of the
language. Thereafter, we must learn how to construct well-formed sentences in
that language, which are known as Instructions in a programs.
Analogically, the next step is that we need to “Writing a Story”. For writing a
story, you must have a ‘Plot’ and good descriptive capabilities. The same analogy
is applicable to evolve as a computer programmer.
In detail in order to evolve as computer programmer one should adopt the
following steps :
1. Learning Semantics and Syntax rules of a Programming language.
2. Learning to write correct instructions to develop programs.
3. Taking a Problem Domain and Understand it analytically and thoroughly.
4. Understand the Solution Domain - means, which results are expected from the
Software exactly.
5. Developing the Software, using the skills( 1) and ( 2 ) described above.
6. Testing the Software, whether it is working accurately in all possible cases, or not.
By studying these basic steps, you can have an outline idea about Software
development process. We will refine this knowledge in various contexts in the
forthcoming chapters which helps you to evolve as proficient programmer.
82 3 - YOUR FIRST IMPRESSION ON PYTHON
3.5 BUILDING BLOCKS OF A PROGRAM
Typically, every Python program is a composition a set of different blocks, each
of which serves different programming purpose useful to achieve the predefined
task of the program.
1. Input
This is useful for getting data from the outside world. Primarily, data is entered
into a computer using the Keyboard. There are many other ways to input data to
a program, such as reading from a file, microphones, GPS, Touch Screen, Mouse
etc. input devices.
2. Output
Results of a program may be displayed on the monitor Screen, or stored in a file
or written onto a disk or played on a audio system etc.
3. Sequential Execution
In this approach, the statements written in a program are executed in a sequential
order, like we read a text line by line.
4. Conditional / Selection Execution
In this approach, the execution of a statement depends on the ‘truth’ position of
a condition. If the condition is ‘True’, a statement or a set of statements are
executed. If the condition is ‘False’, a statement or a set of statements are skipped.
This is like searching the dictionary for the meaning of a word.
5. Iterative or Repetitive Execution
In this approach, a statement or a set of statements are executed repeatedly, with
or without a change, until the task of the program is achieved.
For example, for printing of a multiplication table, we implement this approach.
E.g. Multiplication table 9 from the first to tenth term :
1 X 9=9
2 X 9 = 18
………
10 X 9 = 90
In this Table, each line is printed with an incrementation, say 1, 2, 3,..., 10.
3 - YOUR FIRST IMPRESSION ON PYTHON 83

6. Reusing Code
We create a block with a set of instructions, so as to perform a subtask, and
name the block, call it and use it, whenever it is needed in a program. This is
known as Function. For example, we have created a function named print_line( )
which can print a line.We call it whenever we need to draw a line in our program.
Simply, in our programming studies, we will mainly focus on the building of all
these blocks. Understand that the art of Programming is composing of these
basic building blocks together to generate the results of a program. And you
must understand that any large and complex programming task even, is formed
by composing these small building blocks. Analogically, the building block of a
massive building even, is a small brick .You will learn about all these building
blocks in our forthcoming chapters.
3.6 PROGRAMMING ERRORS

In real life, if we have to instruct others for getting our jobs done, the essential
criteria are our instruction should be Clear, Complete and Correct (3Cs).
Otherwise, the instruction may not be understood properly and implemented
wrongly. In this case, one leverage is there - as we are instructing to a human,
even if the instruction has some lapses, the person may understand and
implement it correctly, using her/his common sense.
But in computer programming, we should not be lenient at all, because computers
are brainless machines - they don’t have any common sense of their own.
Therefore, we must communicate to a computer very precisely, through our
programs. A smallest lapse, deviation or mistake in our program hampers the
execution of our program. So, we must write our programs cent-percent free of
errors.
However, all errors we commit in programs are not alike by their nature. They
are classified into mainly three types. One type of error causes Interpreter to
give up execution of program. Other types of errors do not stop the execution of
the program, but they make the program to generate wrong or unexpected results.
Some other types of errors make the program to generate unexpected or wrong
results, only for certain set of input values. Therefore, we must have a clear
knowledge about the types of errors and their consequences, before we start
writing our first program.
We can classify programming errors into 3 types as described below :
84 3 - YOUR FIRST IMPRESSION ON PYTHON
1. Syntax errors
2. Semantic errors
3. Logical errors
I will give you a brief explanation about them.
1. Syntax errors
These are first type of errors, we commonly commit in our coding. These are
traced and fixed easily. Because of violating the grammar rules of Python, these
are occurred. However, Python helps us to locate and fix these errors easily. But
sometimes, because of some ‘reflective nature’, a syntax error occurs in one
place, and it reflection (impact) is shown in the later lines. Then Python notifies
the line number, where the reflection is found, but not where the error is occurred.
These cases are little tricky.
2. Semantic Errors
Semantics refers to meaning in a language or logic. Sometimes, our program
may be syntactically perfect, and in the right order, but there may be some mistake
in our program, which makes Python to give unexpected results. In other words,
the program is perfectly correct, but it does not do what we intended to.
See the following segment of code for understanding semantic errors.
a) print (100000) # Prints: 100000
b) print (1,00,000) # Prints: 1 0 0
In the statement (b) above, we inserted commas in the integer literal. This is not
a legal integer literal in Python. But this is a some other legal type, tuple. But
Python Interpreter interprets it as 3 different comma-separated integer literals
and prints it as 1 0 0 with spaces in between.So, understand this error is occurred
because Interpreter took a wrong meaning.
3. Logical Errors
Logic error occurs in our program, when there is a mistake in the order of the
statements or a mistake how the statement/s relate to one another. For instance,
we want to take an assistant, who attained the age of 20 years or more and
obtained ‘Distinction’ in his / her graduation.We have to write the code as follows:
(age >= 20) and (grade == ‘distinction’)
Instead of that, if you write the following it leads to a logical error:
(age >= 20) or (grade == ‘distinction’)
This code leads to selecting a wrong candidate, because of the logical error.
3 - YOUR FIRST IMPRESSION ON PYTHON 85

3.7 GETTING STARTED WITH PYTHON


So far, I have explained all the basic concepts of Python, which are relevant to the
programs in this chapter. Study all these concepts thoroughly. If you have any doubts
in this study, don’t worry, because we will discuss these concepts in depth in the
following chapters. Before working out the programs in this chapter, first install
Python in your system, strictly according to the procedure explained in the 15th
and the last concept of this chapter. Then only, you must start studying the programs
in this chapter. Without working out programs, you can’t derive ensued benefit
out of this chapter.
Executing Python Programs
we have two basic options for running Python code: Interactive mode and Script
mode. Now I explain the procedures of the both
1. Interactive Mode: This is also known as Shell mode. This is useful for quickly
running single lines or blocks of code. Python Shell is available with the basic
Python installation. The symbol >>> indicates that the Shell is ready to accept
interactive commands. As this is the interactive mode, just type the code and
press Enter key. The corresponding results are displayed, as shown below:

2. Script Mode: This is also known as Program mode. If we want to write an actual
program, instead of a few lines of code, we need Script mode. This involves 3 Steps
as described below:
86 3 - YOUR FIRST IMPRESSION ON PYTHON
Step – 1: Typing Program on the Text Editor
In the Standard Python Shell, we have to go to File => New File (or Press Ctrl + N) to
open the Python Text Editor. Then we have type an Script there.

Step – 2: Save the Script with .py extension


After typing the text, you have to Save the file with the appropriate name with .py
extension, in the directory, where you want to save it.

Step – 3: Executing the Program


In order to Run the Script, you may select either: Run => Run module or press F5
key. Then you can view the output.
3 - YOUR FIRST IMPRESSION ON PYTHON 87

3.8 YOUR FIRST PYTHON PROGRAM


Before entering into Python for learning ,writing solid Python Programs remains
as an amazing experience to you . Don’t surprise , this is not a Magic. This is
simply the ‘ Ekalavya Style of Learning ‘. Analogically , this is like learning the
driving of a Car first ,and then learning all the allied elements. You will derive
many benefits out of this approach.
It drives away your dismay towards newly learning a technology and multiplies
your interest and crystallizes your Self-Confidence towards the subject.It enables
you to experience the simplicity and elegance of the Python.It allows you to
understand and own the concepts practically than otherwise.
Above all , it forms the ‘ First- Best Impression’ on Python, which has tremendous
impact on your future learning process.
1. First of all, Write a program to write your Biodata in the following format. You
may give your data or some other data as you like, for the following 7 items :
88 3 - YOUR FIRST IMPRESSION ON PYTHON
——————————————————————
BIODATA
——————————————————————
Name : Arjun
Gender : Male
Age : 22 yrs
Height : 5.6 fts
Weight : 55.5 Kgs
Qualfcn : B.E
Address : 123 - Galaxy residency
: R.K Road , RajajiNagar
: Bangalore - 560010
——————————————————————
For this purpose, prepare a Python Script program, execute it and see the results.
Thereafter , read the line-wise explanation given below the program, which helps
you to understand the coding details of the program. Thereafter, every program
will help you to enrich your knowledge step-by-step.

# 3.1 Demo Program : Printing My Biodata in an elegant Format


1. name = input('Enter your Name : ') # Input Section
2. gender = input('Enter your Gender : ')
3. age = input('Enter your Age : ')
4. hgt = input('Enter your Height : ')
5. wgt = input('Enter your Weight : ')
6. qlfcn = input('Enter your Qualfcn : ')
7. # Address is divided into 3 lines
8. adds_line1 = input('Enter your Adds-Line-1 : ')
9. adds_line2 = input('Enter your Adds-Linr-2 : ')
10. adds_line3 = input('Enter your Adds-Linr-3 : ')
11.
12. print('\n------------------------------------------------------') # Output Sections
13. print('\n\t BIODATA ')
14. print('---------------------------------------------------------')
15. print('Name : ', name )
16. print('Gender : ', gender )
17. print('Age : ', age ,'yrs')
18. print('Height : ', hgt ,'fts')
19. print('Weight : ', wgt ,'Kgs')
20. print('Qualfcn : ', qlfcn )
21. print('Address : ', adds_line1)
22. print(' : ', adds_line2)
23. print(' : ', adds_line3)
24. print('---------------------------------------------------------')

Note: Normally, our addresses contain many elements. That’s why, divide them
into 3 or 4 lines looks realistic.
3 - YOUR FIRST IMPRESSION ON PYTHON 89

OUTPUT:
Enter your Name : Arjun
Enter your Gender : Male
Enter your Age : 22
Enter your Height : 5.6
Enter your Weight : 55.5
Enter your Qualfcn : B.E
Enter your Adds-Line-1 : 123 - Galaxy residency
Enter your Adds-Linr-2 : R.K Road , RajajiNagar
Enter your Adds-Linr-3 : Bangalore - 560010
------------------------------------------------------------
BIODATA
------------------------------------------------------------
Name : Arjun
Gender : Male
Age : 22 yrs
Height : 5.6 fts
Weight : 55.5 Kgs
Qualfcn : B.E
Address : 123 - Galaxy residency
: R.K Road , RajajiNagar
: Bangalore - 560010
-------------------------------------------------------------

Line-wise Explanation
Before understanding the code in a program . you must understand the basic
concept , ‘ Input-Process-Output (IPO) ‘. Every program ,regardless of the
language, takes data for Processing or Presentation or both . That is known as
Input data , simply Input. Most programs process the Input data for generating
results . For example , we enter the marks in 5 exam papers of a student to the
program, through the keyboard, which prints ‘ Students Marks Report ‘. The marks
in 5 papers are the Input data . The program processes the marks and generates
output, with the information, such as Total marks, Average Marks(%), Passed/
Failed, and Exam grade, and displays the Marks Report. That is Output.
In some cases , a program simply takes Input data , and displays Output in a
readable format, without generating any additional information . In this ‘ Biodata’
program , you can find, only Input data and Output data, without any processing
of data items. Now with reference to this explanation ,you can understand the
program line-wise.
Line-1 : name = input(‘ Enter your Name : ‘) # Input Section
90 3 - YOUR FIRST IMPRESSION ON PYTHON
The input( ) is a standard input function meant for reading the input data ,that we
enter through the keyboard . Simply, the input( ) function reads data from the
Keyboard. The function can also display a prompt statement to guide us for, which
data we have to enter. In this case , that is ‘Enter your Name : ‘ . Because of this
prompt statement, the users can enter (type ) relevant data, otherwise the user
may be confused. Just think, without having the prompt statements , can you
operate a Bank ATM ? That’s why, we always write appropriate prompt statement
in input( ) functions. The prompt statements must be enclosed by a pair of single
quotes( ). Note that writing prompt statement in an input( ) function is optional.
Whatever the user enters input data, it is assigned and stored in the variable
named ‘ name ‘ . Understand that a variable represents a memory container .
Lines(2-10) : The same explanation given for the ‘ name ‘ variable, is equally
applicable to the remaining 8 variables in the program.
Lines(8-10) : Typically, any address consists of number of elements , namely
Door No, Name of the Building , Road , Area ,and Town/City, Pin code etc. So we
have defined three variables for 3 lines of a address.You may decide the number
of lines required, depending on the length of the address.
Lines - 11 : Blank line: This is not compulsory. By dividing the blocks of code
with blank lines in a program, we can improve the readability of a program. This
is like a paragraph division in a text document. In this case , we are inserting a
blank line between the Input Section and the Output Section .
Line(1 and 12 ) : Comments : In order to improve the readability of a program ,
we include comments in the programs, using ‘ # ‘ symbol. Whatever text, we
write following the # sign in the same line, is a comment. These are meant only
for improving the readability of the program, but they do not create any
executable code. This means , even if we remove all the comments from this
program, it produces the same output.
With this program and the following explanation, you can learn some basic
operations in Python programs. In the same manner, you will learn some more
new concepts from every program. In this manner, you have to learn programming
concepts and acquire programming skills in a step-by-step approach.
You must remember the following fact :Nobody evolves as a programmer
overnight, it needs time and Right strategy.Your commitment, aptitude, hard work
and common sense are the basic qualities, which evolve you as proficient
programmer.
3 - YOUR FIRST IMPRESSION ON PYTHON 91

3.9 PROGRAM - STUDENT’S MARKS REPORT

Now let us write a program to write a Student’s Marks Report in the following
format. We will learn a few more new points in this program.
__________________________________________________
MARKS REPORT
__________________________________________________
Name : Dharani Class : 10 Roll No:6
__________________________________________________
Subjects : AAA BBB CCC DDD EEE
__________________________________________________
Marks(%) : 68 76 85 78 69
__________________________________________________
Total Marks : ?
Average Marks: ?
__________________________________________________

3.2 Demo Program: Printing Student's Marks Report


1. # Input Section
2. name = input('\n Enter Student\'s Name : ')
3. klass = input('Enter Class No. : ')
4. roll_no = input('Enter Roll No. : ')
5.
6. # Enter the Name and Marks(%) in 5 Subjects
7. sub1_name = input('\n Enter Subject- 1 - Name : ')
8. sub1_marks = input('Enter Marks(%) in Subect-1 : ')
9.
10. sub2_name = input('\n Enter Subject- 2 - Name : ')
11. sub2_marks = input('Enter Marks(%) in Subject-2 : ')
12.
13. sub3_name = input('\n Enter Subject- 3 - Name : ')
14. sub3_marks = input('Enter Marks(%) in Subject-3 : ')
15.
16. sub4_name = input('\n Enter Subject- 4 - Name : ')
17. sub4_marks = input('Enter Marks(%) in Subject-4 : ')
18.
19. sub5_name = input('\n Enter Subject- 5 - Name : ')
20. sub5_marks = input('Enter Marks(%) in Subject-5 : ')
21.
92 3 - YOUR FIRST IMPRESSION ON PYTHON
22. # Processing Section - printing Marks Report
23. tot_marks = int(sub1_marks)+int(sub2_marks)+int(sub3_marks) +
int(sub4_marks)+int(sub5 _marks)
24. avg_marks = int(tot_marks) // 5 # Round off to Floored Integer Value
25.
26. # Printing Marks Report - Output Statements
27. print(' ____________________________________________________________')
28. print(' \t\t MARKS REPORT ')
29. print(' ____________________________________________________________')
30. print(' Name : ','\t', name ,'\t Class : ', klass ,'\t Roll No:', roll_no)
31. print(' ____________________________________________________________')
32. print(' Subjects :','\t', sub1_name,'\t', sub2_name ,'\t', sub3_name,'\t',
sub4_name ,'\t, sub5_name)
33. print(' ____________________________________________________________')
34. print(' Marks(%) :','\t',sub1_marks ,'\t',sub2_marks ,'\t',sub3_marks ,'\t',
sub4_marks ,'\t', sub5_marks)
35. print(' ____________________________________________________________')
36. print(' Total Marks : ' , tot_marks )
37. print(' Average Marks: ' , avg_marks)
38. print(' ____________________________________________________________')
OUTPUT : Enter Student's Name : Dharani
Enter Class No. : 10
Enter Roll No. : 6
Enter Subject- 1 - Name : AAA
Enter Marks(%) in Subect-1 : 68

Enter Subject- 2 - Name : BBB


Enter Marks(%) in Subject-2 : 76

Enter Subject- 3 - Name : CCC


Enter Marks(%) in Subject-3 : 85

Enter Subject- 4 - Name : DDD


Enter Marks(%) in Subject-4 : 78

Enter Subject- 5 - Name : EEE


Enter Marks(%) in Subject-5 : 69
________________________________________________
MARKS REPORT
________________________________________________
Name : Dharani Class : 10 Roll No:6
________________________________________________
Subjects : AAA BBB CCC DDD EEE
________________________________________________
Marks(%) : 68 76 85 78 69
________________________________________________
Total Marks : 376
Average Marks: 75
____________________________________________
3 - YOUR FIRST IMPRESSION ON PYTHON 93

Line wise Explanation:


Line Nos.( 1-20 ) : input( ) statements
We have written 13 input( ) statements , to read the values form the keyboard. All
the values read are assigned to 13 corresponding variables. Notice that all these
Variables provide the corresponding data relating to a Student’s marks report.
So, you must note that we have to declare a variable for every data item, we
require in a program.

Whenever you have to write a program on an issue or problem, first you


must understand the issue thoroughly and then form a clear idea about
the output to be generated by the program. For example, in this Student’s
Marks Report Program, you are well-versed with issue. That’s why, you
form a clear idea on the output : contents and format. With reference to
the expected contents , you have to declare the Variables and write the
input( ) statement. With reference to the formation , you have to write the
corresponding output ( print( ) ) statements.Your Program may be either
big or small ,there will be no room for confusion in writing the program.

Lines( 23 & 24 ) : Processing Section


In this section, we declared two new variables : tot_marks and avg_marks
These are known as Output Variables. These variables are assigned values
through arithmetic statements( or formulae ), unlike input variables. As you have
seen above, the 13 input variables are assigned values through the corresponding
input( ) statements respectively.
You have to learn two more points regarding these processing statements :
All the 5 marks variables are converted to int type as :
int( sub1_marks ) + int( sub2_ marks ) + ...
This is because, the input() function reads any value and converts it into a string
and then assigns it to the corresponding variable. For example, if we enter 68
value for the sub1_marks, it is converted as a string as ‘ 68 ‘ . ‘ As this is a string ,
we can’t perform any arithmetic operation on it. Without performing arithmetic
operations , we cannot derive values for the tot_marks and avg_marks. So, it
should be first converted to int type; then only we can perform any arithmetic
94 3 - YOUR FIRST IMPRESSION ON PYTHON
operation on it. For this purpose , we used : int( Sub1_marks) function syntax for
all the 6 variables in the line - 24 Obviously, the total of the marks in the 5
papers is the int type. Python designates the variable, tot_marks with int type .
We will discuss this concept in depth in the next chapter.
Lines Nos.( 26-38 ) : Output Section
In order to display the output in the required format, we have to write print( )
statements, as I explained about them in detail in the previous program.
In these statements , I have inserted tab ( ‘ \t ‘ ) sequence between two variables.
This sequence creates a tab between two values, which formats the data in a
readable manner. By default, the size of a tab( ‘ \t ‘ ) is 8 spaces length.
3.10 PROGRAM - PRINTING PRICE LIST OF ITEMS
Now let us write a program to print a Price List of 3 Items, each of it has 3
grades, namely grade1, garde2 and grade3. It includes the average price of the
3 grades for each item, as shown below:
______________________________________________
PRICE LIST (Rs./Kg)
______________________________________________
Item Grade1 Grade2 Grade3 Avg.Price
______________________________________________
AAA 95 85 75 ?
BBB 85 78 65 ?
CCC 78 68 55 ?
______________________________________________
#3.3 Demo Program: Printing Price List of Items
1. # Input Section - for Entering Input Values
2. item1_name = input('\nEnter the Name of Item-1 : ') # Item-1
3. item1_grd1_price_kg = input('Enter the Price of Grade-1 - Item1 :')
4. item1_grd2_price_kg = input('Enter the Price of Grade-2 - Item1 :')
5. item1_grd3_price_kg = input('Enter the Price of Grade-3 - Item1 :')
6.
7. item2_name = input('\nEnter the Name of Item-2 : ') # Item- 2
8. item2_grd1_price_kg = input('Enter the Price of Grade-1 - Item2 :')
9. item2_grd2_price_kg = input('Enter the Price of Grade-2 - Item2 :')
10. item2_grd3_price_kg = input('Enter the Price of Grade-3 - Item2 :')
11.
12. item3_name = input('\nEnter the Name of Item-3 : ') # Item - 3
13. item3_grd1_price_kg = input('Enter the Price of Grade-1 - Item3 : ')
14. item3_grd2_price_kg = input('Enter the Price of Grade-2 - Item3 : ')
3 - YOUR FIRST IMPRESSION ON PYTHON 95

15. item3_grd3_price_kg = input('Enter the Price of Grade-3 - Item 3 : ')


16.
17. #Process Section - Calculating Average Prices - Rounding off to Floored Integer
18.
19. item1_avg_price_kg = (int(item1_grd1_price_kg) + int(item 1_grd2_price_kg) +
int(item1_grd3_price_kg )) // 3
20. item2_avg_price_kg = (int(item2_grd1_price_kg) + int(item 2_grd2_price_kg) +
int(item2_grd3_price_kg )) // 3
21. item3_avg_price_kg = (int(item3_grd1_price_kg) + int(item3_grd2_price_kg) +
int(item3_grd3_price_kg )) // 3
22. #Output Section - Printing Price List
23. print(' ______________________________________________')
24. print(' \t PRICE LIST (Rs./Kg)')
25. print(' ______________________________________________')
26. print('Item \tGrade1\tGrade2\tGrade3\tAvg.Price')
27. print(' ______________________________________________')
28. print( item 1_name ,'\t' , item 1_grd1_price_kg ,'\t', item1_grd2_price_kg ,'\t',
item1_grd3_price_kg ,'\t', item1_avg_price_kg )
29. print( item 2_name ,'\t' , item 2_grd1_price_kg ,'\t', item2_grd2_price_kg ,'\t',
item2_grd3_price_kg ,'\t', item2_avg_price_kg )
30. print( item 3_name ,'\t' , item 3_grd1_price_kg ,'\t', item3_grd2_price_kg ,'\t',
item3_grd3_price_kg ,'\t', item3_avg_price_kg )
31. print(' ______________________________________________')

OUTPUT :
Enter the Name of Item-1 : AAA
Enter the Price of Grade-1 - Item1 : 95
Enter the Price of Grade-2 - Item1 : 85
Enter the Price of Grade-3 - Item1 : 75

Enter the Name of Item-2 : BBB


Enter the Price of Grade-1 - Item2 : 85
Enter the Price of Grade-2 - Item2 : 78
Enter the Price of Grade-3 - Item2 : 65

Enter the Name of Item-3 : CCC


Enter the Price of Grade-1 - Item3 : 78
Enter the Price of Grade-2 - Item3 : 68
Enter the Price of Grade-3 - Item3 : 55

Note: In order to save time in typing the code, you may copy and paste the similar
code, and make the necessary changes in it. For example, you may copy
and paste the 19th Line of code for 20th and 21st lines and make the
corresponding changes.
96 3 - YOUR FIRST IMPRESSION ON PYTHON
_____________________________________________
PRICE LIST (Rs./Kg)
______________________________________________
Item Grade1 Grade2 Grade3 Avg.Price
______________________________________________
AAA 95 85 75 85
BBB 85 78 65 76
CCC 78 68 55 67
______________________________________________

Line-wise Explanation :
Line Nos.( 1-17 ) : Declaration and Input Section
In this program we declared 4 variables for the 3 Items each, and the total number
of variables are 12. For the sake improving the readability, we grouped them
Item-wise, by inserting blank lines. For assigning the value for all the 12 variables,
we have written an input( ) statement for each variable separately. Since all the
12 variables are given self-explanatory names, obliviously, you can understand
them easily. The explanation given in the first program is equally applicable to
all these statements.
Line Nos.( 19-21 ) : Processing Section
These 3 statements are written for calculating the Average price( per kg) of the
3 grades of each item. The corresponding formula is the sum of the prices of 3
grades, divided by 3. For the division sake we used // ( double slashes) symbol,
which makes integer division, means ignores fractional part, if any, in the quotient.
In contrast , if we use / (single slash), it produces the fractional part also, if any, in
the quotient. Notice the difference. In this case, as I wanted to ignore paise ithe
average prices, I used // ( integer division operator) instead of / ( real division
operator) for generating an integer value.
Line Nos.( 23-31) : Output Section
This section produces ‘ Price List ‘ in an elegant format. You must Study this
output keenly to understand the elements in detail. I advise you to type this
code carefully, as it is, and try to understand the purpose of each and every
element , with reference to the output of the program. By performing this program
on your own, your self-confidence is doubled towards Python programming.

Notice that the first 3 blocks of code consists of almost same elements,
with simple differences. So, you type the block - 1 (Line Nos. 2 to 5) and
copy he same for the item2 and item3. Then make the necessary changes.
You can save a lot of time in typing code. You may apply the technique in
all places, it is applicable
3 - YOUR FIRST IMPRESSION ON PYTHON 97
3.11 PROGRAM - SCHOOL STATISTICS REPORT
In our first program series in this chapter, this is the fourth and the last one. I
strongly believe that by performing these four programs, you certainly form a
clear idea on the basics of Python programs - their structure, Input/Output ( I/O)
functions and other allied elements, on your own. It is not possible otherwise. I
am sure that these four programs create the First-best Impression to you on Python
Programming, which has tremendous impact in your future learning process.
Now let us write a program to generate School Statistics Report in the following format :
———————————————————
School Statistics Report
———————————————————
ClsNo. NumBoys NumGirls TotStrg
———————————————————
X 33 27 ?
———————————————————
XI 38 22 ?
———————————————————
XII 36 24 ?
———————————————————
Total: ? ? ?
———————————————————
You may write this program on your own with the help of the elements you have
learnt in the previous programs. So try this program sincerely. I am sure that you
can do it.

#3.4 Demo :School Statistics Report


1. # Input Section - Naming Class Nos. as X , XI and XII
2. class1_num = input('\nEnter Class-1 No.: ')# Entering Details of Class - X
3. X_num_boys = input('Enter the No. Boys of Class-X : ')
4. X_num_girls = input('Enter the No. Girls of Class-X : ')
5. # Entering Details of Class -XI
6. class2_num = input('\nEnter Class-2 No.: ')
7. XI_num_boys = input('Enter the No. Boys of Class-XI : ')
8. XI_num_girls = input('Enter the No. Girls of Class-XI : ')
9. # Entering Details of Class - XII
10. class3_num = input('\nEnter Class-3 No.: ')
11. XII_num_boys = input('Enter the No. Boys of Class-XII : ')
12. XII_num_girls = input('Enter the No. Girls of Class-XII : ')
13. # Process Section - Arithmetic Statements
14.
15. X_strength = int(X_num_boys) + int(X_num_girls)
16. XI_strength = int(XI_num_boys) + int(XI_num_girls)
98 3 - YOUR FIRST IMPRESSION ON PYTHON

18. XII_strength = int(XII_num_boys) + int(XII_num_girls)


19.
20. school_boys_strengh = int(X_num_boys) + int(XI_num_boys) +
int(XII_num_boys)
21. school_girls_strengh = int(X_num_girls)+ int(XI_num_girls) +
int(XII_num_girls)
22. school_total_strengh = int(X_strength) + int(XI_strength) + int(XII_strength)
23.
24. # Output Section - Printing Statistics Report
25. print('----------------------------------------------------')
26. print(' School Statistics Report ')
27. print('----------------------------------------------------')
28. print(' ClsNo.','NumBoys','NumGirl','TotStrg',sep = '\t')
29. print('----------------------------------------------------')
30. print(class1_num ,X_num_boys ,X_num_girls , X_strength , sep = '\t')
31. print('----------------------------------------------------')
32. print(class2_num , XI_num_boys , XI_num_girls , XI_strength, sep ='\t')
33. print('----------------------------------------------------')
34. print(class3_num , XII_num_boys , XII_num_girls , XII_strength, sep ='\t')
35. print('----------------------------------------------------')
36. print('Total:',school_boys_strengh,school_girls_strengh,school_total_strengh,
sep = '\t')
37. print('----------------------------------------------------')

OUTPUT:
Enter Class-1 No.: X
Enter the No. Boys of Class-X : 33
Enter the No. Girls of Class-X : 27

Enter Class-2 No.: XI


Enter the No. Boys of Class-XI : 38
Enter the No. Girls of Class-XI : 22

Enter Class-3 No.: XII


Enter the No. Boys of Class-XII : 36
Enter the No. Girls of Class-XII : 24
----------------------------------------------------
School Statistics Report
----------------------------------------------------
ClsNo. NumBoys NumGirl TotStrg
----------------------------------------------------
X 33 27 60
----------------------------------------------------
XI 38 22 60
----------------------------------------------------
XII 36 24 60
----------------------------------------------------
Total: 107 73 180
----------------------------------------------------
3 - YOUR FIRST IMPRESSION ON PYTHON 99

Line-wise Explanation
Line Nos.( 2-12 ) : Input and Declaration Sections
In this report ,we are producing the strength of the boys and girls and the total
strength of each class, for 3 classes. For this purpose, we need 3 variables for
each class, namely class Number, Number of boys, and Number of girls. So, totally
9 input variables are required.
And the corresponding input( ) statements are required to read the data for each
variable. For the sake of readability, I have given class names as X, XI, XII, to
represent 10th, 11th and 12th classes respectively.This is also required because
of a Syntactical reason, which we will discuss in the forth coming chapters.
Line Nos.( 16-22 ) : Processing Section
In this section, we have declared 6 output variables, which are required for the
report.We have written the corresponding arithmetic statements for each output
variable, which assigns the value to the variable.
E.g. X_strength = int( X_num_boys ) + int( X_num_girls)
This statements, evaluates the sum of the number of boys and girls, and assigns
the value to the variable : X_strength. In this previous program, I have explained
the need of converting a string type data into an int type data. The explanation
given in the previous programs, is applicable here also.
Line Nos.( 25-37) : Output Section
We have written the print( ) statements to produce the output in the above given
format. In these statements, I have used a new element ‘ sep ‘. This element
simplifies the coding for formation of output.
We have written ‘ sep = ‘ \t’ ‘ in the five print( ) statements. The ‘ sep ‘ represents
Separator . In each print( ) statement, it replace the comma ( , ) with tab ‘ \t ‘ and
output is printed as if we write tabs in the statements. Note that ‘ sep ‘ manipulator
can be initialized with any other Escape Sequence or a Space. In such cases,
where a comma is written in the print ( ) statement, there that Escape Sequence
or Space will replace the comma.
100 3 - YOUR FIRST IMPRESSION ON PYTHON
3.12 A SMALL TASKS FOR A BIG MOTIVATION
So far you have gone through, and probably worked out four solid Programs
using Python. For a beginner Python learner, no doubt, these are really great
tasks, which create an amazing first impression on Python.
Now One Step further - ‘ Test and Trust ‘ - without testing the amount of your
knowledge, how can you believe it, that you have it. That’s why, here I am giving
you two assignment programs. In order to write these programs, the amount of
knowledge so far you acquired in the previous four programs, is enough. You
don’t need to learn any new element, to write these programs. So I request you
to make a sincere attempt to write the following two programs. If you get any
doubt in the course, you may refer to the previous programs. Nothing wrong in it.
However, you must write these programs on your OWN. There is no better
alternative than Hands on approach. Once you achieve this task, you will be
well motivated to finish the rest of the book in the same spirit. After writing the
programs if you want to compare your programs with our version of programs,
write to us to : [email protected]
1. Write a Program to print the following Weekly Temperature Report :
____________________________________________________
Weekly Temperature Report
____________________________________________________
SUN MON TUE WED THU FRI SAT
____________________________________________________
30.1 32.3 30 30.5 31 32.2 32.9
____________________________________________________
Total Temperature : ?
Average Temperature : ?
____________________________________________________

2. Write a Program to print the following Stock Exchange Sensex Report :


____________________________________
Stock Exchange Sensex Report
____________________________________
Index BSE NSE
____________________________________
Opening 34153 10555
Maximum 34293 10572
Minimum 34100 10500
Closing 34225 10568 ____________________________________
____________________________________ BSE : Bombay Stock Exchange
Avg.Sensex ? ?
___________________________________ NSE : National Stock Exchange
____________________________________
3 - YOUR FIRST IMPRESSION ON PYTHON 101

3.13 UNDERSTANDING FUNCTION - ORIENTED PROGRAMMING (FOP) APPROACH


Function-Oriented Programming( FOP ) is one of the most important
implementation approaches in programming. For example, C is the true FOP
language. Python also supports FOP approach in the implementation of its
programming tasks. So, I want to introduce this approach precisely here, and
we will discuss this in depth in the 7th chapter.
Functions are created in a program so as to perform a single identifiable subtask
by each function. In fact, this ‘ Functions ‘ concept is borrowed from real life ‘
Specialists ‘ . So, we must understand the ‘ Specialists ‘ concept of real life first,
before learning about the functions. Consider the following examples :
1. I want to get my house Cleaned : I call a Specialist for it :
Cleaner
2. I want to get my house Painted and Cleaned :
I call the corresponding Specialists :
Painter and Cleaner
3. I want to get my house Shifted :
I call the corresponding Specialists :
Packers , Lifters and Movers
4. I want to get my house Constructed :
I call the corresponding Specialists
Architect, Engineers, Mason, Transporter, Carpenter , Electrician ,Welder, Plumber, Painter,
Interior Decorator etc.
In Programming terminology, the so-called Specialists in real life, are called
as ‘ Functions ‘ . This means, every function in a program performs only one
single-identifiable subtask, however simple it is. By collective contribution of
all the functions in a program, the main task of the program is performed
You can have a clear idea about the functions through the following example:
Example: Program for Preparing a Student’s Marks Report
102 3 - YOUR FIRST IMPRESSION ON PYTHON
______________________________________________
Marks Report
_______________________________________________
Name: Arun CLASS: 10 Roll NO.: 45
_______________________________________________
Subjects: AAA BBB CCC DDD EEE
_______________________________________________
Marks(%): 45 56 67 78 89
_______________________________________________
Total Marks: 335 Avg. Marks(%): 67
Status : Passed Grade : First Class
_______________________________________________
If you study the above task ,preparing Marks Report analytically , you can
dissect it as the following identifiable subtasks. They are:
1. Reading Marks
2. Calculating Total Marks
3. Calculating Average Marks (%)
4. Testing Pass/Fail
5. Evaluating Grade
6. Printing Marks Report
You can realize one fact- all these subtasks are identifiable subtasks, however
simple they are. In Python , we create a Function to perform each such subtask.
Each function is written with a self-explanatory name, followed by a pair of
parenthesis. So, in order to write a Python program for producing a Marks report,
we have to write the following 6 functions .
1. Read _marks( ) - For reading the marks from the keyboard
2. Calc_total _marks( ) - For calculating the total marks
3. Calc_ avg_marks_perc( ) - For calculating the average marks(%)
4. Testing_pass_or_fail( ) - For testing Pass or Fail
5. Calc_grade( ) - For calculating the exam grade
6. Print_marks report( ) - For printing the Marks Report
Function plays a vital role in programs b ecause they perform all the operations
required for generating output. That’s the reason, I want to introduce a Function-
Oriented Python program, as a ‘ Look and Feel‘ program.You Just go through its structure
and organization of components, without bothering about the coding details.
3 - YOUR FIRST IMPRESSION ON PYTHON 103

3.14 Look and Feel PROGRAM : Student’s Marks Report


This program is a ‘ Look and Feel ‘ FOP program, which is meant for demonstrating
the structure of a true FOP program. At this stage, don’t bother about the coding
details. Understand the structure of the program and its Function components
through the corresponding comments. You will be able to write this program in
the 7th chapter.

# D e m o : M a rk s R e p o rt o f a Stu d e n t w ith G ra d e

# D e clarin g a d a ta S tru c tu re : d ic t fo r s to rin g Stud e n t's d ata


d e f re a d _ stu d _d a ta( ):
'F u n c tio n to R e ad Stud e n ts d ata '
stu d _d a ta = { }
stu d _d a ta ['n am e '] = in p u t('E n te r th e N am e o f Stu d en t :')
stu d _d a ta ['cla ss_n o '] = in p u t('E n te r th e C lassN o :')
stu d _d a ta ['ro ll_n o '] = in p u t('E n te r R o ll N o .:')
re tu rn (stu d _d ata )
# D e c la rin g a d ict fo r sto ring M ark s in 5 P ap e rs
d e f re a d _m a rk s( ):
'F u n c tio n to R e ad M ark s in 5 P ap e rs n am e d "A A A ", "B B B ",...'
m ark _list = { }
m ark _list['A A A '] = in t(in p u t('E n te r A A A M ark s : '))
m ark _list['B B B '] = in t(in p u t('E n te r BB B M a rk s : '))
m ark _list['C C C '] = in t(in p u t('E n te r C C C M a rk s : '))
m ark _list['D D D '] = in t(inp u t('E n te r D D D M a rk s : '))
m ark _list['E E E '] = int(inp u t('E nte r E E E M a rk s : '))
re tu rn m ark _list
# F u n ctio n to R e ce ive M a rk list an d calcu late To ta l M a rk s
d e f to ta l_m a rk s(m _ list):
' F u n c tio n to R e ce ive M ark list a nd ca lc u la te T o ta l M a rk s'
tm = 0
fo r va l in m _ lis t.valu e s( ):
tm + = v al
re tu rn tm
104 3 - YOUR FIRST IMPRESSION ON PYTHON

# Function to Receive Total Marks and Calculate Avg.Marks


def avg_marks(t_marks):
' Function to Receive Total Marks and calculate Average Marks '
am = t_marks// 5
return am
# Function to check Pass or Fail in 5 Papers
def check_pass_or_fail(m_list):
'Function to check Pass or Fail in 5 Papers'
status = True
for val in m_list.values( ):
if val < 35: # Testing - if failed in any paper
status = False # If - failed
return status
# Function to Award Grade only for "status", based on marks%
def grade(a_marks, s_status):
'Function to Award Grade only for "status", based on Marks% '
grade = ' '
if a_marks >= 70 and s_status:
grade = 'Distinction'
elif a_marks >= 60 and s_status:
grade = 'First Class'
elif a_marks >= 50 and s_status:
grade = 'Second Class'
elif a_marks >= 35 and s_status:
grade = 'Third Class'
else:
grade = 'Failed'
return grade
# Function to print Horizontal Line
def print_line( ):
' Function to print Horizontal Line '
print('---------------------------------------------')
3 - YOUR FIRST IMPRESSION ON PYTHON 105

# Function to print Marks Report in a Format


def print_report(s_data,m_list,t_marks,a_marks,s_status,s_grade):
' Function to print Marks Report in a Format '
print_line( )
print('\t\tMarks Report')
print_line( )
print('Name: %s ClassNo.:%s’ %(s_data['name'],s_data['class_no']),end=’ ’)
print(' Roll No. : %s'%(s_data['roll_no']))
print_line( )
print('Subjects: AAA \t BBB \t CCC \t DDD \t EEE')
print_line( )
print('Marks(%):','%d \t %d \t ' %(m_list['AAA'],m_list['BBB']),end='')
print(' %d \t %d \t %d'%(m_list['CCC'],m_list['DDD'],m_list['EEE']))
print_line( )
print('Total Marks : ',t_marks,'\t','Avg.Marks(%): ',a_marks)
print_line( )
if s_status:
print('%s\t\t\tGrade: %s' % ('STATUS', s_grade))
else:
print('%s\t\t\tGrade: %s' % ('FAILED', s_grade))
print_line( )
def main( ): # main Function is calling other Functions
'Main Function is calling other Functions'
s_data = read_stud_data( )
m_list = read_marks( )
t_marks = total_marks(m_list)
a_marks = avg_marks(t_marks)
s_status = check_pass_or_fail(m_list)
s_grade = grade(a_marks,s_status)
print_report(s_data,m_list,t_marks,a_marks,s_status,s_grade)
main( ) # Calling the main( ) Function
106 3 - YOUR FIRST IMPRESSION ON PYTHON

OUTPUT :
Run1: Enter the Name of Student :Arun
Enter the ClassNo :10
Enter Roll No.:8
Enter AAA Marks : 45
Enter BBB Marks : 65
Enter CCC Marks : 78
Enter DDD Marks : 67
Enter EEE Marks : 30
-----------------------------------------------------------
Marks Report
----------------------------------------------------------
Name: Arun ClassNo.:10 Roll No. : 8
----------------------------------------------------------
Subjects: AAA BBB CCC DDD EEE
----------------------------------------------------------
Marks(%): 45 65 78 67 30
----------------------------------------------------------
Total Marks : 285 Avg.Marks(%): 57
----------------------------------------------------------
FAILED Grade: Failed
----------------------------------------------------------

Run2: Enter the Name of Student : Dharani


Enter the ClassNo :10
Enter Roll No.:6
Enter AAA Marks : 45
Enter BBB Marks : 56
Enter CCC Marks : 67
Enter DDD Marks : 78
Enter EEE Marks : 89
---------------------------------------------------------------
Marks Report
---------------------------------------------------------------
Name: Dharani ClassNo.:10 Roll No. : 6
----------------------------------------------------------------
Subjects: AAA BBB CCC DDD EEE
----------------------------------------------------------------
Marks(%): 45 56 67 78 89
----------------------------------------------------------------
Total Marks : 335 Avg.Marks(%): 67
----------------------------------------------------------------
STATUS : PASSED Grade: First Class
----------------------------------------------------------------
3 - YOUR FIRST IMPRESSION ON PYTHON 107

Analysis and Algorithm :


1. According to the Marks Report, there are 8 input data items of the student. For
the sake of integrity, write two separate functions to read data, namely
read_stud_data() (for non-marks data ) and read_marks().
In the read_stud_data( ) function, create a list to store the data, and in the
read_marks( ) function also, create a special data structure, named dict for storing
marks. Both the functions return the list for corresponding list.
2. For calculating total marks
Write a function, named total_marks( ) and pass the mark list as the input
parameter. It returns total marks.
3. For calculating Average Marks, define a function, named avg_marks( ) . It takes
mark list as an input parameter and returns the average marks.
4. Grade in the exam is awarded provided the student passes in all 5 papers.
For checking this, a function, named check_pass_or_fail( ). It takes the marks report
and returns the status, either pass or fail.
5. Evaluating Grade, For evaluating the grade, a function, named grade( ) is to be
defined. It takes two parameters : marks_list and status (passed or failed)
6. As all data required for the student’s marks report is ready, for printing Marks
Report, we define the function named, print_report( ). It takes all the data,
described above and prints the report. It does not return any value.
7. In order to print the report in a format , the horizontal lines are required. For
drawing line, we have defined a function, named print_line( )
8. For Calling all the above functions, we have defined the main( ) function and
called it.
In order to have a clear understanding over Function-Oriented Programming
(FOP) approach, without bothering about coding details, you may read all the
functions, in the program. This knowledge will help you to understand forth-
coming concepts easily.
108 3 - YOUR FIRST IMPRESSION ON PYTHON

RECAP THE CORE CONCEPTS


Recapping the following concepts helps you a lot in Job interviews and
examinations.
1. ID (IDentifier / name)
In Python, every Object has an Identity, a Type and a Value. An Object identity
never changes once it has been created. We may consider it as the Object’s
address in memory. The operator: is compares the identity of two Objects. The
id( ) function returns the memory address of the given Object. ID represents
the location in the computer memory (or memory address), where the Object is
stored.
2. Type
The Type of an object represents its characteristics and behaviour. This means,
the type of Value it can represent, and the set of Operations that can be performed
on it. For example, the type: int (means integer), that can represent only whole
numbers (positive, negative or zero)and we can perform arithmetic, relational
and logical operations on it.
3. Value
This is the value of an object, belong to a specific data type. For example, height
may hold the value 5.8, that belongs to float (floating-point) type.
4. Object
An object is an in-Computer-Memory representation of a Value belong to a
specific Data Type. Every object has three characteristics:
i. Name / ID ii. Type iii. Value
5. Data Type
A data type represents a set of values, and a set of operations allowed to be
performed on those values. For example, one of the Python built-in types is
3 - YOUR FIRST IMPRESSION ON PYTHON 109

Integer, which is represented by the word, int. Therefore, the data type int
represents all whole (integral) numbers. E.g. 0, -123, 123456789 (Zero, Positive,
and Negative).
Operations: On the values of int type, we can perform all types of arithmetic,
relational and logical operations.
6. Literal
A literal is a Python-Code representation of a data type value. Every object
contains a literal. In the above figure, the object contains the literal 123 of int
type. Every literal, depending on its nature, belongs to one data type. Some
examples for literals are: 9576, 3.14159, ‘Python’, 1.234e5, True, False Prima facie,
you can understand that they belong to different types, depending on their nature.
7. Classification of Data Types (Literals)
Classification of Built-In Data Types
Data Type Coverage Operations Allowed Examples
int Integers(whole  Arithmetic 0, 45, 123456789
Numbers)  Relational
 Logical
float floating point numbers -1.23 45.678
3.4e5
bool True, False values and or not True, False
str A string of characters + * 'OK', ' 3.14 @#$ '

8. Object Reference
An object reference is the representation of the identity of an object. More clearly,
you may understand it as this is the memory address of an object. Python Programs
uses an object reference for accessing the object, retrieving the value stored in
it, and manipulating the same. These are like printer variables in C.
9. Variable
A variable is a name for an object reference. In the above diagram ‘a’ is the
variable, which represents the object’s reference. We use the variables to access
the value in the objects, retrieve and manipulate them.
10. Operators
An Operator is a Python code-representation of an operation on a data type. In
the above table, we listed out the operations allowed on each built-in data type.
110 3 - YOUR FIRST IMPRESSION ON PYTHON

We can perform only such operation on the data type. For example, arithmetic
operations, such as +, -, *, /, % etc. are allowed only on the int and float types. It is
not possible to use them on the bool type. But the ‘+ ‘operator can be used on a
string type variable as a concatenating operator, while ‘*’ operator is used on
strings to repeat it multiple times as specified.
11. Identifiers: We use various types of elements in a Python program, such as
variables, Functions, Modules etc. An identifier is a Python code representation
of the name of the program element. There are a set of rules and conventions for
defining identifiers. We will discuss them in the next chapter in detail.
12. Keywords :Python reserved 33 keywords as the language-oriented identifiers.
By their nature, they are classified into the following three groups.
i. Literals : False, True, None
ii. Operators : and, or, not
iii.Code-builders : as, assert, break, class, continue, def, del, elif, else, except,
finally , for, from, global, if, import, in, is, lambda, nonlocal,
pass, raise, return, try, while, with, yield
Python has given a specific meaning and purpose for each of these keywords.
They must be used exactly for the same purpose in Python programs. They should
not be used as (user-define) identifiers.
13. Expressions :An expression is a combination of literals, variables, operators, and
function calls that Python evaluates to produce a single value.
E.g. (a + b) / 4, x * y / (a + b - 3). Note that operators act upon operands. Operands
may be either variables, literals or expressions.
14. Function Definition
A function is a named – block of statements, with the following characteristics:
 having a Self-explanatory name, followed by a pair of parentheses.
E.g. calc_product( ), print_report( ), calc_area( )
may or may not take arguments
E.g. print_line( ), print_area(leng, bread)
 may return a zero or Single value
 Performs a single identifiable task
15. Function-Oriented Program
A program which is divided into number of functions is known as a Function-
Oriented program. Each such function performs a single-identifiable subtask of
the program. By the collective contribution of aLL such functions, the main task
of the program is performed.

You might also like