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

Module1 Python

The document provides an introduction to programming in Python, emphasizing the importance of programming for solving real-world problems and the need for creativity and logical thinking. It covers the basic architecture of computer hardware, the skills required for programming, and the installation of Python and its IDEs, including Jupyter Notebook. Additionally, it explains the concepts of interpreters and compilers, the structure of programs, and common programming constructs such as input, output, and control flow.

Uploaded by

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

Module1 Python

The document provides an introduction to programming in Python, emphasizing the importance of programming for solving real-world problems and the need for creativity and logical thinking. It covers the basic architecture of computer hardware, the skills required for programming, and the installation of Python and its IDEs, including Jupyter Notebook. Additionally, it explains the concepts of interpreters and compilers, the structure of programs, and common programming constructs such as input, output, and control flow.

Uploaded by

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

1

Notes for Programming in python(Open Elective - 21CS751)

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.

1.1.1 Creativity and Motivation


When a person starts programming, he himself will be both the programmer
and the end- user. Because, he will be learning to solve the problems. But, later,
he may become a proficient programmer. A programmer should have logical
thinking ability to solve a given problem. He/she should be creative in analyzing
the given problems, finding the possible solutions, optimizing the resources
available and delivering the best possible results to the end-user. Motivation
behind programming may be a job-requirement and such other prospects. But,
the programmer should follow certain ethics in delivering the best possible
output to his/her clients. The responsibilities of a programmer includes
developing a feasible, user-friendly software with very less or no hassles. The
user is expected to have only the abstract knowledge about the working of
software, but not the implementation details. Hence, the programmer should
strive hard towards developing most effective software.

1.1.2 Computer Hardware Architecture


To understand the art programming, it is better to know the basic architecture
of computer hardware. The computer system involves some of the important
parts as shown in Figure
1.1.These parts are as explained below:
 Central Processing Unit (CPU): It performs basic arithmetic, logical, control
and I/O operations specified by the program instructions. CPU will
perform the given tasks with a tremendous speed. Hence, the good
programmer has to keep the CPU busy by providing enough tasks to it.
 Main Memory: It is the storage area to which the CPU has a direct access.
Usually, the programs stored in the secondary storage are brought into
main memory before the execution. The processor (CPU) will pick a job
2
Notes for Programming in python(Open Elective - 21CS751)

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

Input and Output Central


Devices Processing Unit

Main Secondary
Memory Memory

Figure 1.1 Computer Hardware Architecture

 Secondary Memory: The secondary memory is the permanent storage of


computer. Usually, the size of secondary memory will be considerably
larger than that of main memory. Hard disk, USB drive etc can be
considered as secondary memory storage.
 I/O Devices: These are the medium of communication between the user
and the computer. Keyboard, mouse, monitor, printer etc. are the
examples of I/O devices.
 Network Connection: Nowadays, most of the computers are connected to
network
and hence they can communicate with other computers in a network.
Retrieving the information from other computers via network will be
slower compared to accessing the secondary memory. Moreover, network
is not reliable always due to problem in connection.

The programmer has to use above resources sensibly to solve the problem.
Usually, a programmer will be communicating with CPU by telling it ‘what
to do next’. The usage of main memory, secondary memory, I/O devices
also can be controlled by the programmer.

To communicate with the CPU for solving a specific problem, one has to write
a set of instructions. Such a set of instructions is called as a program.

1.1.3 Understanding Programming


A programmer must have skills to look at the data/information available
about a problem, analyze it and then to build a program to solve the
problem. The skills to be possessed by a good programmer includes –
 Thorough knowledge of programming language: One needs to know the
vocabulary and grammar (technically known as syntax) of the
programming language. This will help in constructing proper instructions
in the program.
 Skill of implementing an idea: A programmer should be like a ‘story teller’.
That is, he must be capable of conveying something effectively. He/she
4
Notes for Programming in python(Open Elective - 21CS751)

must be able to solve the problem by designing suitable algorithm and


implementing it. And, the program must provide appropriate output as
expected.
5
Notes for Programming in python(Open Elective - 21CS751)

Thus, the art of programming requires the knowledge about the problem’s
requirement and the strength/weakness of the programming language
chosen for the implementation. It is always advisable to choose
appropriate programming language that can cater the complexity of the
problem to be solved.

1.1.4 Words and Sentences


Every programming language has its own constructs to form syntax of the
language. Basic constructs of a programming language includes set of
characters and keywords that it supports. The keywords have special
meaning in any language and they are intended for doing specific task.
Python has a finite set of keywords as given in Table 1.1.

Table 1.1 Keywords in Python


and as assert break class continue
def del elif else except False
finally for from global if import
in is lambda None nonlocal not
or pass raise return True try
while with Yield

A programmer may use variables to store the values in a program. Unlike


many other programming languages, a variable in Python need not be
declared before its use.

1.1.5 Python Editors and Installing Python


