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

Python Lesson One

Uploaded by

Ankita Ghosh
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)
9 views

Python Lesson One

Uploaded by

Ankita Ghosh
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/ 46

The tools and techniques of programming in

Python
Lesson-1
Basics of Python

By
Prof. Dr. A.B.Chowdhury,HOD,CA

Techno India University, West Bengal,India


For any query,Email-Id:hod.ca@technoindiaeducation.com

September 30, 2024

By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)


The tools and techniques of programming in Python Lesson-1Basics
September 30,of2024
Python 1 / 46
Learning Objectives of this Lesson
This lesson aims to introduce the reader to the following concepts:
Concepts of Python Environment
Basic Advantages of Python
Python Execution System
The Python Character Set
Python Words
Data Types in Python
Python Variables,Constants and Literals
Unicode in Python
Python Operators
Python Statements
Installation of Python
Python as a Displayer
Python as a Desk Calculator
Python as a Scripting Language
By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)
The tools and techniques of programming in Python Lesson-1Basics
September 30,of2024
Python 2 / 46
Introduction
Python is a Scripting as well as High Level general-purpose program-
ming language.It may be termed as a multi-paradigm programming
platform because of its features for Functional Programming,Object-
Oriented as well as Structured Programming paradigms.It is a
dynamically-typed,easily understandable and highly readable language
developed by Guido van Rossum in the late 1980s at Centrum Wiskunde
& Informatica (CWI) which is a national research institute for mathemat-
ics and computer science in the Netherlands. The Programming Language
is a successor to the ABC language which owes its origin at the same
place. Guido van Rossum was inspired by the short, unique, and slightly
mysterious word Python perhaps from the name of the published scripts
“Monty Python’s Flying Circus”, a BBC comedy series from the 1970s
of which he was known to be an avid reader and a big fan of the show.
The implementation of Python was started in December 1989 and
finally the first version was introduced in 1991. Since its inception and
introduction of Version 1, the evolution of Python has reached up to Version
3.12.6 (September- 2024).
By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)
The tools and techniques of programming in Python Lesson-1Basics
September 30,of2024
Python 3 / 46
Introductory Ideas of Python
Python’s lead developer Van Rossum continued till July 12, 2018, when he declared
his ”permanent vacation” from his responsibilities as Python’s Benevolent Dic-
tator For Life.It is a title the Python community bestowed upon him to pay tribute
to his long-term commitment as the chief decision-maker of the project to create
the beautiful language.
Python Software Foundation (PSF) was formed in March 6, 2001, with head-
quarters in Delaware, United States, under his leadership with a view to promote,
protect, and advance the Python programming language as well as to support and
facilitate the growth of a diverse and international community of Python program-
mers.
Python can be run well in the following OS platforms:
Linux
Windows Vista and newer for Python 3.7, Windows XP and newer for
Python 2.7
FreeBSD 10 and newer
macOS Leopard (macOS 10.6, 2008) and newer
Android and iOS etc. mobile platforms.
Python can be easily downloaded from the website:
By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)
The tools and techniques of programming in Python Lesson-1Basics
September 30,of2024
Python 4 / 46
Introductory Ideas of Python
https://www.python.org/downloads/ for the desired platform.
Basic Advantages of Python.
Well-readability and ease of maintenance being formed of
well-structured and easily readable and understandable code.
High portability for being a scripting language and supported
interpreter in most of the modern OS platforms.
Good extensibility with libraries by having a large base of third party
library that enhances the functionality greatly.
Python Execution System
The Python execution system comprises the Python interpreter which is
required to execute the Python Code. The latest version of the interpreter
is : Python 3.9.6. The Python execution model may be depicted as shown
below:

Figure: Pictorial presentation of Python execution model

By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)


The tools and techniques of programming in Python Lesson-1Basics
September 30,of2024
Python 5 / 46
Introductory Ideas of Python–Contd.
The Python interpreter works in two phases:
Conversion phase from source code to byte code
Execution of byte code in the Python Virtual Machine(PVM)
The byte code is regenerated whenever any changes are performed in the
source code or the version of the interpreter is changed; otherwise, the same
byte code is utilized repeatedly for every execution of some source code and
thus the time required for translating the source code to byte code is saved.
Python Code Development
Python code can be developed either to run in a batch processing mode
or in an interactive mode. For batch processing mode we open a file write
down the requisite Python script. Having completed the writing, we first
save the script in a file with .py extension then we check the accuracy of
the syntax of the script. If the script is found to be correct, then we run
the script.For an interactive mode, we write the commands one at a time
at the command prompt: >>>, and then get it executed.

By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)


