Unit 3
Unit 3
Python Interpreter
Python is a high level language. We know that computer understand only machine language or binary language
which is also known as low level language. The job to translate programming code written in high level
language to low level language is done with the help of Translator. The mostly used translators are compiler
and interpreter.
Working of Compiler
Compiler is a special type of software, it first checks the source code of the complete program for the syntax
errors, if no error found in the program code then the source code of the program is converted to the machine
code and finally the executive file of the program is created. The executive file can be executed by the CPU and
can produce desired result as per the program requirements.
Working of Interpreter
The Python interpreter first reads the command, then evaluates the command, prints the results, and then again
loops it back to read the next command and because of this only Python is known as REPL i.e., (Read, Evaluate,
Print, Loop).
Interpreter check the code of program line by line if no error is found it is converted into the machine code and
simultaneously gets executed by the CPU.
Python shell
Python provides a Python Shell, which is used to execute a single Python command and display the result.
The three arrow symbols >>> seen in the command prompt is known as the Shell. It is also known as python
REPL (Read, Evaluate, Print, Loop), where it reads the command, evaluates the command, prints the result, and
loop it back to read the next command again.
The Python REPL shows three arrow symbols >>> followed by a blinking cursor. Programmers type commands
at the >>> prompt then hit [ENTER] to see the results. Commands written into the python Shell/ REPL are read
by the interpreter and results of running the commands are evaluated, and then printed to the command window.
After output is printed, the >>> prompt appears on a new line. This process repeats over and over again in
continuous loop.
Python as a Calculator
Python can be used as a calculator to compute arithmetic operations like addition, subtraction, multiplication
and division. Python can also be used for trigonometric calculations and statistical calculations.
Simple calculations can be completed at the Python Prompt.
Let’s try some commands at the Python REPL :
Arithmetic calculation
>>> 5 + 3
8
>>> 8 - 1.5
6.5
>>>5000 / 2500
2.0 // always returns decimal value
>>> 5 * 2
10
>>> 3 ** 2 // the double asterisk symbol ** to raise a number to a power.
9
>>> 2 * 5
10
>>> _ + 1.5 + 1 // the answer of an operation Python saves as an underscore’ _’ to use in
12.5 // our next operation.
Trigonometry calculation
Trigonometry functions such as sine, cosine, and tangent can also be calculated using the Python REPL.
To use Python's trig functions, we need to introduce a new concept: importing modules.
In Python, there are many operations built into the language when the REPL starts. These include + , -, *, / as we saw in
the previous section. However, not all functions will work right away when Python starts.
Suppose we want to find the sin of an angle.
Try the following:
>>> sin(60)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
sin(60)
NameError: name 'sin' is not defined. Did you mean: 'bin'?
This error results because we have not told Python to include the sin function. The sin function is part of
the Python Standard Library. The Python Standard Library comes with every Python installation and includes
many functions, but not all of these functions are available to us when we start a new Python REPL session. To
use Python's sin function, first we have to import the sin function from the math module which is part of the
Python Standard Library.
So to find sin of an angle we have to use the following syntax:
from module import function
We can import more than one function at the same time using the following syntax:
from module import function1, function2, function3
Example:
Python Statement
Instructions that a Python interpreter can execute are called statements.
For example: a = 1, is an assignment statement.
if statement, for statement, while statement, etc. are other kinds of statements.
We can make a statement extend over multiple lines with the line continuation character (\).
For example:
a=1+2+3+\
4+5+6+\
7+8+9
This is an explicit line continuation.
In Python, line continuation is implied inside parentheses ( ), brackets [ ], and braces { }.
For instance, we can implement the above multi-line statement as:
a = (1 + 2 + 3 +
4+5+6+
7 + 8 + 9)
Here, the surrounding parentheses ( ) do the line continuation implicitly.
Same is the case with [ ] and { }.
For example:
colors = ['red',
'blue',
'green']
We can also put multiple statements in a single line using semicolons, as follows:
a = 1; b = 2; c = 3
Indentation
Indentation in Python refers to the (spaces and tabs) that are used at the beginning of a statement. The
statements with the same indentation belong to the same group.
Python indentation uses to define the block of the code.
The other programming languages such as C, C++, and Java use curly braces {}, whereas Python uses an
indentation.
Indentation uses at the beginning of the code and ends with the unintended line.
That same line indentation defines the block of the code (body of a function, loop, etc.)
for i in range(5):
print(i)
if(i == 3):
break
To indicate a block of code we indented each line of the block by the same whitespaces.
For Example
a=2
print(a)
if a==3 :
print(“hello world”)
print(“HELLO WORLD”)
else :
print(“ bye world”)
print(“ BYE WORLD”)
Python Comments
Python Interpreter ignores comments.
Comments are very important while writing a program.
Comments are for programmers to better understand a program.
For example,
We might forget the key details of the program we just wrote in a month's time. So taking the time to explain
these concepts in the form of comments is always fruitful.
These triple quotes are generally used for multi-line strings. But they can be used as a multi-line comment as
well.
Unless they are not docstrings, they do not generate any extra code.
"""This is also a
perfect example of
multi-line comments"""
Elements of Python
Identifier
Identifier is a name given to various programming elements such as a variable, function, class,
module or any other object.
Following are the rules to create an identifier.
The allowed characters are a-z, A-Z, 0-9 and underscore (_)
It should begin with an alphabet or underscore
It should not be a keyword
It is case sensitive
No blank spaces are allowed.
It can be of any size
Valid identifiers examples : si, rate_of_interest, student1, ageStudent
Invalid identifier examples: rate of interest, 1student, @age
Keywords
Keywords are the identifiers which have a specific meaning in python, there are 33 keywords in
python. These may vary from version to version.
Keywords are predefined reserved words used in Python programming that have special meaning to the compiler.
We cannot use a keyword as a variable name, function name, or any other identifier. They are used to define the
syntax and structure of the python language.
All the keywords except True, False and None are in lowercase and they must be
False None True and as assert beak class continue
def del elif else except finally for from global if
import in is lambda nonlocal not or pass raise
return try while with yield
To get complete list of all the keywords with examples open the link given bellow.
https://www.programiz.com/python-programming/keyword-list
Variables and Types
When we create a program, we often need to store values so that it can be used in a program.
We use variables to store data which can be manipulated by the computer program.
Every variable has:
Name and memory location where it is stored.
type or data type
value
Variable name:
1. Can be of any size
2. Have allowed characters, which are a-z, A-Z, 0-9 and underscore (_)
3. Should begin with an alphabet or underscore
4. Should not be a keyword
It is a good practice to follow these identifier naming conventions:
1. Variable name should be meaningful and short
2. Generally, they are written in lower case letters
Type or data type: specify the nature of variable i.e. what type of values can be stored in
that variable and what operations can be performed. We can check the type of the variable by using ‘type’
command
>>> type(variable_name)
Literals
A literal can be defined as data that is given in a variable or a constant that appear directly in a program and this
value does not change during the Program execution i.e. remains fixed.
Example:
Num=5
Principle_amount= 5000.00
Here 5 and 5000.00 are literals.
Python support the following literals
Numeric literals
Numeric Literals are immutable. Numeric literals can belong to four different numerical types:
Integers, Long Integers (exists in Python 2.x, deprecated in Python 3.x), Floating point and complex
String Literals
String literals can be formed by enclosing a text in either single or double quotes to create a string.
Boolean literals
A Boolean literal can have any of the two values: True or False.
Special Literals
Python contains one special literal i.e., none. None is used to specify to that field that is not created.
Collection Literals
Python provides the four types of literal collection such as :
List literals, Tuple literals, Dict literals, and Set literals.
Data Types
Various data types available in python are as follow:
1. Number
2. Sequence
i. String
ii. Lists
iii.Tuples
3. Boolean
4. Sets
5. Dictionaries
1. Number
Number data type stores Numerical Values. These are of three different types:
a) Integer & Long(Long is exists in Python 2.x, deprecated in Python 3.x)
b) Float/floating point
c) Complex
a) Integers are the whole numbers consisting of + or – sign like 100000, -99, 0, 17. While writing a large
integer value
e.g. age=19
salary=20000
b) Floating Point: Numbers with fractions or decimal point are called floating point numbers.
A floating point number will consist of sign (+,-) and a decimal sign(.)
e.g. temperature= -21.9,
growth_rate= 0.98333328
The floating point numbers can be represented in scientific notation such as
-2.0X 105 will be represented as -2.0e5
2.0X10-5 will be 2.0E-5
c) Complex: Complex number is made up of two floating point values, one each for real and imaginary part.
For accessing different parts of a variable x we will use x.real and x.imag.
Imaginary part of the number is represented by j instead of i, so 1+0j denotes zero imaginary part.
Example
>>> x = 1+0j
>>> print x.real, x.imag
1.0 0.0
2. None
This is special data type with single value. It is used to signify the absence of value/false in asituation. It is
represented by None.
3. Sequence
A sequence is an ordered collection of items, indexed by positive integers.
There are three types of sequence data type available in Python
Those are Strings, Lists & Tuples.
3.1 String: is an ordered sequence of letters/characters. They are enclosed in single quotes (‘’) or double
(“”).
Example
>>> a = 'Ram'
>>>a=”Ram”
3.2 Lists: List is also a sequence of values of any type. Values in the list are called elements /items. The
items of list are accessed with the help of index (index start from 0). List is enclosed in square brackets
([]).
Example
Student = [“Ajay”, 567, “CS”]
3.3 Tuples: Tuples are a sequence of values of any type, and are indexed by integers. They are
immutable i.e. we cannot change the value of items of tuples . Tuples are enclosed in ().
Example
Student = (“Ajay”, 567, “CS”)
4. Sets
Set is an unordered collection of values, of any type, with no duplicate entry. Sets are immutable.
Example
s = set ([1,2,3,4])
5. Dictionaries: Dictionaries store a key – value pairs, which are accessed using key. Dictionary is enclosed in
curly brackets.
Example
d = {1:'a', 2:'b', 3:'c'}
String
Python does not have a character data type, a single character is simply a string with a length of 1.
In computer programming, a string is a sequence of characters.
For example, ‘hello’ is a string containing a sequence of characters: ‘h’ ‘e’ ‘l’ ‘l’ and ‘o’.
Square brackets can be used to access elements of the string.
Creating a String
Strings in Python can be created using single quotes or double quotes or even triple quotes.
In Python, strings are immutable. That means the characters of a string cannot be changed.
Example:
message = 'Helo Everyone'
message[0] = 'E'
print(message)
Traceback (most recent call last):
File "C:/Users/TACT/Desktop/str2.py", line 2, in <module>
message[0] = 'E'
TypeError: 'str' object does not support item assignment
While accessing an index out of the range will cause an IndexError. Only Integers are allowed to be passed
as an index, float or other types that will cause a TypeError.
List
The list is a sequence data type which is used to store the collection of data.
Python Lists are similar to arrays in C. However, the list can contain data of different types. The items stored in
the list are separated with a comma (,) and enclosed within square brackets [].
We can use slice [:] operators to access the data of the list.
The concatenation operator (+) and repetition operator (*) works with the list in the same way as they were
working with the strings.
Lists in Python can be created by just placing the sequence inside the square brackets []
Consider the following example.
list1 = [1, "hi", "Python", 2]
#Checking type of given list
print(type(list1))
#Printing the list
print (list1)
# List slicing
print (list1[3:])
# List slicing
print (list1[0:2])
# List Concatenation using + operator
print (list1 + list1)
# List repetation using * operator
print (list1 * 3)
Tuple
The Tuple is a sequence data type which is used to store the collection of data.
A tuple is similar to the list in many ways. Like lists, tuples also contain the collection of the items of different
data types.
The items of the tuple are separated with a comma (,) and enclosed in parentheses ().
A tuple is a read-only data structure as we can't modify the size and value of the items of a tuple.
Let's see a simple example of the tuple.
tup = ("hi", "Python", 2)
# Checking type of tup
print (type(tup))
#Printing the tuple
print (tup)
# Tuple slicing
print (tup[1:])
print (tup[0:1])
# Tuple concatenation using + operator
print (tup + tup)
# Tuple repatation using * operator
print (tup * 3)
# Adding value to tup. It will throw an error.
Set
Python Set is the unordered collection of the data type. It is iterable, mutable (can modify after creation), and
has unique elements. In set, the order of the elements is undefined; it may return the changed sequence of the
element. The set is created by using a built-in function set(), or a sequence of elements is passed in the curly
braces and separated by the comma. It can contain various types of values. Consider the following example.
Dictionary
Dictionary is an unordered set of a key-value pair of items. It is like an associative array or a hash table where
each key stores a specific value. Key can hold any primitive data type, whereas value is an arbitrary Python
object.
The items in the dictionary are separated with the comma (,) and enclosed in the curly braces {}.
Consider the following example.
AND OR NOT
Bitwise Operators:
Bitwise operators are applied upon the bits.
Example:
Assignment Operators
Assignment operators are used to assign a value to the variable.
Membership Operator
Identity Operator
In other words, it’s a compact alternative to the common multiline if-else control flow statements in situations
when we only need to "switch" between two values. The ternary operator was introduced in Python 2.5.
The equivalent of a common if-else statement, in this case, would be the following:
if condition:
a
else:
b
Let’s look at a simple example:
>>> “Is true” if True else “Is false”
O/P: 'Is true'