Before getting into details of the programming language Python, it is better
to learn how to install the software. Python is freely downloadable from
the internet. There are multiple IDEs (Integrated Development
Environment) available for working with Python. Some of them are
PyCharm, LiClipse, IDLE etc. When you install Python, the IDLE editor will
be available automatically. Apart from all these editors, Python program
can be run on command prompt also. One has to install suitable IDE
depending on their need and the Operating System they are using.
Because, there are separate set of editors (IDE) available for different OS
like Window, UNIX, Ubuntu, Soloaris, Mac, etc. The basic Python can be
downloaded from the link:
https://www.python.org/downloads/

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

Successful installation of anaconda provides you Python in a command


prompt, the default editor IDLE and also a browser-based interactive
computing environment known as jupyter notebook.
7
Notes for Programming in python(Open Elective - 21CS751)

The jupyter notebook allows the programmer to create notebook documents


including live code, interactive widgets, plots, equations, images etc. To code in
Python using jupyter notebook, search for jupyter notebook in windows search (at
Start menu). Now, a browser window will be opened similar to the one shown in
Figure 1.2.

Figure 1.2 Homepage of Jupyter Notebook


8
Notes for Programming in python(Open Elective - 21CS751)

Figure 1.3 IDE of Jupyter Notebook


9
Notes for Programming in python(Open Elective - 21CS751)

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.

1.1.6 Conversing with Python


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

Figure 1.4 Python initialization in command prompt

After understanding the basics of few editors of Python, let us start our
communication with Python, by saying Hello World. The Python uses print()
function for displaying the contents. Consider the following code –

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


Hello World #output displayed
>>> #prompt returns again
10
Notes for Programming in python(Open Elective - 21CS751)

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)

Figure 1.5 Python IDLE editor

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

>>> quit() #Python terminates

1.1.7 Terminology: Interpreter and Compiler


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

A compiler translates the source code of high-level programming language into


machine level language. For this purpose, the source code must be a complete
program stored in a file (with extension, say, .java, .c, .cpp etc). The compiler
generates executable files (usually with extensions .exe, .dll etc) that are in
machine language. Later, these executable files are executed to give the
output of the program.

On the other hand, interpreter performs the instructions directly, without


requiring them to be pre-compiled. Interpreter parses (syntactic analysis) the
source code ant interprets it immediately. Hence, every line of code can
12
Notes for Programming in python(Open Elective - 21CS751)

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)

Consider an example of adding two numbers –


>>> x=10
>>> y=20
>>> z= x+y
>>> print(z)
30

Here, x, y and z are variables storing respective values. As each line of code
above is processed immediately after the line, the variables are storing the
given values. Observe that, though each line is treated independently, the
knowledge (or information) gained in the previous line will be retained by
Python and hence, the further lines can make use of previously used variables.
Thus, each line that we write at the Python prompt are logically related, though
they look independent.

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.

1.1.8 Writing a Program


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

1.1.9 What is a Program?


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

Programming languages like Python will act as an intermediary between the


computer and the programmer. The end-user can request the programmer to
write a program to solve one’s problem.

1.1.10 The Building Blocks of Programs


There are certain low-level conceptual structures to construct a program in any
programming language. They are called as building-blocks of a program and
14
Notes for Programming in python(Open Elective - 21CS751)

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.

The art of programming involves thorough understanding of the above


constructs and using them legibly.

1.1.11 What Could Possibly Go Wrong?


It is obvious that one can do mistakes while writing a program. The possible
mistakes are categorized as below –
 Syntax Errors: The statements which are not following the grammar (or
syntax) of the programming language are tend to result in syntax errors.
Python is a case- sensitive language. Hence, there is a chance that a
beginner may do some syntactical mistakes while writing a program. The
lines involving such mistakes are encountered by the Python when you
run the program and the errors are thrown by specifying possible reasons
for the error. The programmer has to correct them and then proceed
further.
 Logical Errors: Logical error occurs due to poor understanding of the
problem. Syntactically, the program will be correct. But, it may not give
the expected output. For example, you are intended to find a%b, but, by
mistake you have typed a/b. Then it is a logical error.
 Semantic Errors: A semantic error may happen due to wrong use of
variables, wrong operations or in wrong order. For example, trying to
modify un-initialized variable etc.

Note that, some of textbooks/authors refer logical and semantic error


16
Notes for Programming in python(Open Elective - 21CS751)

both as same, as the distinction between these two is very small.


17
Notes for Programming in python(Open Elective - 21CS751)

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

1.2 VARIABLES, EXPRESSIONS AND STATEMENTS


After understanding some important concepts about programming and
programming languages, we will now move on to learn Python as a
programming language with its syntax and constructs.

1.2.1 Values and Types


A value is one of the basic things in a program. It may be like 2, 10.5, “Hello”
etc. Each value in Python has a type. Type of 2 is integer; type of 10.5 is
floating point number; “Hello” is string etc. The type of a value can be checked
using type function as shown below –

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