The tools and techniques of programming in Python Lesson-1Basics
September 30,of2024
Python 6 / 46
Introductory Ideas of Python–Contd.
For large and complex projects, we usually take the help of an IDE like
PyCharm for single-developer projects and Jupyter notebook for multi-
developer projects with a view to share codes.
The Python character set
The python character set comprises all the printable characters as well as
space available on the keyboard. Each of the characters alone or in com-
bination implies some meaning as will be explored through subsequent dis-
cussions.
Python Words
A sequence of characters from the python character set obeying certain rules
forms a python word. Python words are of two types:
Reserved words
User-defined words
The reserved words are known as keywords. They are defined as part of
the language with specific usages and cannot be used for any other purpose
except for the purpose for which they are defined. There are 36 keywords
in Python 3.9 which may vary slightly in course of time.
By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)
The tools and techniques of programming in Python Lesson-1Basics
September 30,of2024
Python 7 / 46
Introductory Ideas of Python–Contd.
The keywords are stated below:
The following ones are the Keywords in Python:
False, class, finally, is, return,, None, continue, for, lambda,
try, True, def, from, nonlocal, while, and, del, global, not,
with, as, elif, if, or, yield, peg parser , assert, else, im-
port, pass, ,async, await, break, except, in, raise
The user-defined words are those sets of characters used for naming different
entities in python required by the users such as variables, function names etc.
The user-defined words are called identifiers. They are so named because
they identify some entity uniquely. The following rules are to be followed
for naming identifiers:
1 Any combination of letters from the English alphabet, digits and
underscore can only be used.
2 The use of letters is case-sensitive. Once defined in a certain case,
must be followed strictly in its subsequent uses in the same form.
3 Digits cannot be used as the starting characters.
By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)
The tools and techniques of programming in Python Lesson-1Basics
September 30,of2024
Python 8 / 46
Introductory Ideas of Python–Data Types-Contd.
Data Types in Python
In general, the term data type implies the nature of data.It is an attribute that points
out what kind of value a fact possesses like numeric, alphabetic, alphanumeric etc.
Data types are means of classification of storage of the data depending on which
mathematical, relational or logical operations can be applied to the data without
causing an error. The data storage format that can contain a value of a specific
type or range of values clearly signifies a data type.
Data can be either of scalar data types or of compound data types. A
scalar data type contains only one data element, such as a number. Since such
types of data are not defined in terms of other data types, they are known as
primitive data types. A Composite or compound data type contains a collection
of data elements of single or multiple types i.e. the data may be homogeneous
or heterogeneous. For example, arrays are a compound data type which contains
a collection of elements of the same type. Other compound data types may be
structures, classes, vectors, lists, dictionaries, sets, data frames, records, files etc.
depending on the programming language being used. Those data types can contain
a collection of several other data types.

By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)


The tools and techniques of programming in Python Lesson-1Basics
September 30,of2024
Python 9 / 46
Introductory Ideas of Python–Data Types-Contd.
Compound types are commonly defined by programmers to collect data
together into a useful abstraction. For instance information about a fruit
may include the following:
Shape
Size
Colour
Flavour
Python supports the following data types:
The primitive data types in Python are:
Integer: represents whole numbers comprising digits 0 through 9. It
can be of any length depending on the capacity of the computer under
use. For instance,125,6789,12345678987654321 are integer data.
Floating-point number: represents fractional numbers with fixed or
variable precision. A floating point number can be accurate up to 15
digits after the decimal point. Hence, 5.75, 22/7 , 2.7e-3 etc. are
floating point numbers.
By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)
The tools and techniques of programming in Python Lesson-1Basics
September 30,of
2024
Python 10 / 46
Introductory Ideas of Python–Data Types-Contd.
Complex number : A number of the form : a+bj, is called a
complex number where, a is known as the real part and b ,the
imaginary part of the number. Thus, 2+3j, 5-2j, 3j etc. are complex
numbers.
String: Any sequence of Unicode characters from the Python
character set enclosed within quotation marks forms a string. The
quotation signs may either be single or double but not mixed.
Multiline strings are enclosed within triple quotes. Thus, “This is
Tapesh”, ‘That is Mahesh’ and ‘” My c.v. is described
below:. . . . . . ..”’, are all strings.
Bool: represents either True and False value which are known as
Boolean values.
The Composite data types in Python include the following ones:
List: represents an ordered sequence of homogeneous or
heterogeneous values separated by comma and enclosed within square
brackets. For instance, l=[5,7,6,’program’,8,9], defines a list with
the name l.
By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)
The tools and techniques of programming in Python Lesson-1Basics
September 30,of
2024
Python 11 / 46
Introductory Ideas of Python–Data Types-Contd.
A value in a list is referenced by using the name of the list followed by an index
within square brackets where the index can range from 0 to the number of elements
in the list; e.g. l[0], l[4] etc.
Tuple: represents an ordered unchangeable sequence of homogeneous or
heterogeneous values separated by comma and enclosed within parenthesis.
For instance, t=(3,2,9, ‘Data Science’,’R’) defines a Tuple with the
name t. An element of a list is pointed out by using the name of the list
followed by the index value within square brackets such as t[3] to indicate
the fourth element of the tuple t and t[0:3] to imply the first four elements
of the tuple.
Set: represents an unordered collection of unique items of unchangeable
data type which are separated by comma and enclosed within braces. For
instance, s={3,5,7,1,2,’Python”} defines a set with the name s. A set can
contain numbers, strings and tuples as its elements. It does not support
indexed referencing like lists and tuples; so, s[0] or s[2] are invalid undefined
references. It has been included in Python to support set operations in
particular. It discards any duplicate value included in the definition.

By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)


