Python Notes JNVB Oct16
Python Notes JNVB Oct16
2.Introduction to Python
Q1:What is Program?
Ans: An ordered set of instructions or commands to be executed by a computer is
called a program
Q3.What is Python?
Ans:Python is a programming,highlevel,interpreted,portable,free&open source language, as
Python programsare executed by an interpreter.Created by Guido van Rossum in
February,1991.Python got its name from a BBC comedy series from seventies called “Monty
”. It is based on two programming languages called ABC and
Modula–3.
Q4: What are the Advantages ofPython?
1.Easy to Use: Python is compact and very easy to use with very simple syntax
rules. It is programmer–friendly
2.Expressive Language: Because of simple syntax and fewer lines of code, it is
more capable to express code's purpose than many other languages
3.Interpreted Language: Python interprets and executes the code line by line at a
time. It makes Python an easy–to–debug language and thus suitable for beginners
and advanced users.programs written in Python are easily readable and
understandable
4.Completeness: Python Standard Library provides various modules for different
functionalities.
5.Cross–Platform Language: Python can run on different platforms like Windows,
Linux / Unix, Macintosh, Super Computers, Smart Phones etc. Hence it portable
language
6.Free and Open Source: Python is freely available at free of cost and its source
code is available to every body for further improvement
7.Variety of Usage: Python can be used for a variety of applications like Scripting,
Web Applications, Software development.,Game development, System
Administration, Rapid Prototyping, GUI Programs, Database Applications etc.,
scientific computing, big data and Artificial Intelligence.
8.Case Sensitive:It is case sensitive. i.e. Uppercase and Lowercase alphabets are
different
3.1.1 Working with Python
To write and run Python program, install Python interpreter in computer. IDLE (GUI integrated) is the
standard, most popular Python development environment.
(ii) Script Mode:In the script mode, we can write a Python program in a file, save it and then use the
interpreter to execute the program from the file. Such program files have a .pyextension and they are
also known as scripts.
Basic Structure Of Python Program:
1.Comments:These are the statements that will be ignored by Python interpreter .A single line
comment starts with the symbol#. For multiline comment content will be enclosed in triple quotes
(" " ") or triple apostrophe (' ' ').
2.Functions: A function is a code that has collection of statements to do some task. It has a name
and a function can be executed repeatedly as many times required
3.Statement:A statement is a programming instruction that does something i.e. performs some
action.An expression evaluates and gives some results.
x = 15
y =x – 2 * 4
z = x + z – 10
if (x > y):
4.Expression:An expression in Python is a combination of literals,operators and operands that is
evaluated to produce some other values
5 IndentationandBlocks:Python uses indentation for block as well as for nested block structures.
Leading whitespace (spaces and tabs) at the beginning of a statement is called indentation. In
Python, characters that are used for spacing are called as whitespace characters.
async,await
A3(2)+B1+C2+D2+E3+F4+G1+I4+L1+N3+O1+P1+R2+T2+W2+Y1
To get the updated keywords list type below program
import keyword
list=keyword.kwlist
print(len(list))
for i in list:
print(i)
2.Identifiers:InPython programming language, identifiers are names usedto identify a
variable, function, or other entities in aprogram.
The 4 rules for naming an identifier in Python are as follows:
1Name should begin with uppercase (A-Z) orlowercase (a-z) orunderscore sign (_).
2.It can be of any length (it is preferred tokeep it short and meaningful)
3.An identifiercannot start with a digit &It should not be a keyword or reserved word
4.We cannot use special symbols like !, @, #, $, %, etc.in identifiers
(i) Integer literals:An integer literal is whole numbers or must have at least one digit and
must not contain any decimal point.
Python Supports 4 types of integer literals
a. Decimal Integer literals b.Binary Integer Literals
c. Octal Integer literals d.Hexadecimal integer literals.
a. Decimal Integer Literals: It consists of a sequence of digits between 0 and 9 and does
not start with zero. Ex: 1234, –458 etc.
b. Binary integer literals: consists of digits “0” and “1” and starts with “0b”
2. Floating (or) Real Point Literals: represent real numbers and are written with a decimal
point.These can be expressed in two forms viz. Fractional Form and Exponent Form
a. Fractional form: it consists of signed or unsigned digits including a decimal point
between digits Ex: 3.0,15.9,-10.0
b.Exponent form: A real constant in exponent form consists of two parts mantissa and
exponent. The mantissa must be either an integer or a proper real constant. The mantissa
is followed by a letter E or e and the exponent. The exponent must be an integer.
Ex: 152E05, 1.52e07, 0.152E08, 152e+8,–0.172E–3, .25e–4
3. Complex Literals: Complex number in python is made up of two floating point values,
one each for real and imaginary part. Syntax: a + bj,
a is the real part of the number.b is the imaginary part of the number.
j represents the imaginary unit, which is the square root of -1.i2=-1
(iii)Boolean Literals: A Boolean literal represent one of the two Boolean values i.e. True or
False. It is a unique data type, consisting of two constants, True and False. Boolean True value is
non-zero(1). Boolean False is the value zero(0).
5. Punctuators: These are the symbols used in programming to organize sentence structures and
indicate the emphasis of expressions, statements and program structure. Some punctuators
available in Python are, ' " # \ ( ) [ ] { } @,:. =
Variables: A variable is anidentifier whose valuecan change during program execution.In
Python, we can use an assignment operator(=) to create new variables and assign specific values
to them.
Ex: gender = 'M' ,message = "Keep Smiling" , age=30
LValues and RValues: The LValues are the variables that hold a value or expression. The RValues
are the literals or variables that are assigned to LValues and can present on only right–hand side
of assignment.
Ex: Valid Statements a = 20 Invalid Statements: 20 = a
Multiple Assignments: Different ways of assignments are
1. Assigning same value to multiple variables
Ex: a = b = c = 18
2. Assigning multiple values to multiple variables
Ex1: x, y, z = 10, 20, 30 # Means x=10, y=20, z=30
Ex2: x,y = y,x # This makes x=20, y = 10
Ex3: a, b, c = 5, 10, 7
a, b, c = a+1, b+2, c–1
print (a, b, c) # a=6, b=12, c=6
Displaying type of variable: The type( ) can be used to display the data type of a variable.
>>> a=10 >>> a=20.5 >>> a="Python"
>>> type(a) >>> type(a) >>> type(a)
<class 'int'> <class 'float'> <class 'str'>
id of an object: The id of an object is the memory location of it. The function id( ) is used
for this purpose Ex:
Constant:In the Python programming language, Constants are types of variables whose values cannot
be altered or changed after initialization Eg: 3.14; gravity=9.8
Input() And Output() functions In Python:
Input:-In Python, we have the input() function for taking values entered by input device such as a
keyboard. The input() function prompts user to enter data.
Syntax for input() is: variable = input([Prompt])Eg:>>> name = input("Enter your name: ")
Print():Python uses the print() function to output data to standard output device — the screen.
The function print() evaluates the expression before displaying it on the screen
Syntax for print() is: print(value) Eg:>>>print("Hello")
Type conversion or casting: to change one type of value/variable to another type and can be
done in 2 ways. Implicit (Interpreter automatically converts the data type).
Explicit (programmer specifies the conversions) or
Data Types in Python:
Immutable Types: The immutable types are those that cannot change their value in place. Integers, Float, Booleans,
Complex,Strings and Tuples are immutable types
(b)Tuples: Tuples are asequence of values of any data type, and are indexed by integers.
They are immutable (we cannot modify). Tuples are enclosed inparentheses ()separated
bycommas(,). Example: t=(1,2.3,’jnv’)
Single Element tuple: To construct a tuple with one element add comma (,) after single element
Ex: t=(1,)
Nested tuple: If a tuple contains an element , which is a tuple itself
Eg:t=(1,2,(3,4,5),6,7),t4=((101,'phy',),(102,'eng'),(3,'ip'))
(c)Sets:A set is an unordered collection of unique elementswith no duplicate entry. Setsnot
allowed indexing and slicing, they are mutable (changeable). Sets are enclosed in curly brackets { }.
Example: s={1,2.3,'jnv'},s=set([1,2.3,'jnv']),
Eg:s1={10,True,'Rafiq',1.43,1}Duplicate items not allowed
Adding Element in set Removing Element in set Sets allow immutable Sets not allowedmutable
>>> s={10,20,30} >>> s={10,20,30,40}se={1,2,3,(10.20,30)}se={1,2,3,[10.20,30]}
>>> print(s) >>> print(s) se={1,2,3,{1:1,2:2,3:3}}
{10, 20, 30} {10, 20, 30,40} Empty set se={1,2,3,{10,20,30}}
>>>s.add(40) >>>s.remove(40) a=set()
>>> s >>> s Update set
{40, 10, 20, 30} {10, 20, 30} s.update([50,60,70])
d)Lists:List is a sequence of values of any type. Values in the list are called elements / items.
They are mutable and indexed/ordered. List is enclosed in square brackets [].
Example: l = *1, 2.3,’jnv’+
Mapping:-Mapping is an unordered data type in Python. Currently, there is only one standard
mapping data type in Python called Dictionary.
Dictionary: Dictionary is an unordered data type in Python holds data items in key-value pairs,
They are mutable. Dictionaries are enclosed in curly brackets { }
Ex: d={"Name" : "Teja", "Age":16,"Group":"MPC","Fees":20000,"School":"JNV"}
2.Assignment Operators:In Python, assign values to variables. There are 8 ASo’s in Python
3.Relatonal or Comparison Operators:in Python are used to compare two values and return a
Boolean result (True or False).There are 6 RO’s in Python 1.Greater than(>) 2.Greater Than or Equal
To(>=),3.Less Than(<),4.Lesser Than or Equal To(<=),5.Equal To(==),6.Not Equal To(! =)
4.Logical Operators: There are three logical operators supported by Python. These operators (and,
or, not) are to be written in lower case only. The logical operator evaluates to eitherTrueor
Falsebased on the logical operands on its either side.
1.and:andoperator is used by applying(.-->dot) between two variables, it is just like
multiplication. If both operands are True, then condition becomes True
2.or : oroperator is used by applying(+-->plus) between two variables, it is just like addition.
If any of the two operands are True, then condition becomes True
3.Not: Used to reverse the logicalstate of its operand.It returns True if the conditional expression
returns False, and vice-versa.#WAPP by using LO operators
2.Not in:Returns True if the variable/value is not found inthe specified sequence and
False otherwise
Type Conversion:we can change the data type of a variable in Python from one type to another.
Data type conversion can happen in two ways:explicitly(when the programmer specifies for the interpreter
to convert) or implicitly(when the interpreter understands such a need by itself)
Operator Associativity:Almost all the operators have left to right associativity except exponential
operator (**) which has right to leftassociativity
Ex7(a) Ex7(b) Ex:8(a) Ex:8(b)
7/2*6%4 7//2*6%4 2**4**2 (Right to left) 2**3**2
3.5*6%4 3*6%4 42=16 32=9
21%4 18%4 216=65536 29=512
1 2
5 + 3 * 2 ** 2 // 4
Exponents: 2 ** 2 evaluates to 4.
Multiplication: 3 * 4 evaluates to 12.
Floor division: 12 // 4 evaluates to 3 (integer division that rounds down).
Addition: 5 + 3 evaluates to 8.
Membership :-The membership operator in checks if the elementis present in the list and
returns True, else returnsFalse.
Ex:>>> l1=['mon', 'tue','wed','thu']
>>> 'mon' in l1
True
>>> 'fri' in l1
False
>>> 'fri' not in l1
True
Slicing:Slicing operations allow us to create new list by takingout elements from an
existing list.
Ex:a=['H','e','l','L','o',' ','V','e','r','l','d'],
print(a[3:8])
['L', 'o', ' ', 'V', 'e']
print(a[-8:-3])
['L', 'o', ' ', 'V', 'e']
b=['J','a','w','a','h','a','r',' ','N','a','v','o','d','a','y','a',' ','V','i','d','y','a','l','a','y','a']
print(b[0],b[8],b[17]) J N V
print(b[0],b[-18],b[-9])J N V
Debugging:The process of identifying and removing errors is called debugging. Python
supports three types of errors
1. Syntax Error 2.Logical Error 3.Runtime Error
1.Syntax Error: In Python, a syntax error occurs when the interpreter encounters code
that doesn't conform to the language's grammar rules.
Ex: 1.print(‘Helo”), Ex: 2.print(“Hello, 3.a=10
b=5
if(a<b)
print(x)
2.Logical Error:logical error/bug (called semantic error) does not stop execution but the
program behaves incorrectly and produces undesired /wrong output
Ex:if we wish to find the average of two numbers 10 and 12
>>>int(10+12/2)
16
>>>
>>>int(10+12)/2
11.0
Ex: Suppose if u want to add 2 numbers and type below code like this
a=input("enter number1"))
b=input("Enter number2"))
c=a+b
print('add',c)
it will give output like this
12
To add 2 numbers use correct logical code
a=int(input("enter number1"))
b=int(input("Enter number2"))
c=a+b
print('add',c)
3. Runtime Error:A runtime error causes abnormal termination of program while it is
executing. Runtime error is when the statement is correct syntactically, but the interpreter
cannot execute it.
Ex:-For example, we have a statement having division operation in the program. By
mistake, if the denominator value is zero then it will give a runtime error like “division by
zero”.
Ex1.:13/0 (ZeroDivisionError:)
Ex:2
>>>str = "Hello"
>>> print(str + 5) (TypeError)
Ex 3:int(‘bc’) (Value Error)
Ex 4: c=[1,2,3,4]
print(c[4])(Index Error)
Functions: A function refers to a set of statements or instructionsgrouped under a name
that perform specified tasks.
Afunction is defined once and can be reused at multipleplaces in a program by simply
writing the functionname, i.e., by calling that function.Python has many predefined
functions called built‑infunctions.
Syntax of Function: Ex:
deffunction_name(parameters): def ex(a,b):
#function body if(a>b):
.print(a)
.else:
callfunction() print(b)
ex(1,2)
defeo(a):
if a%2==0:
print(a,"is even")
else:
print(a,"is odd")
eo(9)
eo(8)
Built-in Functions: Pre-defined functions of Python such as input(), int(), max(), len() etc.
Module:A module is a python file inwhich multiple functions are grouped together,These
functions can be easily used in a Python program byimporting the module using import
command.Ex: import math()
User-Defined Functions: Function created by the programmerEx:greet()
Flow of Control: The execution of the statements in a program is known as flow of control.
The flow of control can be implemented using control structures.
Python has three types of control structures—Sequence, Selection, Iteration (repetition).
List is Mutable: In Python, lists are mutable. It means that the contents of the list can
be changed after it has been created
Ex:
ps=['kalki','mirchi','saaho','ntr']
ps
['kalki', 'mirchi', 'saaho', 'ntr']
ps[3]='bahubali'
ps
['kalki', 'mirchi', 'saaho', 'bahubali']
Traversing a list: means to access each and every element of the list one by one, we can
use for and while loop for traversing a list
Using FOR loop Using WHILE loop
Another way of accessing the elements of the list is using range() and len() functions
List Methods and Built-in Functions:There are 15 list methods in python
s.no Method Description Example
1 len() Returns the length of the list >>>a=(‘p’,’y’,’t’,’h’,’o’,’n’)
>>>len(a) 6
2 list() Creates an empty list if no argument is passed >>>a=list()
>>>a o/p []
3 append() Appends a single element passed as an argument at >>>a=[10,20,30,40]
the end of the list >>>a.append(50)
>>>a [10,20,30,40,50]
4 extend() Appends each element of the list passed as argument >>>s=*‘r’,’a’,’f’+
at the end of the given list >>>t=*‘i’,’q’+
>>> s.extend(t)
>>>*‘r’,’a’,’f’,’I’,’q’+
5 Insert() Inserts an element at a particular index in the list >>>a=[10,20,30,40,50]
>>>a.insert(2,25)
>>>a
[10, 20, 25, 30, 40, 50]
6 count() Returns the number of times a given element appears >>>a = [10,20,30,10,40,10]
in the list >>>a.count(10)
3
7 index() Returns index of the first occurrence of the element in >>>a = [10,20,30,20,40,10]
the list >>>a.index(40) 4
8 remove() Removes the given element from the list. >>>a = [10,20,30,20,40,10]
>>>a.remove(30)
[10, 20, 20, 40, 10]
9 pop() Returns the element whose index is passed as >>>a = [10,20,30,40,50,60]
argument to this function and also removes it from >>>a.pop(3) 40
the list
10 reverse() Reverses the order of elements in the >>>a = [10,20,30,40,50,60]
given list >>>a.reverse()
>>>a
[60, 50, 40, 30, 20, 10]
11 sort() Sorts the elements of the given list in place >>>a =
['Tiger','Zebra','Lion','Cat',
'Elephant' ,'Dog']
>>>a.sort()
>>>a
['Cat', 'Dog', 'Elephant',
'Lion', 'Tiger', 'Zebra']
12 sorted() It takes a list as parameter and creates a new list >>>a= [23,45,11,67,85,56]
consisting of the same elements but arranged in >>>b=sorted(a)
ascending order a [23, 45, 11, 67, 85, 56]
b [11, 23, 45, 56, 67, 85]
13 min() Returns minimum or smallest element of the list >>>a = [34,12,63,39,92,44]
>>>min(a) 12
14 max() Returns maximum or largest element of the list >>>a = [34,12,63,39,92,44]
>>>max(a) 63
15 sum() Returns sum of the elements of the list >>>a=[1,2,3,4,5]
>>>sum(a)
15
Introduction to Dictionaries: Dictionaries store data in Key:Value pairs.
The data type dictionary falls under mapping. It is a mapping between a set of keys and a
set of values. The key-value pair is called an item. A key is separated from its value by a
colon(:) and consecutive items are separated by commas and enclosed in curly braces{ }
Syntax of Dictionary:
Eg:
6 d = { "name": "NTR","age": 35, "is_hero": True, "grades": [85, 90, 95], Mixed Dictionaries
"address": { "street": "GANDHI NAGAR","city": "HYD", "country":
"INDIA" }}
7 d = { 'HERO': { 'name': 'NTR', 'age': 30, 'city': 'HYD' }, 'HEROINE': { Nested Dictionary
'name': 'JK', 'age': 25, 'city': 'MUMBAI' }, 'VILLAIN': { 'name': 'SAIF',
'age': 45, 'city': 'DELHI' } }
>>>d2={1:'One',2:'Two',3:'Three'}
>>>for i in d2:
print(i,':',d2[i])
1 : One
2 : Two
3 : Three
Dictionary Methods & Built-in Functions: There are 10 dictionary methods in python
>>>print(staff['Syed Rafiq'])
{'Dept': 'Computer', 'Salary': 32000, 'age': 35, 'Place': 'AP'}