2 Introduction To Python1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 49

Introduction to Python

An ordered set of instructions to be executed by a computer to carry out a specific task is


called a Program, and

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.

A program written in a high-level language is called source code.

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.

⚫ Python is derived from many other languages, including ABC, Modula-


3, C, C++, Algol-68, SmallTalk, and Unix shell and other scripting
languages.

⚫ Python is copyrighted. Like Perl, Python source code is now available


under the GNU General Public License (GPL).
Introduction to Python
Features of Python
➢Python is a High Level Language. It is Free and Open Source.
➢It is interpreted language as python programs are executed by an interpreter.
Unlike compiler, an Interpreter executes statement line-by-line.
➢Easy to learn as it has clearly defined syntax and relatively simple structure.
➢Python is portable and platform independent as it can run on various operating
systems and hardware platforms.
➢Python has a rich library of predefined functions.
➢Python is also helpful in web development. Many popular web services and
applications are built using Python.
➢Instead of curly braces, Python uses indentation for blocks and nested blocks.
➢It is Interactive scripting languauge
➢ It is Object-oriented
➢It is Case-sensitive

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.

Interactive mode allows execution of individual statement instantaneously.


Whereas,
Script mode allows us to write more than one instruction together in a file called
Python source code file that can be executed.

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.

Python scripts have names that end with “.py”.


By default, the python scripts are saved in the Python folder.

To execute the script, we can either


❑Type the file name at the prompt, or
❑While working in the script mode, after Saving the file, click [Run]>>[Run Module]
in the menu.

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:

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

assert else import pass

break except in raise


Identifiers
A name given by the user while writing a program is called an identifier.
The rules for naming an identifier in Python are as follows:

❑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 (“hello”) gives hello

⚫ print (“hello:”+”good”) gives hello:good

⚫ print (2+3) gives 5

⚫ print ('asd:'*3) gives asd:asd:asd:

⚫ v='asd$#@'; print ('v is : ',v) gives v is : asd$#@

⚫ 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$#@

⚫ Semicolon (;) in python is used to write multiple statements on one line


⚫ Escape character \ is Used to ignore it usual meaning
Escape Sequence Meaning

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

\t ASCII Horizontal Tab (TAB)

\v ASCII Vertical Tab (VT)


\ooo ASCII character with octal value ooo

\xhh... ASCII character with hex value hh...


Variables
A variable in a program is uniquely identified by a name (identifier).
Variable in Python refers to an object- an item that is stored in the memory.

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

Statement ⚫ print (counter) print (counter,miles,name) print(counter,'\n', miles,'\n', name)


s: ⚫ print (miles)
⚫ print (name)
Output: 100 100 1000.0 John 100
1000.0 1000.0
John John

⚫ Multiple assignment in a statement

− a = b = c = 1 #a, b, c of integer type


− a,b,c = 1,2,"john" #a, b of type integer and c of type string
Comments
Comments are used to put a remark or a note in between codes.
Comments are not executed by interpreter.
In Python, a comment starts with # (hash sign).
Everything following the # till the end of that line is treated as a comment and the
interpreter simply ignores it.

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

Boolean data types (bool) are a subtype of integers.


It is a unique data type, consisting of two constants, True and False.
Boolean true value is non-zero, non-null and non-empty. Boolean false is the value zero.
Data types
Python Statements Output
>>>a = 10
>>>type(a) <class 'int'>

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

>>> s3 = set([1,2,4,6]) #create a set from a list


>>> print(s3)
{1, 2, 4, 6}
None
None is special data type with a single value.
It is used to signify the absence of value in a situation.
None supports no special operations. None is neither False nor 0 (zero).

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.

⚫ A=5 +6 # 5, 6 are operands and + operator

⚫ Python language supports the following types of


operators
− Arithmetic Operators
− Comparison (Relational) Operators
− Assignment Operators
− Logical Operators
− Bitwise Operators
− Membership Operators
− Identity Operators
Arithmetic Operators

Operator Description Example

+ Addition Adds values on either side of the operator. a + b = 30

- Subtraction Subtracts right hand operand from left hand a – b = -10


operand.

* Multiplication Multiplies values on either side of the operator a * b = 200

/ Division Divides left hand operand by right hand operand b/a=2

% Modulus Divides left hand operand by right hand operand and b%a=0
returns remainder

** Exponent Performs exponential (power) calculation on a**b =10 to


operators the power
20

// Floor divison To get truncated quotient 4//3=1


-4//3=-2
Addition Concatenates the two items on either side of the operator.

>>> p = "Hello"
>>> q = "India"
>>> p + q
‘HelloIndia’

Multiplication Repeats the item on left side of the operator.

>>> q = 'India'
>>> q * 2
'IndiaIndia'
Relational Operators
Operator Description Example

== If the values of two operands are equal, then the (a == b) is not


condition becomes true. true.
!= If values of two operands are not equal, then
condition becomes true.

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

or Logical OR If any of the two operands are non-zero then (a or b) is


condition 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

Operator Description Example

& Binary AND Operator copies a bit to the result if it (a & b) (means 0000 1100)
exists in both operands

| Binary OR It copies a bit if it exists in either operand. (a | b) = 61 (means 0011


1101)
^ Binary XOR It copies the bit if it is set in one operand (a ^ b) = 49 (means 0011
but not both. 0001)

~ 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