The tools and techniques of programming in Python Lesson-1Basics
September 30,of
2024
Python 12 / 46
Introductory Ideas of Python–Data Types-Contd.
Dictionary: represents unordered associations of Key: Value pairs
separated by comma and enclosed within braces. This data type is
used to map some key value to its corresponding defined value. For
instance, D={‘Fruit’:’Orange’, ‘Key’:55, ‘odour’:’pungent’}. The
referencing of the elements can then done as D[‘Fruit’], D[‘Key’] etc.
Bytes/byte array. It references file of any type.
As an object oriented language, Python also supports the following data
types:
Module
Function
Class
Method
File
These data types will be discussed elaborately in a separate section for the
sake of simplicity.
By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)
The tools and techniques of programming in Python Lesson-1Basics
September 30,of
2024
Python 13 / 46
Introductory Ideas of Python–Variables-Contd.
Python Variables, Constants and Literals.
Python Variables
A variable in python is an identifier used as a holding place of values of
the users. It may be defined as a named location in the main memory of
the computer for putting data values required for processing. It is so called
because its content can be changed (i.e. the content can vary) any time
in its lifespan in a program depending on requirement. For example, let us
consider the following statement:
for i in range(1,10):
print(i)
Here, i is a variable that takes values from 1 to 9 and prints each of them.
Python constants.
In Python, a constant is a specially named identifier the value of which
cannot be changed. We may name such constants as figurative constants,
because they are usually defined to represent some figures or values which
can otherwise be used directly without the declaration as a constant. They
are like variables or containers with static content.
By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)
The tools and techniques of programming in Python Lesson-1Basics
September 30,of
2024
Python 14 / 46
Introductory Ideas of Python–Constants-Contd.
Constants in Python act as rhetoric. For example, if we define:
PI=3.14
Acceleleration for Gravity=9.8
e= 2.718
We can make use of the words representing figures in a better understandable form.
As an instance, we may cite the statement required for finding out the perimeter
of a circle the radius of which is known as under:
Perimeter=2*PI*radius
If we define all the requisite constants in a separate module, say, constant.py and
then include this module in any main module by issuing the statement:
import constant
at the beginning of the main module, then, we can write the above statement in
the main module as follows:
Perimeter=2*constant.PI*radius.
This type of use of the figurative constants not only increases the readability
and understandability, but also the uniformity of the names of the constant values
throughout a project.
Constants should be named with letters in uppercase and words joined with
underscore to keep a distinction in naming; digits can also be used as per
stated naming rules for an identifier.
By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)
The tools and techniques of programming in Python Lesson-1Basics
September 30,of
2024
Python 15 / 46
Introductory Ideas of Python–Literals-Contd.
Literals in Python
In Python, a literal is an initial value assigned to a variable or a constant
to create an immutable data type for the variable or the constant. They
represent the possible choices in the primitive data types in Python. Python
supports 5 basic types of literals as stated below.
Number: which may either be integers, or long integers, or floating
point numbers or complex numbers.
String: which may represent a character or a sequence of characters
enclosed within quotes.
Boolean: represents a Boolean value
Special: represents the value None. It is used to define a variable
which is created.
Collections: represents list, tuple, set and dictionary collections.
In addition, a literal may be a Unicode literal.
Unicode in Python
We know that normal character strings can only come from a set of 256
characters.
By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)
The tools and techniques of programming in Python Lesson-1Basics
September 30,of
2024
Python 16 / 46
Introductory Ideas of Python–Literals-Contd.
There are many more than 256 characters in the real world (e.g., with
notations like β = 5 Å) which means there may be some string which can’t
be written using a simple (byte) string. To handle such situations, experts
have agreed on Unicode strings, which extends the character space from 0
to 0x10FFFF (about 1.1 million values, with some 110 thousand assigned
so far)
Unicode (https://www.unicode.org/) is a stipulation that aims to list
every character used by human languages in the world and to give each
character its own unique code. The Unicode specifications are regularly
revised and updated to add new languages, words and symbols.
However, Unicode representation presents a number of problems.
1 It’s not portable; so,different processors order the bytes differently.
2 Its use is a very wasteful of space. In most texts, the majority of the
code points are less than 127, or less than 255, so a lot of space is
occupied by 0x00 bytes. The string illustrated above takes 24 bytes
compared to the 6 bytes needed for an ASCII representation.
By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)
The tools and techniques of programming in Python Lesson-1Basics
September 30,of
2024
Python 17 / 46
Introductory Ideas of Python–Literals-Contd.
This results in unjustified use of storage space, particularly, increased re-
quirement of network bandwidth by a factor of 4 which has become unac-
ceptable.It’s not compatible with existing C functions such as strlen(), so
a new family of wide string functions would need to be developed.
Therefore, this encoding is not used very much, and people instead started
choosing other encoding techniques that are more efficient and convenient,
such as UTF-8. UTF-8 is one of the most commonly used encoding
methods, and Python usually uses it by default. UTF stands for “Unicode
Transformation Format”, and the ‘8’ means that 8-bit values are used in
the encoding. (There are also UTF-16 and UTF-32 encodings, but they
are less frequently used than UTF-8.) UTF-8 has been formulated with
the following rules:
1 If the code point is <128, it’s represented by the corresponding byte

value.
2 If the code point is ≥ 128, it’s turned into a sequence of two, three,

