2 Introduction To Python1
2 Introduction To Python1
2 Introduction To Python1
The language used to specify the set of instructions to the computer is called
Programming Language.
Computers understand the language of 0’s and 1’s which is called machine language or
low level language.
However, it is difficult for human to write or comprehend instruction using 0’s and 1’s.
This led to the advent of high level programming languages like Python, Visual Basic, PHP,
Java that are easier to manage by human but not directly understood by the computer.
Language translators like compilers and interpreters are needed to translate the source
code into machine language.
Introduction to Python
An interpreter processes the program one statement at a time, alternately reading
statements, translating it and performing computations. It continues translating and
executing the program until the first error is found, in which case it stops.
A compiler translates the entire source code, as a whole, into object code. After scanning
the whole program, it generates the error messages.
Python uses an interpreter to convert its instructions into machine language, so that it
can be understood by the computer.
The Python interpreter processes the program one statement at a time, alternately
reading statements and performing computations.
Introduction to Python
Background of Python
⚫ Python was developed by Guido van Rossum in the late eighties and
early nineties at the National Research Institute for Mathematics and
Computer Science in the Netherlands.
Downloading Python
The latest 3.x version of python is available on the official website of Python:
http://www.python.org/
Introduction to Python
Working with Python
To write and run a Python program, we need to have Python interpreter installed on our
computer or we can use any online python interpreter. A sample screen of Python
interpreter is shown below:
In the above screen, the >>> is the Python prompt, which indicates that it is ready to take
instructions. We can type commands or statements on this prompt to execute them using
Python interpreter.
Introduction to Python
Execution Modes
There are two ways to use the Python interpreter:
❑Interactive mode
❑Script mode.
To work in the interactive mode, we can simply type a Python statement on the
>>> prompt directly. As soon as we press enter, the interpreter displays the
result(s).
Working in the interactive mode is convenient for testing single line code for
instant execution. But in interactive mode, we cannot save the statements for
future use and we have to retype the statements to re-use them.
Introduction to Python
Script mode :
In script mode, we can type a Python program in a file, save it and then use the
interpreter to execute it.
For example, If the name of the file is prog71.py, you would need to type
python3 prog71.py to execute it.
Python Keywords
Keywords are reserved words. Each keyword has a specific meaning to the Python interpreter. As
Python is case sensitive, keywords must be written exactly as given below. The following is a list of
reserved words, or keywords in Python:
as elif if or yield
❑The name should begin with an uppercase or a lowercase alphabet or an underscore sign (_).
This is followed by characters a-z, A-Z, 0-9 or underscore (_).
❑It can be of any length. (However, it is preferred to keep it short and meaningful).
❑It should not be a keyword/ reserved word.
❑Python does not allow punctuation characters such as @, $, and % within identifiers.
❑ Python is a case sensitive programming language. Fanpower and fanpower are two different
identifiers in Python.
❑Valid identifiers: abc, A13, A123_x
❑Invalid identifiers 123, -asd,&asd
Example
To find average of three students marks, it is suggested to choose identifier names as
marks1, marks2, marks3 and avg rather than a, b, c,... or A,B,C, …
avg = marks1 + marks2 + marks3
Similarly, to calculate the area of a rectangle, we may use identifier names such as area,
length, breadth.
area = length * breadth
PRINT: to display the content
⚫ print ('asd'+'def')
⚫ print ('asd:'*3,end='') #next print on same line
⚫ v='asd$#@'; print ('v is : ',v) #multiple statement seperated by ;
⚫ OUTPUT:
⚫ asddef
⚫ asd:asd:asd:v is : asd$#@
\newline Ignored
\\ Backslash (\)
\' Single quote (')
\" Double quote (")
\a ASCII Bell (BEL)
\b ASCII Backspace (BS)
\f ASCII Formfeed (FF)
\n ASCII Linefeed (LF)
\r ASCII Carriage Return (CR)
Value of a variable can be a string (e.g., ‘b’, ‘Global Citizen’), numeric (e.g., 345) or any
combination of alphanumeric characters.
In Python we can use an assignment statement to create new variables and assign specific
values to them.
gender = 'M'
message = "Keep Smiling"
price = 987.9
Wherever a variable name occurs in an expression, the interpreter replaces it with the
value of that particular variable.
print(“your gender is”, gender, “and you have to pay Rs. “, price, “. Have a good day”,
message)
Your gender is M and you have to pay Rs. 987.9. Have a good day Keep Smiling.
Variables
⚫ counter = 100 # An integer assignment
⚫ miles = 1000.0 # A floating point
⚫ name = "John" # A string
Example:
# Variable amount is the total spending on grocery
amount = 3400
# totalMarks is sum of marks in all the tests of Mathematics
totalMarks = test1 + test2 + finalTest
Use of three single quote in the beginning and at the end of multiple lines
comments.
'''not to be executed
... print not to display
... just for documentation'''
Program structure
⚫ Lines and indentations are used to build program
⚫ Lines at same level of indentation indicate one block
⚫ Multiple nested blocks are at same indentation level e.g.
⚫ Each statement in program is end by EOLN (enter)
⚫ In case line is too long then it is continued using back slash character
if True:
print "True"
else:
print "False"
total = item_one + \
item_two + \
item_three
Data types
Every value belongs to a specific data type in Python.
Data type identifies
❑ the type of data a variable can hold and
❑ the operations that can be performed on that data.
The following chart enlists the data types available in Python.
Data types
Type/ Class Description Examples
int integer numbers (with no decimal place) -12,-3,0,125, 2
float real numbers -2.04, 4.0, 14.23,
complex complex numbers 3 + 4i, 2 - 2i
>>>b =- 1210
>>>type(b) <class 'int'>
>>>t1 = True
>>>type(t1) <class 'bool'>
>>>f2 = -1921.9
>>>type(f2) <class 'float'>
f5 = -9.8*10**2
print(f5, type(f5)) -980.0000000000001 <class 'float'>
c2 = -3+7.2j
print(c2, type(c2)) (-3+7.2j) <class 'complex'>
Sequence
A Python sequence is an ordered collection of items, indexed by integers.
Three types of sequence data types are available in Python are
Strings, Lists and Tuples.
String
String is a group of characters.
These characters may be alphabets, digits or special characters including spaces.
String values are enclosed either in single quotation marks (e.g. ‘Hello’) or in double quotation marks
(e.g. “Hello”).
The quotes are not a part of the string, they are used to mark the beginning and end of the string for
the interpreter.
Example
>>> s1 = 'Hello Friend'
>>> s2 = "452"
We cannot perform numerical operations on strings, even when the strings contains digits in it “452”
as shown above.
Sequence
List
List is a sequence of items separated by commas and enclosed in square brackets [ ].
Example
>>> list1 = [5, 3.4, "New Delhi", "20C", 45] # To create a list
>>> print(list1) # print the elements of the list list1
[5, 3.4, 'New Delhi', '20C', 45]
Tuple
Tuple is a sequence of items separated by commas and enclosed in parenthesis ( ).
This is unlike list, where values are enclosed in parenthesis [ ].
Once created, we cannot change the tuple.
Example
>>> t1 = (10, 20, "Apple", 3.4, 'a') # create a tuple t1
>>> print(t1) # print the elements of the tuple t1
(10, 20, "Apple", 3.4, 'a')
Sets
Sets
Set is an unordered collection of items separated by commas and enclosed in curly brackets { }.
They are similar to lists but cannot have duplicate entries.
Like tuples sets cannot be changed.
Example
>>> s1 = {10,20,3.14, "New Delhi"} # create a set
>>> print(type(s1))
<class 'set'>
>>> print(s1)
{'New Delhi', 10, 3.14, 20}
>>> s2 = {1,2,1,3}
>>> print(s2)
{1, 2, 3} # duplicate elements are not included in set
Example
>>> myVar = None
>>> print(type(myVar))
<class 'NoneType'>
>>> print(myVar)
None
Dictionary
Mapping is an unordered data type in Python.
Currently there is only one standard mapping data type in Python called dictionary.
Dictionary
Dictionary in Python holds data items in key-value pairs.
Dictionary is enclosed in curly brackets { }.
Dictionaries permit faster access of data.
The key:value pairs of a dictionary can be accessed using the key.
Every key is separated from its value using a colon (:) sign.
The keys are usually strings and their values can be any data type.
In order to access any value in the dictionary, we have to specify its key in square brackets [ ].
Example
#create a dictionary
>>> dict1 = {'Fruit':'Apple', 'Climate':'Cold', 'Price(kg)':120}
>>> print(dict1)
{'Fruit': 'Apple', 'Climate': 'Cold', 'Price(kg)': 120}
Mutable and Immutable Data Types
Variables whose value can be changed after they are created are called mutable.
The value of some variables cannot be changed once they are created. Such variables are called
immutable.
As the value of an immutable variable cannot be changed when an attempt is made to update its
value; the old variable is destroyed and a new variable is created by the same name in memory.
Immutable Data type : Integers, Float, Boolean, Complex, Strings, Tuples, Sets
Mutable Data type : Lists, Dictionary
What happens when an attempt is made to update the value of a mutable variable ?
>>>a = 300
This statement will create an object with value as 300 referenced by the identifier a.
>>>b = a
will make b refer to the value 300, also being referred to by a, stored at memory location number say
1000. So, a shares the referenced location with b.
In this manner Python makes assignment efficient by copying only the reference, and not the data.
>>> a = b + 100
Links the variable a to a new object stored at memory location number say 2200 having a value 400.
As a is an integer- an immutable type, it has been rebuilt.
Mutable and Immutable Data Types
Mutable and Immutable Data Types
Variables whose value can be changed after they are created are called mutable.
The value of some variables cannot be changed once they are created. Such variables are called
immutable.
As the value of an immutable variable cannot be changed when an attempt is made to update its
value; the old variable is destroyed and a new variable is created by the same name in memory.
Immutable Data type : Integers, Float, Boolean, Complex, Strings, Tuples, Sets
Mutable Data type : Lists, Dictionary
What happens when an attempt is made to update the value of a mutable variable ?
>>>a = 300
This statement will create an object with value as 300 referenced by the identifier a.
>>>b = a
will make b refer to the value 300, also being referred to by a, stored at memory location number say
1000. So, a shares the referenced location with b.
In this manner Python makes assignment efficient by copying only the reference, and not the data.
>>> a = b + 100
Links the variable a to a new object stored at memory location number say 2200 having a value 400.
As a is an integer- an immutable type, it has been rebuilt.
Operators
⚫ Operators are the constructs which can
manipulate the value of operands.
% Modulus Divides left hand operand by right hand operand and b%a=0
returns remainder
>>> p = "Hello"
>>> q = "India"
>>> p + q
‘HelloIndia’
>>> q = 'India'
>>> q * 2
'IndiaIndia'
Relational Operators
Operator Description Example
> If the value of left operand is greater than the value (a > b) is not
of right operand, then condition becomes true. true.
< If the value of left operand is less than the value of (a < b) is true.
right operand, then condition becomes true.
>= If the value of left operand is greater than or equal (a >= b) is not
to the value of right operand, then condition true.
becomes true.
<= If the value of left operand is less than or equal to (a <= b) is true.
the value of right operand, then condition becomes
true.
Logical Operators
Logical Description Example
Operator
and Logical If both the operands are true then condition (a and b) is
AND becomes true. true.
not Logical Used to reverse the logical state of its operand. Not(a and
NOT b) is false.
Given a = 60; and b = 13; with binary format
a = 0011 1100
b = 0000 1101
& Binary AND Operator copies a bit to the result if it (a & b) (means 0000 1100)
exists in both operands
~ Binary Ones It is unary and has the effect of 'flipping' (~a ) = -61 (means 1100
Complement bits. 0011 in 2's complement
form due to a signed binary
number.
<< Binary Left The left operands value is moved left by a << 2= 240 (means 1111
Shift the number of bits specified by the right 0000)
operand.
>> Binary Right The left operands value is moved right by a >>2 = 15 (means 0000
Shift the number of bits specified by the right 1111)
operand.
Decimal to binary numbers
⚫ Divide the quotient by 2 recursively till quotient is
0 and store remainder
2 25
12 1
6 0
Note bits from
3 0 bottom to top
1 1
0 1
Quotient Remainder
4 3 2 1 0
⚫ 1x2 +1x2 +0x2 +0x2 +1x2
⚫ =16 + 8 + 0 + 0 + 1
⚫ =25
Python function to get binary or
decimal
⚫ Decimal to binary
− Bin(24) -> 11000
⚫ Binary to decimal
− 0b11000 -> 24
Bitwise operations
⚫ A=10 binary equivalent A=1010
⚫ B=12 binary equivalent B=1100
⚫
+= Add AND It adds right operand to the left operand and c += a -> c = c + a
assign the result to left operand
/= Divide AND It divides left operand with the right operand and c /= a -> c = c / a
assign the result to left operand
Decreasing order
* / % // Multiply, divide, modulo and floor division
+- Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'
^| Bitwise exclusive `OR' and regular `OR'
<= < > >= Comparison operators
<> == != Equality operators
(= ) %= /= //= -= Assignment operators
+= *= **=
is, is not Identity operators
in, not in Membership operators
Not , or, and Logical operators
Examples on operators
⚫ Given x=30; y=15; z=5 evaluate following
Expression Result Expression Result
x/y+z 7 x !=y TRUE
x+y*z**2 405 x > y and y > z TRUE
The two operators have equal precedence. Thus, the first operator i.e. subtraction be
applied before the second operator i.e. addition
= (20 – 30) + 40 # Step 1
= 10 + 40 # Step 2
= 50 # Step 3
How will Python evaluate the following expression written using parenthesis?
(20 + 30) * 40
i Serial_no. v Total_Marks
ii 1st_Room vi total-Marks
Q4. Which data type will you use to represent the following data values and why?
x=4
y=x+1
x=2
print x, y
x, y = 2, 6
x, y = y, x + 2
print x, y
a, b = 2, 3
c, b = a, c + 1
print a, b, c
Q7. Give the output of the following when a= 4, b=3, c= 2
a += b + c
print (a)
a = a ** (b + c)
print (a)
a **= b + c
print (a)
a = ‘5’ + ‘5’
print(a)
print(4.00/(2.0+2.0))
a = 2+9*((3*12)-8)/10
print (a)
a = 24 // 4 // 2
print (a)
Q7. Give the output of the following when a= 4, b=3, c= 2
a = float(10)
print (a)
a = int(‘3.14’)
print (a)
print('Bye' == 'BYE')