Chapter 3
Introduction to Python
Python Programming Authors: Sridhar, Indumathi, and Hariharan
What is Python?
• A Python program is a script, which is vaguely a short program that
can be executed in Python interactive script.
• A statement is a line of code or command or instruction for
computers to perform initialize a number, perform some
computations, and do some control flow.
• A Function is a collection of statements that perform an intended
action and returns a Value.
• There are two types of statements: Simple and Compound. Simple
Statement: Performs a single simple task. For Ex., Expressions and
Assignment Statements.
Python Programming Authors: Sridhar, Indumathi, and Hariharan
• Compound Statements: This is a group of statements that spans multiple
lines and that control the execution of other statements of that program. •
For example, if, while and function are examples of the compound
statement.
• Example: Illustration of swapping of variables in Interactive
mode >>> x = 10
>>> y = 20
>>> t = x
>>> x = y
>>> y = t
>>> x, y
(20, 10)
>>>
Python Programming Authors: Sridhar, Indumathi, and Hariharan
Differences Between Python 2.x and 3.x
No Python 2.x Python 3.x
1. Old version of Python. New and updated language
2. The syntax of the print statement is The syntax of Python 3. x print is
print "hello" changed. Print is a function and it
should be
print("Hello").
3. Uses ASCII as default for string Uses UNICODE (UTF-8) to represent
representation. strings. So foreign languages and more
characters are supported.
4. Python 2.x is not forward compatible. Python 3.x is compatible compared
with Python 2.x.
5. The division is awkward in Python The division of 7 by 2 results in 3.5;
2.x. Division of 7/2 gives 3. hence, calculations are more
predictable.
Python Programming Authors: Sridhar, Indumathi, and Hariharan
Elements of Python Language
• The set of valid characters that a programming language can recognize is called the character set
of the language. Two types of character sets are
• Source Characters. ( Alphabets uppercase and lowercase, underscore, Special characters blank –
(+,-,*,/,^,~,%,!,&,|,(),{},[] ?’, ;, \), blank(“”))
• The Token is the smallest lexical unit in a program. The Types of tokens are listed below.
1. Identifiers
2. Keywords
3. Literals
4. Punctuations
Python Programming Authors: Sridhar, Indumathi, and Hariharan
Identifiers
• Identifiers- In Python, all variables, objects, and functions are given a
name. These names are called identifiers.
• Certain rules govern how a name can be given. The guidelines are
given below.
1) Every identifier must start with a letter or underscore ("_") 2) The
letter or underscore can be followed by any sequence of letters, digits,
or underscores.
3) Identifier cannot have a space
4) Identifiers are space sensitive. So the names celsius, Celsius, and
CELSIUS are different
Python Programming Authors: Sridhar, Indumathi, and Hariharan
Keywords
• Python has many inbuilt functions like input(). So Python does not
allow a program to use these function names liberally.
Keywords in Python:
and as assert del for False break class finally is
return None continue def del else if in global not
local except in raise with or else import True Float
Python Programming Authors: Sridhar, Indumathi, and Hariharan
Literals
• Literal is one way of specifying data values. These will be the values
that never modify while the program is executing.
• Literals in Python are numbers, text, or other fixed data, unlike
variables whose values change during the action.
• Some of the literals are listed below:
1. String literals
2. Numerical literals
3. Boolean literals
Python Programming Authors: Sridhar, Indumathi, and Hariharan
Literals string
literals
>>>
• String Literals
>>> # string literals
>>> # in single quote
>>> single_quote = ‘stringliterals’ >>> # in double quotes • Numerical Literals
>>> double_quotes = "stringliterals" >>> # multi-line string Example of handling constant as a variable
>>> multiline = ‘’’ string
... literals’’’
>>>
>>> print(single_quote)
stringliterals >>> PI = 3.14
>>> print(double_quotes) >>> TEMPERATURE = 9.0
stringliterals
>>> print(multiline)
Python Programming Authors: Sridhar, Indumathi, and Hariharan
Python Block Structure
Python Programming Authors:
Sridhar, Indumathi, and Hariharan
Illustration of Blocks in Python
x = 10 # Block 1 starts
if x% 2 == 0: # Block 1 continues
print("The number is even" ) # Block 2
else: # Block 1
print("The number is odd") # Block 2
print("Program Ends’) # Block 1 continues
Python Programming Authors: Sridhar, Indumathi, and Hariharan
Comments in Python
Block Comments illustration Inline comments illustration Multiple quotes illustration
>>> # This is a single-line >>> a = 10 # a is initialized to >>> # Multiline Quote
comment >>> # This is a block 10 >>> a = 10 # a is initialized >>> """
comment >>> # This is a block to 10 >>> b = 10 # b is ... This is a multiline quote
comment initialized to 10 >>> c = a + b # ... using Triple quotes
c=a+b ... """
>>> >>>
Python Programming Authors: Sridhar, Indumathi, and Hariharan
Variables and Assignment Statement
• In Python everything is an object, therefore a variable also is an
object. Thus, the rules for forming a variable are the same as the
identifiers.
Python
Programming Authors: Sridhar, Indumathi, and Hariharan
Assignment Statement
• One of the most critical statements in Python is the assignment
statement. The syntax of the introductory assignment statement is
given as follows:
• An alternative form of an assignment statement is to assign/compute
several values simultaneously. The syntax of simultaneous is given as
follows:
Python
Programming Authors: Sridhar, Indumathi, and Hariharan
Name Spaces
• Python interpreter uses a unique structure called namespace using
which it maintains a list of names and their associated values.
• Python updates the list when a new variable is created and it is
deleted in the namespace when the variable is deleted.
Python Programming Authors: Sridhar, Indumathi, and Hariharan
Python Objects
• In Python all are objects, variables, functions or even values.
An object is linked with three concepts-Identify, Zero or more names, and a set of attributes. 1.
Identify the Object
When the object is assigned to a variable, some memory address is allocated to the object. The
Python function to get the memory address is called id() function.
Python Programming Authors: Sridhar, Indumathi, and Hariharan
Data Types in Python
• A data type indicates what values a variable can hold, and an operator indicates the kind of
operations performed on the values.
• Python supports numbers and floating numbers. Classification of data types as follows,
Python Programming Authors: Sridhar, Indumathi, and Hariharan
Collection data Types
• Two main kinds of collection types are sequence and another type
called mapping.
• A sequence in an ordered collection of values. These sequence types
are string, list and tuples.
1) A string is a sequence of characters
2) A list is a sequence of values
3) A tuple is a sequence of values like lists but a tuple is immutable
Python Programming Authors: Sridhar, Indumathi, and Hariharan
The string is an example of a sequence collection data type. It is a collection of characters delimited
by single, double, and triple quotes. It can include letters, numbers, punctuations, and many special/
unprintable characters.
Python Programming Authors: Sridhar, Indumathi, and Hariharan
Lists
A list is a set of items or elements. All these items are separated by commas and enclosed within square brackets.
In all aspects, lists are similar to arrays but can have non-homogenous content. To create a list, one can just
enclose the sequence of objects in square brackets.
Illustration of Slicing in
Lists
Python Programming Authors: Sridhar, Indumathi, and Hariharan
Tuples
• A tuple is a collection of items or elements. A tuple is also a sort of list
but the main difference is that tuples are immutable compared to
mutable lists.
• The tuple items are enclosed in round brackets and separated by a
comma. The empty tuple is (). The tuple with a single element is called
a singleton.
• Some of the examples are,
Python Programming Authors: Sridhar, Indumathi, and Hariharan
Dictionary in the form of keys and values A dictionary is
called a mapping type.
• A dictionary is an unordered collection of items
more elements with no duplicates. As in
• A map type consists of a set of element pairs.
mathematics, a set is an unordered collection
The first element of the pair is called a key, and
of items with no duplicate items that use curly
the second element is called a value.
braces for sets- {}.
• To find the corresponding equivalent values,
• The set is immutable and unique.
one can search for a key or value.
Sets/Frozen Sets
• A set is an unordered collection of zero or
Python Programming Authors: Sridhar, Indumathi, and Hariharan
Operations
• One of the other attributes of the objects is operations. Operations
are performed on operands. For example, in the expression, ‘a+b’, ‘a’
and ‘b’ are called operands, and ‘+’ is the operator. Operations depend
on the data type.
Python
Programming Authors: Sridhar, Indumathi, and Hariharan
The classification of operators
Python Programming Authors: Sridhar, Indumathi, and Hariharan
Type Conversions
• There are certain limitations to the data types. For example, one cannot do 'Hello"+4, because one
is a string type and another is an integer. For example, input() returns a string, so one needs to
convert that to an integer to perform operators. This concept is called type conversion.
• There are two types of data conversion. They are
1) Implicit conversion (or Type Coercion)
2) Explicit conversion (or Type Casting)
Implicit conversion
Python implicitly converts a data type during compilation or runtime. Python automatically converts an
integer to a floating point to preserve the fractional part.
Python Programming Authors: Sridhar, Indumathi, and Hariharan
Explicit conversion
The explicit conversion of a value from one data type into another data type is called typecasting.
There are many built-in functions available for type conversion
Python Programming Authors: Sridhar, Indumathi,
and Hariharan
Simple input/output Statements
• Reading Numbers from the Keyboard. – one can read the input from
the console using the input() function.
• The syntax of the statement is given as
• One can also accept a string using the input() function. The syntax is
given as
Python Programming Authors: Sridhar, Indumathi, and Hariharan
Illustration of Input Illustration of Type Error Illustration of input Illustration of eval
statement statement
>>> str = >>> a = input("Enter >>> a = >>> x =
input("Enter Number ") int(input("Enter eval(input("Enter the
String") Enter Number 10 Number ")) number"))
Enter String Hello >>> a = a + 10 Enter Number 10 Enter the number10
>>> str Traceback (most >>> a = a + 10 >>> x = x + 10
‘Hello’ recent call last): >>> print(a) >>> print(x)
File "<stdin>", line 1, 20 20
in <module>
TypeError: can only
concatenate str (not
"int") to str
>>>
Python Programming Authors: Sridhar, Indumathi, and Hariharan
Print() statement
The contents can be displayed on the screen using a print statement. A python print statement converts all python
objects into a string and writes it on in general i/o stream.
• Illustration of Print
Python Programming Authors: Sridhar, Indumathi, and Hariharan
Formatting using Print Statement
Many times a simple printing of values is not sufficient. Many projects may require fancy printing as per the
requirements. It is called formatting. All variables and constants need to be converted to string type for printing
purposes.
• Built-in Methods
Python Programming Authors: Sridhar, Indumathi, and Hariharan
String Formatting
• String formatting is the second way of formatting; here, there will be a format string and arguments.
• The format of this string formatting is given as
• Formatting Illustration
Python Programming Authors: Sridhar, Indumathi, and Hariharan
Built-in functions
Python Programming Authors:
Sridhar, Indumathi, and Hariharan