or four bytes, where each byte of the sequence is between 128 and
255. UTF-8 has several convenient properties as stated below:
By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)
The tools and techniques of programming in Python Lesson-1Basics
September 30,of
2024
Python 18 / 46
Introductory Ideas of Python–Literals-Contd.
1 It can handle any Unicode code point.
2 A Unicode string is turned into a sequence of bytes that contains embedded
zero bytes only where they represent the null character (U+0000). This
means that UTF-8 strings can be processed by C functions such as strcpy()
and sent through protocols that can’t handle zero bytes for anything other
than end-of-string markers.
3 A string of ASCII text is also valid UTF-8 text.
4 UTF-8 is fairly compact; the majority of commonly used characters can be
represented with one or two bytes.
5 If bytes are corrupted or lost, it’s possible to determine the start of the next
UTF-8-encoded code point and resynchronize. It’s also unlikely that random
8-bit data will look like valid UTF-8.
6 UTF-8 is a byte oriented encoding. The encoding specifies that each
character is represented by a specific sequence of one or more bytes. This
avoids the byte-ordering issues that can occur with integer and word
oriented encodings, like UTF-16 and UTF-32, where the sequence of bytes
varies depending on the hardware on which the string was encoded.
By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)
The tools and techniques of programming in Python Lesson-1Basics
September 30,of
2024
Python 19 / 46
Introductory Ideas of Python–Operators-Contd.
Since Python 3.0, the language’s str type contains Unicode characters, meaning
any string created using ”unicode rocks!”, ’unicode rocks!’, or the triple-quoted
string syntax is stored as Unicode.The default encoding for Python source code is
UTF-8, so we can simply include a Unicode character in a string literal.
Python operators.
An operator is a symbol or a combination of symbols that indicates an operation to
be performed upon one or more variables, constants or literals to generate some re-
sult. Three types of operators are usually supported by all programming languages.
They are:
Arithmetic operators for calculations,
Relational operators for comparisons and
Logical operators for basic logical operations of And, Or and Not.
Python supports six different types of operators. In addition to the three mentioned
above, the other operators are:
Bitwise operators
Membership operators and
Identity operators
By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)
The tools and techniques of programming in Python Lesson-1Basics
September 30,of
2024
Python 20 / 46
Introductory Ideas of Python–Operators-Contd.
We shall now study each type operator in detail.
Arithmetic Operators.
The following table illustrates the arithmetic operators available in Python.
Operator Name Functional Example
+ Addition (i) 2+3 yields 5 (ii)+7 implies positive seven
- Minus or Subtraction (i) 5-3 yields 2(ii)-8 implies negative eight
* Multiplication 5*3 yields 15
/ Division 10/4 yields 2.5
% Modulus or Modulo operator 5%2 yields 1
** Exponent 2**3 returns 8
// Floor division 5//2 returns 2

The following points may be noted for further clarification:


Addition generates the sum of two operands on either side of it as a binary operator. As a unary operator it shows a
positive value
Subtraction generates the difference of two operands on either side of it as a binary operator. As a unary operator it
shows a negative value.
Multiplication generates the product of two operands on either side of it as a binary operator.
Division generates the quotient of two operands on either side of it as a binary operator using left hand operand as the
dividend and the right hand operand as the divisor. The result is a floating point value.
Modulo operator performs an integer division on the left hand operand as the dividend by the right hand operand as the
divisor and returns the remainder of the operation.
Exponent acts as the power sign of the left hand operand(base) and raises its value to the power indicated by the right
hand operand (exponent) and returns the result.
Floor division performs an integer division on the left hand operand as the dividend by the right hand operand as the
divisor and returns the quotient of the operation.

By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)


The tools and techniques of programming in Python Lesson-1Basics
September 30,of
2024
Python 21 / 46
Introductory Ideas of Python–Operators-Contd.
Relational Operators in Python
The relational operators are all binary operators and they are used for com-
paring the values of the operands on their both sides. This is why they are
also called comparison or conditional operators. The relational operators in
Python are explained in the table below:
Operator Name Functional Example
== Equal to x= = y will hold True if they are equal, otherwise not
!= Not Equal to X!=0 will hold True if X is not equal to zero
> Greater than X>5 will hold True if X greater than 5
< Less than Y<10 will hold True if Y is less than 10.
>= Greater than or equal to X >=0 will hold True if X is nonnegative.
<= Less than or equal to Y <=x will hold True if Y is less than or equal to the value of x.

The following points may be noted for further clarification:


The compound operator Equal to is used to test whether the values of the operands on either side of it are same or
not. The comparison generates True if they are equal or False otherwise.
The compound operator Not Equal to is used to test whether the value of the operand on the left hand side of it is not
equal to that of the right hand side. The comparison generates True if they are unequal or False otherwise.
The operator Greater than is used to test whether the values of the operand on the left hand side of it is greater than
that of the right hand side or not. The comparison generates True if it is greater or False otherwise,
The operator Less than is used to test whether the value of the operand on the left hand side of it is less than that of
the right hand side or not. The comparison generates True if it is lesser or False otherwise,
The compound operator Greater than or equal to is used to test whether the value of the operand on the left hand side
of it is greater than or equal to that of the right hand side or not. The comparison generates True if it is greater or
False otherwise,
The compound operator Less than or equal to is used to test whether the value of the operand on the left hand side of
it is less than or equal to that of the right hand side or not. The comparison generates True if it is lesser or equal or
False otherwise,
By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)
The tools and techniques of programming in Python Lesson-1Basics
September 30,of
2024
Python 22 / 46
Introductory Ideas of Python–Operators-Contd.
Logical Operators in Python.
Python supports three logical operators as described below.
Operator Name Functional Example
and Logical AND a>b and b>c
or Logical OR a>b or b
not Logical NOT not(a>b and b>c)

The following points may be noted for further clarification:


