Python: Your First Impression On
Python: Your First Impression On
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
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
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
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
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.
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
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: ?
__________________________________________________
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
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.
OUTPUT:
Enter Class-1 No.: X
Enter the No. Boys of Class-X : 33
Enter the No. Girls of Class-X : 27
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 : ?
____________________________________________________
# 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
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
----------------------------------------------------------
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.