will be decided by the value assigned to it. A value can be assigned to a


variable using assignment operator (=). Consider the example given below–
>>> x=10
>>> print(x)
10 #output
19
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

It is observed from above examples that the value assigned to variable


determines the type of that variable.

1.2.3 Variable Names and Keywords


It is a good programming practice to name the variable such that its name
indicates its purpose in the program. There are certain rules to be followed
while naming a variable –
 Variable name must not be a keyword
 They can contain alphabets (lowercase and uppercase) and numbers, but
should not start with a number.
 It may contain a special character underscore(_), which is usually used to
combine variables with two words like my_salary, student_name etc. No
other special characters like @, $ etc. are allowed.
 As Python is case-sensitive, variable name sum is different from SUM, Sum
etc.

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 –

>>> print("hello") #printing statement


hello
>>> x=5 #assignment statement
>>> print(x) #printing statement

1.2.5 Operators and Operands


Special symbols used to indicate specific tasks are called as operators. An
operator may work on single operand (unary operator) or two operands (binary
operator). There are several types of operators like arithmetic operators,
relational operators, logical operators etc. in Python.
20
Notes for Programming in python(Open Elective - 21CS751)

Arithmetic Operators are used to perform basic operations as listed in Table 1.2.

Table 1.2 Arithmetic Operators


Operator Meaning Example
+ Addition Sum= a+b
- Subtraction Diff= a-b
* Multiplication Pro= a*b
/ Division Q=
a/b X =
5/3
(X will get a value
1.666666667)
// Floor Division – returns F = a//b
only X= 5//3 (X will get a value 1)
integral part after division
% Modulus – remainder R = a %b
after (Remainder after dividing a by
division b)
** Exponent E = x** y
(means x to the powder of y)

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.

Assignment Operators: Apart from simple assignment operator = which is used


for assigning values to variables, Python provides compound assignment
operators. For example,

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)

2. Python supports bitwise operators like &(AND), | (OR), ~(NOT), ^(XOR),


>>(right shift) and <<(left shift). These operators will operate on every
bit of the operands. Working procedure of these operators is same as that
in other languages like C and C++.
3. There are some special operators in Python viz. Identity operator (is and is
not) and membership operator (in and not in). These will be discussed in
further Modules.

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.

1.2.7 Order of Operations


When an expression contains more than one operator, the evaluation of
operators depends on the precedence of operators. The Python operators follow
the precedence rule (which can be remembered as PEMDAS) as given below –
 Parenthesis have the highest precedence in any expression. The
operations within parenthesis will be evaluated first. For example, in the
expression (a+b)*c, the addition has to be done first and then the sum is
multiplied with c.
 Exponentiation has the 2nd precedence. But, it is right associative. That is,
if there are two exponentiation operations continuously, it will be
evaluated from right to left (unlike most of other operators which are
evaluated from left to right). For example,
>>> print(2**3) #It is 23
8
>>> print(2**3**2) #It 2
23 , so to be evaluated from right
is 512

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

1.2.8 String Operations


String concatenation can be done using + operator as shown below –
>>> x="32"
>>> y="45"
>>> print(x+y)
3245

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.

1.2.9 Asking the User for Input


Python uses the built-in function input() to read the data from the keyboard.
When this function is invoked, the user-input is expected. The input is read till
the user presses enter- key. For example:
>>> str1=input()
Hello how are you? #user input
>>> print(“String is “,str1)
String is Hello how are you? #printing str1

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)

>>> x=int(input("Enter x:")) #use int()


Enter x:10
>>> type(x) #Now, type of x is int
<class 'int'>

A function float() is used to convert a valid value enclosed within quotes into
float number as shown below –

>>> f=input("Enter a float value:")


Enter a float value: 3.5
>>> type(f)
<class 'str'> #f is actually a string “3.5”
>>> f=float(f) #converting “3.5” into float value 3.5
>>> type(f)
<class 'float'>

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.

Ex1. #This is a single-line comment

Ex2. ''' This


is a
multiline
comment '''

Python (and all programming languages) ignores the text written as comment
lines. They are only for the programmer’s (or any reader’s) reference.

1.2.11 Choosing Mnemonic Variable Names


Choosing an appropriate name for variables in the program is always at stake.
Consider the following examples –
27
Notes for Programming in python(Open Elective - 21CS751)

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 –

Ex1. >>> avg sal=10000


SyntaxError: invalid syntax

Here, there is a space between the terms avg and sal, which is not allowed.

Ex2. >>> m=09


SyntaxError: invalid token

Python does not allow preceding zeros for numeric values.

Ex3. >>> basic=2000


>>> da=0.3*Basic
NameError: name 'Basic' is not defined
28
Notes for Programming in python(Open Elective - 21CS751)

As Python is case sensitive, basic is different from Basic.


29
Notes for Programming in python(Open Elective - 21CS751)

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.

You might also like