The operator and is used to test the truth or falsity of the operands on its
both sides.Here, a will be the greatest among a, b and c if both the
relational expressions are found to be true. The expression: a and b will be
true if both contain non-zero values.
The operator or is used to test the truth or falsity of any one of the
operands on its both sides. The result will be true if any one happens to be
true a >b or b>c.Here, if either a>b or b>c is found to be true then the
expression becomes true, The expression: a or b will be true if any of them
contains non-zero values.
The operator not is used to reverse the logical state of its operand written
after it; e.g., not(a>b and b>c) will return false if a happens to be the
greatest.
By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)
The tools and techniques of programming in Python Lesson-1Basics
September 30,of
2024
Python 23 / 46
Introductory Ideas of Python–Operators-Contd.
Assignment Operators in Python
There are eight assignment operators in Python as explained below.
Operator Name Functional Example
= Assignment operator X=5,Y=x+3
+= Add AND hold X+=3, Here, with X=5,the value of X will become 8
-= Subtract AND hold X-=4 will store 4 in X with X=8
*= Multiply AND hold X*=3 will store 12 in X with the initial value 4 in X
/= Divide AND hold X/=4 will store 3.0 in X with the initial value 12 in X
%= Modulo Division AND hold X%=2 will store 1 in X with the initial value 3 in X
**= Exponentiation AND hold With X=2,X**=5, will store 32 in X
//= Integer Division AND hold X//=5 will store 6 in X with the initial value 32 in X
The following points may be noted for further clarification:
The Assignment operator is used to assign the value of the right hand side operand/expression to the operand at the
left hand side.
The Add AND hold operator adds the value of the left hand side operand to that of the right hand side and then stores
the result in the operand at the left hand side.
The Subtract AND hold operator subtracts the value of the left hand side operand to that of the right hand side and
then stores the result in the operand at the left hand side.
The Multiply AND hold operator multiplies the value of the left hand side operand to that of the right hand side and
then stores the result in the operand at the left hand side.
The Divide AND hold operator divides the value of the left hand side operand to that of the right hand side and then
stores the result in the operand at the left hand side.
The Divide AND hold operator obtains the remainder of the value of the left hand side operand to that of the right
hand side and then stores the result in the operand at the left hand side.
The Modulo Division AND hold operator obtains the remainder of the value of the left hand side operand to that of
the right hand side and then stores the result in the operand at the left hand side.
The Exponentiation AND hold operator obtains the exponential value of the operand at the left hand side to that of
the right hand side and then stores the result in the operand at the left hand side.
The Integer Division AND hold operator obtains the result of the integer division of the value at the left hand side
operand by that of the right hand side and then stores the result in the operand at the left hand side.
By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)
The tools and techniques of programming in Python Lesson-1Basics
September 30,of
2024
Python 24 / 46
Introductory Ideas of Python–Operators-Contd.
Bitwise Operators in Python.
Python supports six bitwise operators as described and illustrated below
with x=45 and y=33 i.e. in terms of bits stored in a byte, x=00101101 and
y=00100001.
Operator Name Functional Example
& Binary AND Z=x&y will store 00100001 in Z
| Binary OR Z=x | y will generate 00101101 in Z
ˆ Binary XOR Z=x ˆy will generate 00001100 in Z
∼ Binary 1’s complement ∼ x will generate 11010010
<< Binary left shift operator x<<3 will generate 01101000
>> Binary right shift operator X>>3 will generate 00000101

The following points may be noted for further clarification:


The binary AND operation is performed bit by bit to generate the resulting bit string. It may be recalled that in AND
operation, 00 will generate 0,01 will generate 0, but 11 will generate 1. i.e. the decimal value of Z in the example will
become 33.
The binary OR operation is performed bit by bit to the generate resulting bit string. It may be recalled that in OR
operation, 00 will generate 0, 01 will generate1, and 11 will generate 1. i.e the decimal of Z in the cited example will
become 45.
The binary XOR operation is performed bit by bit to generate the resulting bit string. It may be recalled that in XOR
operation, 00 will generate 0, 01 will generate1, and 11 will generate 0 i.e. the same bit in both the places will generate
0, otherwise 1.
The Binary 1’s complement operation just changes zeroes to ones and 1s to zeroes. It is a unary operator, whereas, all
the other operators in this group are binary operators.
The Binary left shift operator is used to shift the bits in the left hand side operand to the left by the number of bits
indicated by the right hand side operand. The shifted bits are lost forever and the right hand side vacant bit positions
are filled with zeroes.
This Binary right shift operator is used to shift the bits in the left hand side operand to the right by the number of bits
indicated by the right hand side operand. The shifted bits are lost forever and the left hand side vacant bit positions are
filled with zeroes.
By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)
The tools and techniques of programming in Python Lesson-1Basics
September 30,of
2024
Python 25 / 46
Introductory Ideas of Python–Operators-Contd.
Membership Operators in Python.
Python supports some data structures like a string that can hold a number of
values. The membership operators are used to test for the belongingness of a value
or variable in such a data structure. There are two such operators as illustrated
below.
The operator in is a binary operator that checks for the membership of the left
hand value/variable in the data structure mentioned at the left operand and then
returns true or false based on the occurrence or non-occurrence of the left hand
operand in the right hand operand. Example: X in y
The operator not in is a binary operator that checks for the membership of the
left hand value/variable in the data structure mentioned at the left operand and
then returns true or false based on the non-occurrence or occurrence of the left
hand operand in the right hand operand. Example: X not in y

Identity Operators in Python


