Module1 Python
Module1 Python
MODULE – 1
1.1 WHY SHOULD YOU LEARN TO WRITE PROGRAMS
Programs are generally written to solve the real-time arithmetic/logical
problems. Nowadays, computational devices like personal computer, laptop,
and cell phones are embedded with operating system, memory and processing
unit. Using such devices one can write a program in the language (which a
computer can understand) of one’s choice to solve various types of problems.
Humans are tend get bored by doing computational tasks multiple times.
Hence, the computer can act as a personal assistant for people for doing their
job!! To make a computer to solve the required problem, one has to feed the
proper program to it. Hence, one should know how to write a program!!
There are many programming languages that suit several situations. The
programmer must be able to choose the suitable programming language for
solving the required problem based on the factors like computational ability of
the device, data structures that are supported in the language, complexity
involved in implementing the algorithm in that language etc.
from the main memory and performs the tasks. Usually, information
stored in the main memory will be vanished when the computer is turned-
off.
3
Notes for Programming in python(Open Elective - 21CS751)
What
Next?
Software
Main Secondary
Memory Memory
The programmer has to use above resources sensibly to solve the problem.
Usually, a programmer will be communicating with CPU by telling it ‘what
to do next’. The usage of main memory, secondary memory, I/O devices
also can be controlled by the programmer.
To communicate with the CPU for solving a specific problem, one has to write
a set of instructions. Such a set of instructions is called as a program.
Thus, the art of programming requires the knowledge about the problem’s
requirement and the strength/weakness of the programming language
chosen for the implementation. It is always advisable to choose
appropriate programming language that can cater the complexity of the
problem to be solved.
Python has rich set of libraries for various purposes like large-scale data
processing, predictive analytics, scientific computing etc. Based on one’s
need, the required packages can be downloaded. But, there is a free open
source distribution Anaconda, which simplifies package management and
deployment. Hence, it is suggested for the readers to install Anaconda
from the below given link, rather than just installing a simple Python.
6
Notes for Programming in python(Open Elective - 21CS751)
https://anaconda.org/anaconda/python
You can choose the working directory of your choice for storing your work. To
open a notebook for Python programming, click on New button at the right-side
of the screen. Now select Python 3 from the drop-down list. A new notebook (or
workbook will be created as shown in Figure 1.3. Type a command of your
choice and press Ctrl+Enter to run that command. One can give
headings/subheadings etc for the commands being typed, store the entire
workbook for future reference etc. Readers are advised to try and experience
various options/menu’s available.
After understanding the basics of few editors of Python, let us start our
communication with Python, by saying Hello World. The Python uses print()
function for displaying the contents. Consider the following code –
Here, after typing the first line of code and pressing the enter key, we could
able to get the output of that line immediately. Then the prompt (>>>) is
returned on the screen. This indicates, Python is ready to take next instruction
as input for processing.
11
Notes for Programming in python(Open Elective - 21CS751)
Once we are done with the program, we can close or terminate Python by
giving quit()
command as shown –
generate the output immediately, and the source code as a complete set, need
not be stored in a file. That is why, in the previous section, the usage of single
line print(“Hello World”) could able to generate the output immediately.
13
Notes for Programming in python(Open Elective - 21CS751)
Here, x, y and z are variables storing respective values. As each line of code
above is processed immediately after the line, the variables are storing the
given values. Observe that, though each line is treated independently, the
knowledge (or information) gained in the previous line will be retained by
Python and hence, the further lines can make use of previously used variables.
Thus, each line that we write at the Python prompt are logically related, though
they look independent.
NOTE that, Python do not require variable declaration (unlike in C, C++, Java
etc) before its use. One can use any valid variable name for storing the values.
Depending on the type (like number, string etc) of the value being assigned, the
type and behavior of the variable name is judged by Python.
listed below –
15
Notes for Programming in python(Open Elective - 21CS751)
Input: Every program may take some inputs from outside. The input may
be through keyboard, mouse, disk-file etc. or even through some sensors
like microphone, GPS etc.
Output: Purpose of a program itself is to find the solution to a problem.
Hence, every program must generate at least one output. Output may be
displayed on a monitor or can be stored in a file. Output of a program may
even be a music/voice message.
Sequential Execution: In general, the instructions in the program are
sequentially executed from the top.
Conditional Execution: In some situations, a set of instructions have to
be
executed based on the truth-value of a variable or expression. Then
conditional constructs (like if) have to be used. If the condition is true, one
set of instructions will be executed and if the condition is false, the true-
block is skipped.
Repeated Execution: Some of the problems require a set of instructions to
be repeated multiple times. Such statements can be written with the help
of looping structures like for, while etc.
Reuse: When we write the programs for general-purpose utility tasks, it is
better to write them with a separate name, so that they can be used
multiple times whenever/wherever required. This is possible with the help
of functions.
NOTE: There is one more type of error – runtime error, usually called as
exceptions. It may occur due to wrong input (like trying to divide a number
by zero), problem in database connectivity etc. When a run-time error
occurs, the program throws some error, which may not be understood by
the normal user. And he/she may not understand how to overcome such
errors. Hence, suspicious lines of code have to be treated by the
programmer himself by the procedure known as exception handling. Python
provides mechanism for handling various possible exceptions like
ArithmeticError, FloatingpointError, EOFError, MemoryError etc. A brief idea
about exception handling is there in Section 1.3.7 later in this Module. For
more details, interested readers can go through the links –
https://docs.python.org/3/tutorial/
errors.html and
https://docs.python.org/2/library/exception
s.html
>>> type("hello")
<class 'str'> #output
>>> type(3)
<class 'int'>
>>> type(10.5)
<class 'float'>
>>> type("15")
<class 'str'>
In the above four examples, one can make out various types str, int and float.
Observe the 4th example – it clearly indicates that whatever enclosed within a
double quote is a string.
1.2.2 Variables
A variable is a named-literal which helps to store a value in the program.
Variables may take value that can be modified wherever required in the
program. Note that, in Python, a variable need not be declared with a specific
type before its usage. Whenever you want a variable, just use it. The type of it
18
Notes for Programming in python(Open Elective - 21CS751)
>>> type(x)
<class 'int'> #type of x is integer
>>> y="hi"
>>> print(y)
hi #output
>>> type(y)
<class 'str'> #type of y is string
Examples:
>>> 3a=5 #starting with a number
SyntaxError: invalid syntax
>>> a$=10 #contains $
SyntaxError: invalid syntax
>>> if=15 #if is a keyword
SyntaxError: invalid syntax
1.2.4 Statements
A statement is a small unit of code that can be executed by the Python
interpreter. It indicates some action to be carried out. In fact, a program is a
sequence of such statements. Following are the examples of statements –
Arithmetic Operators are used to perform basic operations as listed in Table 1.2.
Relational or Comparison Operators are used to check the relationship (like less
than, greater than etc) between two operands. These operators return a
Boolean value – either True or False.
can be written x=
as –
x+y
x+=y
Now, += is compound assignment operator. Similarly, one can use most of the
arithmetic and bitwise operators (only binary operators, but not unary) like *, /,
%, //, &, ^ etc. as compound assignment operators. For example,
>>> x=3
>>> y=5
>>> x+=y #x=x+y
>>> print(x)
8
>>> y//=2 #y=y//2
>>> print(y)
2 #only integer part will be printed
21
Notes for Programming in python(Open Elective - 21CS751)
NOTE:
1. Python has a special feature – one can assign values of different types to
multiple variables in a single statement. For example,
>>> x, y, st=3, 4.2, "Hello"
>>> print("x= ", x, " y= ",y, " st= ", st)
x=3 y=4.2 st=Hello
22
Notes for Programming in python(Open Elective - 21CS751)
1.2.6 Expressions
A combination of values, variables and operators is known as expression.
Following are few examples of expression –
x=5
y=x+10
z= x-y*3
The Python interpreter evaluates simple expressions and gives results even
without print(). For example,
>>> 5
5 #displayed as it is
>>> 1+2
3 #displayed the sum
But, such expressions do not have any impact when written into Python script file.
Multiplication and Division are the next priority. Out of these two
operations, whichever comes first in the expression is evaluated.
>>> print(5*2/4) #multiplication and then division
2.5
>>> print(5/4*2) #division and then multiplication
23
Notes for Programming in python(Open Elective - 21CS751)
2.5
24
Notes for Programming in python(Open Elective - 21CS751)
Addition and Subtraction are the least priority. Out of these two
operations, whichever appears first in the expression is evaluated.
Observe the output: here, the value of y (a string “45”, but not a number 45) is
placed just in front of value of x( a string “32”). Hence the result would be
“3245” and its type would be string.
NOTE: One can use single quotes to enclose a string value, instead of double
quotes.
When input() function is used, the curser will be blinking to receive the data. For
a better understanding, it is better to have a prompt message for the user
informing what needs to be entered as input. The input() function itself can be
used to do so, as shown below –
>>> str1=input("Enter a string: ")
Enter a string: Hello
>>> print("You have entered: ",str1)
You have entered: Hello
One can use new-line character \n in the function input() to make the cursor to
appear in the next line of prompt message –
>>> str1=input("Enter a string:\n")
Enter a string:
Hello #cursor is pushed here
The key-board input received using input() function is always treated as a string
type. If you need an integer, you need to convert it using the function int().
Observe the following example –
>>> x=input("Enter x:")
Enter x:10 #x takes the value “10”, but not 10
>>> type(x) #So, type of x would be str
25
Notes for Programming in python(Open Elective - 21CS751)
<class 'str'>
26
Notes for Programming in python(Open Elective - 21CS751)
A function float() is used to convert a valid value enclosed within quotes into
float number as shown below –
A function chr() is used to convert an integer input into equivalent ASCII character.
>>> a=int(input("Enter an integer:"))
Enter an integer:65
>>> ch=chr(a)
>>> print("Character Equivalent of ", a, "is ",ch)
Character Equivalent of 65 is A
There are several such other utility functions in Python, which will be discussed
later.
1.2.10 Comments
It is a good programming practice to add comments to the program wherever
required. This will help someone to understand the logic of the program.
Comment may be in a single line or spread into multiple lines. A single-line
comment in Python starts with the symbol #. Multiline comments are enclosed
within a pair of 3-single quotes.
Python (and all programming languages) ignores the text written as comment
lines. They are only for the programmer’s (or any reader’s) reference.
Ex1.
a=10000
b=0.3*a
c=a+b
print(c) #output is 13000
Ex2.
basic=10000
da=0.3*basic
gross_sal=basic+da
print("Gross Sal = ",gross_sal) #output is 13000
One can observe that both of these two examples are performing same task.
But, compared to Ex1, the variables in Ex2 are indicating what is being
calculated. That is, variable names in Ex2 are indicating the purpose for which
they are being used in the program. Such variable names are known as
mnemonic variable names. The word mnemonic means memory aid. The mnemonic
variables are created to help the programmer to remember the purpose for
which they have been created.
Python can understand the set of reserved words (or keywords), and hence it
flashes an error when such words are used as variable names by the
programmer. Moreover, most of the Python editors have a mechanism to show
keywords in a different color. Hence, programmer can easily make out the
keyword immediately when he/she types that word.
1.2.12 Debugging
Some of the common errors a beginner programmer may make are syntax
errors. Though Python flashes the error with a message, sometimes it may
become hard to understand the cause of errors. Some of the examples are
given here –
Here, there is a space between the terms avg and sal, which is not allowed.
As shown in above examples, the syntax errors will be alerted by Python. But,
programmer is responsible for logical errors or semantic errors. Because, if the
program does not yield into expected output, it is due to mistake done by the
programmer, about which Python is unaware of.