Binary equivalent of 25 is 11001


Binary to Decimal Number
⚫ Given Binary Number is 11001
⚫ Method is to multiply binary digit with 2 with
exponent (its position-1)
⚫ Start from Least significant digit to Most
significant digit

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

Bitwise operator Binary Decimal Binary Dcim


ale
& and 1010 10 11000 24
1100 12 01001 9
1000 8 01000 8 Operands in black
and Output of
| OR 1010 10 11000 24 operators in Red
1100 12 01001 9 color
1110 14 11001 15
~ complement 1010 10 11000 24
0101 5 00111 7

^ XOR 1010 10 11000 24


1100 12 01001 9
0110 6 10001 17
Assignment Description Example
Operator

= Assigns values from right side operands to left c = a + b assigns value of a + b


side operand into c

+= Add AND It adds right operand to the left operand and c += a -> c = c + a
assign the result to left operand

-= Subtract It subtracts right operand from the left operand c -= a -> c = c - a


AND and assign the result to left operand

*= Multiply It multiplies right operand with the left c *= a -> c = c * a


AND operand and 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

%= Modulus It takes modulus using two operands and c %= a -> c = c % a


AND assign the result to left operand

**= Exponent Performs exponential (power) calculation on c **= a -> c = c ** a


AND operators and assign value to the left operand

//= Floor It performs floor division on operators and c //= a -> c = c // a


Division assign value to the left operand
Membership and identity Operators
Operator Description Example
Membership Operator To check membership
of an element in set
in Evaluates to true if it finds a variable in the x in y, results is 1 if x is
specified sequence and false otherwise. a member of sequence
y.
not in Evaluates to true if it does not finds a variable in x not in y, results is 1 if x
the specified sequence and false otherwise. is not a member of
sequence y.
Identity Operator To compare the
memory locations of
two objects.
is Evaluates to true if the variables on either side of x is y, results is 1 if id(x)
the operator point to the same object and false equals id(y).
otherwise.
is not Evaluates to false if the variables on either side of x is not y, results is 1 if
the operator point to the same object and true id(x) is not equal to
otherwise. id(y).
Operator Description
** Exponentiation (raise to the power)
~+- Complement, unary plus and minus (method
names for the last two are +@ and -@)

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

35//y*2-z -1 'BYE'>'bye' FALSE

'hello'*2 hellohello 'hi'*2>'hello' or x/y>z TRUE

~z -6* 'hi'*2>'hello' and x/y>z FALSE


~16 -17

Z=00000101 ~z=11111010 (negative as MSB is 1)


Now it 2’s complement =00000101+1= 00000110 = -6 (-ve from its 1’s)
Write equivalent logical expressions
for given statement
⚫ Check grade is greater than ‘A’ and less than ‘C’
− (grade>’A’) and (grade <’C’)

⚫ City is ‘Delhi’ and population more than 10000


− City ==’Delhi’ and population >10000

⚫ Half of salary is less than equal to 3000


− Salary/2 <= 3000
How will Python evaluate the following expression?
20 - 30 + 40

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?


20 + 30 * 40

= 20 + (30 * 40) # Step 1 # precedence of * is more than that of +


= 20 + 1200 # Step 2
= 1220 # Step 3

How will Python evaluate the following expression written using parenthesis?
(20 + 30) * 40

= (20 + 30) * 40 # Step 1 # using parenthesis(), we have forced precedence


# of + more than that of *
= 50 * 40 # Step 2
= 2000 # Step 3
Q1. Which of the following identifier names are invalid and why?

i Serial_no. v Total_Marks

ii 1st_Room vi total-Marks

iii Hundred$ vii _Percentage

iv Total Marks viii True

Q2. Write the corresponding Python assignment statements:


1.Assign 10 to variable length and 20 to variable breadth.
2.Assign the average of values of variables length and breadth to a variable
sum.
3.Assign a list containing strings 'Paper', 'Gel Pen', and 'Eraser' to a variable
Stationary.
4.Assign the strings 'Mohandas', 'Karamchand', and 'Gandhi' to variables
First, Middle and Last.
5.Assign the concatenated value of string variables First, Middle and Last to
variable Fullname. Make sure to incorporate blank spaces appropriately
between different parts of names.
Q3. Write Python logical expressions corresponding to the following statements and
evaluate the expressions (Assuming variables A, B, C, First, Middle, Last are already
having meaningful values):

1.The sum of 20 and -10 is less than 12.


2.C is not more than 24.
3.6.75 is between the values of integers A and B.
4.The string Middle is larger than the string First and smaller than the string Last.
5.List Stationary is empty.

Q4. Which data type will you use to represent the following data values and why?

1.Number of months in a year


2.You belong to Delhi or not
3.Mobile number
4.Your Pocket money
5.Volume of a sphere
6.Perimeter of a square
7.your Name
8.your Address
Q5. Add a pair of parentheses to each expression so that it evaluates to True.
1.0 == 1 == 2
2.2 + 3 == 4 + 5 == 7
3.1 < -1 == 3 > 4

Q6. Write the output of the following:

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

print(10 != 9 and 20 >= 20)

print(10 + 6 * 2 ** 2 != 9//4 -3 and 29 >= 29/9)

print(5 % 10 + 10 < 50 and 29 <= 29)

print((0 < 6) or (not(10 == 6) and (10<0)))

You might also like