There are two identity operators in Python,namely,
is
is not
By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)
The tools and techniques of programming in Python Lesson-1Basics
September 30,of
2024
Python 26 / 46
The Identity Operators in Python....Contd.
The ’is’ operator is required for comparing two Python objects to conclude
whether they are same or not.For instance,if we define:
a=5;b=5 at the Python prompt then we may write either of the following
Python statements:
if(a is b):print(”The objects are same”)
else:print(”The objects are different”)
OR
if(a is not b):print(”The object a and b are different”)
else:print(”The objects a and b are same”)
Whenever a Python object is created,a unique identity number for the
object is generated corresponding to the main memory location of the com-
puter where the object is stored.if two or more different objects contain
the same value,they are not stored in different memory locations but the
same memory location is referenced by different object names.The unique
identity number for any object is an integer which can be obtained by the
Python id() function. Thus, id(a) and id(b) in our preceding definition
will be the same integer. Hence, the expression a is b will be True.
By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)
The tools and techniques of programming in Python Lesson-1Basics
September 30,of
2024
Python 27 / 46
Precedence and associativity in Python Operators

The following table shows different Python Operators in order of the prece-
dence from the highest to the lowest:

Operator Name
** the binary operator for exponentiation
, + ,- Complement, unary plus and minus (method names for the last two are +@ and -@)
*, / ,% , // Assignment, division,Modulo and integer division operator
+, - the binary addition and subtraction operators
>>, << The Shift operators
& Bitwise ’AND’
ˆ, | Bitwise exclusive ‘OR’ and regular ‘OR’
<=, <, >, >= the relational operators
<>, ==, != the relational operators for testing equality
=, %=, /=, //=, -=, +=, *=, **= the assignment operators
in, not in membership operators
not, or, and logical operators

By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)


The tools and techniques of programming in Python Lesson-1Basics
September 30,of
2024
Python 28 / 46
Basics of Python Programming
Python Statements
A Python statement is a syntactically valid combination of Python words,
functions, literals, constants and operators that a Python Interpreter can
translate and execute. It can be an assignment statement, an input state-
ment, an output statement or a control statement spanning over a single
line or multiple lines. For example, some single line Python statements are
shown below:
1. X=55 , is a valid Python assignment statement. Its purpose is to store
some value in an identifier.
2. Name=input(“Enter a name”) , is an input statement which is used
to accept data in string form by showing the message shown in quotes.
As the message prompts the user to type in the desired input, it is known
as a ‘Prompt’. Here, input is the name of a Python function defined for
enabling the user for accepting inputs typed on the key keyboard until the
Enter/Return key is pressed. The entered data are then assigned to the
variable in the left hand side.

By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)


The tools and techniques of programming in Python Lesson-1Basics
September 30,of
2024
Python 29 / 46
Basics of Python Programming–Contd.
3. print(“The entered name is : “, Name), is a simple output statement
in Python. It shows the value stored in Name beside the text enclosed within
quotes.
Multi-line statements
A Python statement may span over multiple lines if the continued state-
ments are enclosed inside, parentheses, braces or square brackets to imply
wrapping. A substitute of this option is to enter a backslash(\) at the end
of each to imply continuation.
Indentation.
The term indentation implies the white space at the beginning of a line of
writing when it starts further away from the edge of the paper than all the
other lines. Leading white space (spaces and tabs) at the beginning of a
logical line of statement in Python is used to compute the indentation level
of the line, which in turn is used to determine the grouping of statements.
First, tabs are replaced (from left to right) by one to eight spaces such that
the total number of characters up to and including the replacement is a
multiple of eight (this is intended to be the same rule as used by Unix).
By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)
The tools and techniques of programming in Python Lesson-1Basics
September 30,of
2024
Python 30 / 46
Basics of Python Programming–Contd.
The total number of spaces preceding the first non-blank character then
determines the line’s indentation. Indentation cannot be split over multiple
physical lines using backslashes; the white space up to the first backslash
determines the indentation. The number of whitespaces (spaces and tabs)
in the indentation is not pre-defined, but all statements within a block must
be indented with the same amount of white spaces.
Comments in Python
A comment implies a note explaining, illustrating, or criticizing the meaning
of writing. In Python, comments are used to clarify the purpose of some
Python statement. It becomes helpful during reviewing or debugging a
program. It can also be used by some other programmer who is assigned
with the task of modifying a program in absence of the original programmer.
It also helps the original programmer to recapitulate the way in which some
complex task was handled during the development after a long time. It is
simply a text written in an easily understandable form obeying some rule(s)
of a programming language so that language translator does not try to
translate and execute it.
By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)
The tools and techniques of programming in Python Lesson-1Basics
September 30,of
2024
Python 31 / 46
Basics of Python Programming–Contd.
In Python, a comment is written starting with a Hash(#) sign. The hash
sign followed by the desired text can be written beside a Python statement
also or it can be written at the beginning of a line. For multiline comments,
each line must either be started with the hash sign or the whole of the
comment must be enclosed within triple quotes. For example,
# This is a comment
# We can write anything we like in a comment
X=5 # The number 5 is assigned to the variable X.
Installation of Python
To start working with Python 3.x, one needs to have access to the Python
interpreter. There are several common ways to accomplish this: Python can
be downloaded from the Python Software Foundation website at python.org.
Typically, that involves downloading the appropriate installer for the oper-
ating system running on the machine being used.
Some of the operating systems, particularly Linux, provide a package man-
ager that can be run to install Python.

By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)


The tools and techniques of programming in Python Lesson-1Basics
September 30,of
2024
Python 32 / 46
Basics of Python Programming–Contd.
The best way to install Python 3.x on macOS involves installing a package
manager called Homebrew. The relevant section in the tutorial explains
the process. For mobile operating systems like Android and iOS, apps that
provide a Python programming environment are available.
Alternatively, there are several websites that allow one to access a Python
interpreter online without installing anything on the computer at all.
Windows
The following steps may be followed for installing Python in an windows-
based system:
Step 1: The Python 3.x Installer is to be downloaded. A browser
window is to be opened and navigation is required to the Download
page for Windows at python.org. Underneath the heading at the top
that says Python Releases for Windows, clicking is required on the
link for the Latest Python 3 Release - Python 3.x. (As of this writing,
the latest is Python 3.7).Then the bottom is to be scrolled to select
either Windows x86-64 executable installer for 64-bit or Windows x86
executable installer for 32-bit.
By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)
The tools and techniques of programming in Python Lesson-1Basics
September 30,of
2024
Python 33 / 46
Basics of Python Programming–Contd.
Step 2: The Installer is to be executed next by double-clicking on the
downloaded file. It is required to check the box that says Add Python
3.x to PATH as shown to ensure that the interpreter will be placed in
the execution path.
Step 3. Install Now is to be clicked next. A few minutes later a
working Python 3 installation will become available on the system.
Linux
There is a very good chance that the Linux distribution has Python installed
already, but it probably won’t be the latest version, and it may be Python 2
instead of Python 3. To find out the version(s) installed, a terminal window
is required to be opened to try the following commands:
python –version
python2 –version
python3 –version
One or more of these commands should respond with a version, as below:
$ python3 –version
Python 3.6.5
By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)
The tools and techniques of programming in Python Lesson-1Basics
September 30,of
2024
Python 34 / 46
Basics of Python Programming–Contd.
If the version shown is Python 2.x.x or a version of Python 3 that is not the
latest, then the procedure for installing the latest version will depend on the
Linux distribution running on the system.
Ubuntu Depending on the version of the Ubuntu distribution, the Python
installation instructions vary. The local Ubuntu version can be determined
by running the following command: $ lsb release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 16.04.4 LTS
Release: 16.04
Codename: xenial
Depending on the version number displayed under Release in the console
output, the following instructions are to be followed:
Ubuntu 17.10, Ubuntu 18.04 (and above) come with Python 3.6 by default.
The command python3 will invoke it.
Ubuntu 16.10 and 17.04 do not come with Python 3.7 by default, but it is
in the Universe repository. It may be installed with the following commands:
By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)
The tools and techniques of programming in Python Lesson-1Basics
September 30,of
2024
Python 35 / 46
Basics of Python Programming–Contd.
$ sudo apt-get update
$ sudo apt-get install python3.7
The command python3 will invoke it.
Syntax and semantics in Python
The ‘syntax’, in the context of computer science, implies the rules, princi-
ples and processes that govern the structure of statements in a computer
language. So, it guides us in which sequence and form the words and sym-
bols can be written to make a valid statement that can be translated into
a pattern understandable by the computer to be used.
The word ‘semantics’ stands for the meaning implied by the words and
symbols in the syntax of a computer language.
So, a statement may be syntactically correct but incorrect semantically.
For example, in English the statement: he has a heavy account balance, is
syntactically correct; but, semantically incorrect. Similar is the case in any
computer programming language.
If a statement is found to be syntactically incorrect by the translator of
the language, the translator generates a ‘syntax error’.
By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)
The tools and techniques of programming in Python Lesson-1Basics
September 30,of
2024
Python 36 / 46
Basics of Python Programming–Contd.
A syntactically incorrect statement is not translated into machine-readable pat-
tern; but, if it is found to be syntactically correct, it is translated into a machine-
readable pattern. Next, when the machine tries to execute the command embedded
in the pattern, it becomes unable to do it and hence generates a runtime error called
logical error. So, any statement written in a computer programming language must
be accurate syntactically as well as semantically. As an example of a statement in
a programming language, we can store a space in a variable which is correct both
syntactically and semantically. Now, if we write to raise the power of the vari-
able to any value, say,5, the statement we write may like x followed by the power
sign(exponential operator) followed by 5 will be a syntactically valid statement but
semantically meaningless. and hence invalid that results into a logical error.
The following syntactic rules must be obeyed by a Python programmer:
Python is case sensitive. So, Salary and salary indicate different variables,
the starting characters being of different case. We should insist on lowercase
unless it becomes obligatory for some reserved words.
Path specification in Python must be done with forward slashes. So, the
window’s path C: files must be written in Python as
C:/folder/folder/Python files
By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)
The tools and techniques of programming in Python Lesson-1Basics
September 30,of
2024
Python 37 / 46
Basics of Python Programming–Contd.
A Python statement, also called a logical line, may span over a
number of physical lines which must follow the following rules:
1 A sequence of characters terminated by an end-of-line sequence (in
windows it is known as CR LF or return followed by a linefeed and in
Unix, it is called LF or linefeed) creates a physical line.
2 It must be terminated by a newline token.
3 It can contain blank lines provided the blank line comprises only spaces,
tabs, form feeds and possibly one or more comments which are ignored
by the Python interpreter
4 The statement shall obey the line continuation rules stated in 1.10.2
and 1.10.3 above.
Multiple Python statements on a single physical line must be
separated by a semicolon(;)
In an interactive interpreter session, an empty physical line must be
entered to terminate a multiline statement.
Python as a Scripting Language
When the Python IDLE shell is loaded, it shows the following screen: default
prompt:
By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)
The tools and techniques of programming in Python Lesson-1Basics
September 30,of
2024
Python 38 / 46
Python Console

Figure: Pictorial presentation of Python Console

The symbol >>>represents the default prompt of the Python IDLE shell
where IDLE stands for Integrated Development and Learning Environment.
Python can also be loaded without the IDLE by loading the file shown
as Python 3.12(64-bit) when the console is shown as depicted below for
running python as a scripting language.

Figure: Pictorial presentation of Python Prompt

By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)


The tools and techniques of programming in Python Lesson-1Basics
September 30,of
2024
Python 39 / 46
The Python Prompt
The prompt strings of python are defined in the sys module as ps1 and
ps2 and just like any other attribute we can change the values of sys.ps1
and sys.ps2 and the changes take effect immediately and as a result, the
prompt we see in the shell changes to the new value.
>>>import sys
>>>sys.ps1 = ”Python>”
Python>print(”Welcome to Python”)
The shows :
Welcome to Python
Python>print(round(3.14159, 2))
On execution of the above command,the following is shown:
3.14
and the Python prompt reappears to take the next command as under:
Python>
This is how Python can be used as a scripting language.

By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)


The tools and techniques of programming in Python Lesson-1Basics
September 30,of
2024
Python 40 / 46
Basics of Python Programming–Contd.
Python>
Python commands can be typed at this command prompt one by one to get the
output generated by the python interpreter. There are some in-built commands
and functions in Python that can be entered for instant execution. For example, if
we enter “copyright” as shown below,
>>>copyright
The following text is displayed:
Copyright (c) 2001-2019 Python Software Foundation.
All Rights Reserved.
Copyright (c) 2000 BeOpen.com.
All Rights Reserved.
Copyright (c) 1995-2001 Corporation for National Research Initiatives.
All Rights Reserved.
Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
All Rights Reserved.
If we enter credits, then it shows:
Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands for
supporting Python development. See www.python.org for more information. Now,
if we enter license(), then, it shows:
By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)
The tools and techniques of programming in Python Lesson-1Basics
September 30,of
2024
Python 41 / 46
Basics of Python Programming–Contd.
A. HISTORY OF THE SOFTWARE
==========================
Python was created in the early 1990s by Guido van Rossum at Stichting
Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands
as a successor of a language called ABC. Guido remains Python’s principal
author, although it includes many contributions from others.
In 1995, Guido continued his work on Python at the Corporation for National
Research Initiatives (CNRI, see http://www.cnri.reston.va.us) in Reston,
Virginia where he released several versions of the software.
In May 2000, Guido and the Python core development team moved to
BeOpen.com to form the BeOpen PythonLabs team. In October of the
same year, the PythonLabs team moved to Digital Creations, which be-
came Zope Corporation. In 2001, the Python Software Foundation (PSF,
see https://www.python.org/psf/) was formed, a non-profit organization
created specifically to own Python-related Intellectual Property.
Zope Corporation was a sponsoring member of the PSF.

By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)


The tools and techniques of programming in Python Lesson-1Basics
September 30,of
2024
Python 42 / 46
Basics of Python Programming–Contd.
All Python releases are Open Source (see http://www.opensource.org for the
Open Source Definition). Historically, most, but not all, Python Hit Return for
more, or q (and Return) to quit:
Next, if we enter help(), then it shows the following message first and then goes
to the help prompt to help with the explanation on any object:
>>>help()
Welcome to Python 3.7’s help utility!
If this is your first time using Python, you should definitely check out the tutorial
on the Internet at https://docs.python.org/3.7/tutorial/.
Enter the name of any module, keyword, or topic to get help on writing Python
programs and using Python modules. To quit this help utility and return to the
interpreter, just type ”quit”.
To get a list of available modules, keywords, symbols, or topics, type
”modules”, ”keywords”, ”symbols”, or ”topics”. Each module also comes with
a one-line summary of what it does; to list the modules whose name or summary
contain a given string such as ”spam”, type ”modules spam”.
help>

By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)


The tools and techniques of programming in Python Lesson-1Basics
September 30,of
2024
Python 43 / 46
Basics of Python Programming–Contd.
We can also enter help(any object name) to get help on the object.
Running Python as a Desk Calculator
Python shell can be used as a desk calculator to obtain the result of any
arithmetic expression instantly. The following examples illustrate the idea:
>>>2+3
5
>>>2-3
-1
>>>2*3
6
>>>2/3
0.6666666666666666
>>>3/2
1.5
>>>3%2
1

By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)


The tools and techniques of programming in Python Lesson-1Basics
September 30,of
2024
Python 44 / 46
Basics of Python Programming–Contd.
>>>3//2
1
>>>3**2
9
>>>9-(2*3-4*(6-3)/2)/2
9.0
In fact, the Python shell is able to interpret any Python statement as illus-
trated below:
>>>2<3
True
>>>2>3
False
>>>2&3
2
>>>not 2>3
True

By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)


The tools and techniques of programming in Python Lesson-1Basics
September 30,of
2024
Python 45 / 46
Basics of Python Programming–Contd.
>>>3>2 and 4<3
False
>>>a=5
>>>if a>2:
... print(a)
5
These are Interactive features of Python. In Python, any statement can be
run interactively. But, most often we shall like to run Python in the batch
mode in which all the statements required for obtaining some specific output
will be written together in a text file which can then be saved and executed
repeatedly.If we wish to create a text file containing a set of commands of
python to get some specific output, we have to load the Python IDLE as
shown above. We shall explore the procedural as well as object oriented
features of Python in the subsequent lessons using the File option of the
IDLE menu.This will enable us to use python in batch mode of execution.

By Prof. Dr. A.B.Chowdhury,HOD,CA (TIU,W.B.)


The tools and techniques of programming in Python Lesson-1Basics
September 30,of
2024
Python 46 / 46

You might also like