Python Notes of Class XI (Till Looping)
Python Notes of Class XI (Till Looping)
What is Python?
In technical terms, Python is an object-oriented, relatively simple, high-level, general-purpose popular
programming language with integrated dynamic semantics primarily for web and in app development.
It is extremely attractive in the field of Rapid Application Development because it offers dynamic typing
and dynamic binding options.
Python is an interpreted language, meaning that programs written in Python don't need to be
compiled in advance in order to run, making it easy to test small snippets of code and making code
written in Python easier to move between platforms. Since Python is most operating systems in
common use, Python is a universal language found in a variety of different applications.
Why Python?
1. Python is a portable language, it works on different platforms (Windows, Mac, Linux, Raspberry
Pi, etc.).
2. Python has a simple syntax similar to the English language.
3. Python has syntax that allows developers to write programs with fewer lines than some other
Programming languages.
4. Python is an interpreted language, meaning that code can be executed as soon as it is written.
This means that Prototyping can be very quick.
5. Python can be treated in a procedural way, an object-orientated way or a functional way. It is a
complete language in itself, free to download & easily installation.
6. Python allows dynamic typing and dynamic binding.
History of Python
1. Python was developed by Guido van Rossum (Dutch programmer) in the late eighties (Dec. 1989)
and published first official code (version 0.9.0) in early nineties (Feb, 1991) at Centrum Wiskunde &
Informatica (CWI) which is the National Research Institute for Mathematics and Computer
Science in the Netherlands.
2. Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk,
and Unix shell and other scripting languages.
3. Python is copyrighted. Like Perl, Python source code is now available under the General Public
License (GPL).
4. Python is now maintained by a core development team at the institute, although Guido van
Rossum still holds a vital role in directing its progress.
Question / Answer
Q1. Who developed Python?
Ans. Guido Van Rossum in 1990s developed Python programming Language.
Q2. Is Python Object Oriented Programming Language?
Ans. Yes, Python is an Object Oriented programming Language.
Q3. Python is a High Level Interpreted Language? What does it mean?
Ans. Python is a High Level Interpreted programming language. It means that it is programmer friendly
i.e. easy to program and comprehend.
Q4. Python programming language got its name from which T.V. show?
Ans. Python programming language was named after a British T.V. show namely ‘Monty Python’s Flying
Circus’.
Q5. Python is Free and Open Source Language. What do you understand by this feature?
Ans. It means that to download Python, one need not to pay anything, because it is free. And its source
code is also available, which can be modified/improved etc. as it is Open Source.
Q6. What is the difference between Interactive mode and Script mode in Python?
Ans. In Interactive mode, Instruction are given in front of Python prompt (i.e. >>>) in Python Shell. Python
carries out the given instruction and shows the result there itself.
In Script mode, Python instructions are stored in a file generally with .py extension and are executed
together in one go as a unit. The saved instructions are called Python Script or Python Programs.
Q7. What are the advantages of Python programming language?
Ans.
1. Easy to use: Python is a compact and very easy to use object oriented programming language with very
simple syntax rules.
2. Interpreted Language: Python is an interpreted language, not a compiled language. This means that
the Python installation interprets and executes the code line by line at a time.
3. Its Completeness: Python is itself a complete programming language. There is no need to download
anything (like additional libraries), once Python is installed.
4. Interpreted Language: Python is an Interpreted Language, not a Compiled Language. This means that
Python installation interprets and execute the code line by line, which results in easy to debug the
program and thus suitable for beginners to advance users.
5. Cross Platform Language: Python can run equally well on variety on Platforms like: Windows,
Linux/Unix, Supercomputers, Smart phones etc. or in other words, Python is also a Portable Language.
6. Free and Open Source: Python Language is freely available i.e. without paying any cost we can
download it from its official website “Python.org” and its source code (complete program instructions)
is also available.
1. Game Development
2. Database Applications
3. Web Applications
4. Artificial Intelligence
5. GUI (Graphical User Interface) Programs
6. Scripting
Disadvantages of Python:
1. Not the fastest language: Python is little weaker though it offers faster development times but
execution-times are not that fast as compared to some compiled language.
2. Lesser Libraries than C, Java, Perl Programming Languages: Python offers lesser libraries. Thus in some
cases, these languages offer better and multiple solutions than Python.
3. Not Strong on Type Binding: Python interpreter is not very strong on catching “Type-mismatch” issues.
For example: If we assign a integer value to a variable then later on by mistake if we store a string value
in it, Python won’t complain or pin-point it.
Chapter: 6TH
Python Fundamentals
Tokens
The smallest individual unit in a program is known as a Token or Lexical Unit. Python has following
Tokens:
1. Keywords: A keyword is a word having special or fix meaning reserved by programming language.
Python have following Keywords:
False, assert, del, for, in, or, while, None, break, elif, from, is, pass, with, True, class, else, and,
continue, if, return, as, not, etc.
2. Identifier: A Python identifier is a name used to identify a variable, function, class, module or other
object. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more
letters, underscores and digits (0 to 9).
An identifier is a long sequence of letters and digits.
The first character must be a letter; here the underscore (_) counts as letter.
Upper Case and Lower case are different. As Python is a case sensitive language.
The digits 0 to 9 can be a part of an identifier except for the first character.
An Identifier must not be a Keyword of Python.
An Identifier cannot contain any special character except for Underscore (_).
For Example: Myfile, Date_7_77, _DS, CHK, Z2T909 are the valid Identifiers. And Data-Rec,
29CHK, My.File, break, for are not the valid identifiers.
3. Literals / Constant Values: Literals (often termed as Constant values) are the data items that have a
fixed value in the program. Python allows several kinds of Literals:
String Literals: A String Literals is a sequence of characters surrounded by quotes (Single or
Double or Triple quotes).
For example: ‘ab’, “ab”, ‘’’ab’’’.
Important Point: Python also allows us to have NONGRAPHIC CHARACTERS (that cannot be typed directly
through the Keyboard like backspace, tables, carriage return, etc.). These NONGRAPHIC CHARACTERS can
be represented by using escape sequences. An escape sequence is represented by a backslash (\).
Numeric Literals: The numeric literals in Python can belong to any of the following three
different types:
1. int (signed integer)
2. float (floating point real numbers)
3. Complex (Complex number in the form of a + bi, where a is the real part and b is the
imaginary part and i represents ―1)
Floating Point Literals: It can be written in two forms:
1. Fractional form: It consists of signed and unsigned digits, Like +17.5, -17.5
2. Exponent form: It consists of two parts: mantissa and exponent. For example: 0.58×101=
0.58E01, where mantissa part is 0.58 and exponent part is 1.
Boolean Literals: True and False are the only two Boolean values in Python.
Special Literal ‘None’: The None Literal is used just to indicate the absence of value. It is also
used to indicate the end of lists in Python.
Operators
Operators are tokens in Python that triggers some action computation / action when applied to
variables (operands) and other objects in an expression.
Punctuators: Punctuators are symbols that are used in programming languages to organize
programming sentences structure, and indicate the rhythm and emphasis of the expressions,
expressions, statements, and program structure. For ex: ( ), { }, [ ], @,: , #, “ , \, etc..
Expression
Comments
Blocks and Indentation
Statements
Functions
Expression
An expression is any legal combination of symbols that represents a value. An expression represents
something, which Python evaluates and which then produces a value. For example:
1. 15, 2.9 are the expressions that are values only.
2. A+5, (3+5) / 4 are the complex expressions that produces a result when evaluated.
The Expression in Python are as follows:
i. Arithmetic Expression: x+y, y**y, etc..
ii. Relational Expression: x>y, x<=y, etc..
iii. Logical Expression: a or b, a and b, not a
iv. String Expression: “and” + “them”, “and” * 2, etc..
Comment
Comments are the additional readable information to clarify the source code (Programs). There
are two types of comments in Python:
a. Single Line Comment or Full Line Comment
b. Multiline Line Comment or Block Comment
Full Line Comments in Python begin with symbol (#) and generally end with end of the
physical line. As in the above code (program), we can see three comments.
The comment which starts in the middle of a physical line, after Python code is called Inline
Comment
Multiline comments will be enclosed within the (‘’’ ‘’’) triple quotes. This type of multiline
comments is also called docstring.
A group of statements which are the part of another statement or a function are called Block
or Code-Block or Suite in Python.
For example:
if b<5:
print(“Values of ‘b’ is less than 5.”)
print(“Thank You”)
Four spaces here This is a block together mark the with all its
next Indent – level. statements at same Indentation level
Statement
A statement is a programming instruction that does something i.e., some action takes place.
For example:
1. print(“hello”)
2. print()
3. a=15
b=a-10
print(a+3)
if b<3:
--
--
Function
A function is a code that has a name and it can be reused (execute again)by specifying its name in the
program, where needed.
For example: print() is a function but when we call print() to print something, then that function call
becomes a statement. Functions are of two types: System defined function and User defined
function. Rest later on we will learn this concept in detail in class XII.
Dynamic Typing
In Python, the data type of the variable will depend upon the value what we are assigning to it.
Now if later on we reassign that same variable with different data type value then Python will not
complain (no error will be raised) about it. For example:
A=10 then later on if we assign A = ’Himanshu’, then in this case Python will not prompt for error
and the data type of that variable A will be changed from integer to string. This is called Dynamic
Typing.
CHAPTER: 7TH
DATA HANDELING
Data Types: Every value in Python has a data type. Data type represents the type of values and determines
how the value can be used. All data values in Python are encapsulate in relevant object class. To determine
the variable type in Python, we can use the type() function.
The values of some objects are changed and some cannot be change. The objects whose value can be changed
are called Mutable objects and the objects whose values cannot be changed are called Immutable objects.
Some Built-in core data types are as follows:
1. Numbers (int, float, complex)
2. String
3. List
4. Tuple
5. Dictionary
Numbers
Number data types are used to store numeric values in Python. The number data types in Python have
following core data types:
a. Integers
Integers (Signed): Integers in Python can be of any length, it os only limited by the
memory available. The int data type is used to store any integer value. Signed integer
means, the value can either be positive or negative.
Booleans (True and False): Boolean values True and False behaves like 1 and 0. If we type
bool(0) or bool(1), Python will return False or True respectively.
b. Floating Point Numbers: In Python, It represents numbers up to 15 digit precision. It can be
written in two forms:
Fractional Form
Exponent Form
Floating Point numbers have two advantages over integers:
i) They can represent values between the integers.
ii) They can represent a much greater range of values.
c. Complex Numbers: A Complex number is a number of the form A+Bi, where A & B are the real
numbers and i is imaginary number (equal to the square root of -1.
For example: if z = (1+2.56 j) + (-4-3.56 j), then z.real gives the real part and z.imag will gives the
imaginary part. Z.real = -3.0 and z.imag = -1.0
String
A string data types lets us to hold the string data. A string can hold any type of known characters i.e. Letters,
numbers and special characters. For example: “abcd”, “1234”, etc..
String as a sequence of character: A Python string is a sequence of characters and each character can be
individually accessed using its index sometimes called Subscript.
for example: name = ‘PYTHON’
Forward indexing
0 1 2 3 4 5
P Y T H O N
-6 -5 -4 -3 -2 -1 Backward indexing
Here, name[0] = ‘P’ = name[-1]
name[1] = ‘Y’ = name[-2]
name[2] = ‘T’ = name[-3]
name[3] = ‘H’ = name[-4]
name[4] = ‘O’ = name[-5]
name[5] = ‘N’ = name[-6]
Dictionary
Dictionary data type is unordered set of a comma separated Key: value pairs, with in { } i.e. curly braces, with
the requirement that within a dictionary, no two keys can be the same. For example:
D1 = {‘a’:1,’b’:2,’c’:3,’d’:4} ‘’’ here a, b, c, d are the keys of the dictionary D1 and 1, 2, 3, 4 are the values for
these keys respectively.’’’
>>> print(D1[‘a’]) will print 1
Mutable and Immutable Types
The Mutable types are those whose value can be change in place. There are only three types of Mutable in
Python:
1. Lists 2. Dictionaries 3. Sets
The Immutable types are those whose value can never be change in place. There are five types of Immutable
in Python:
1. Integers 2. Floating point numbers 3. Booleans 4. Strings 5. Tuples
Operator Precedence
Operator Description
() Parentheses
** Exponentiation
~x Bitwise NOR
+x, -x Positive, Negative (Unary Operator)
Multiplication, Division, Floor Division, Modulus
*, /, //, %
(Remainder)
+, - Addition, Subtraction
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
Comparisons(Relational Operator), Identity
<, <=, >, >=, <>, !=, ==, is, is not
Operator
Not x Boolean NOT
And Boolean AND
Or Boolean OR
Identity Operator
There are two types of Identity Operators in Python: is and is not.
Is a is b Returns TRUE if both its operands are pointing to the same Objects.
Is not A is not b Returns TRUE if both its operands are pointing to the different Objects.
For example:
Type Casting
As we know that Type conversion is converting one type of data to another type. It is also known as Type
Casting. In Python, Type Casting has two forms:
1. Implicit Type Conversion: In this the conversion will be done by the Interpreter itself without
programmer intervention. It is applied whenever different data types are intermixed in any expression,
so not to lose information. “Python converts all operands up to the type of largest operand. This is
called type promotion”.
For example: if we want to add two variables a and b where a = 2 (int data type) & b = 2.5 (float data
type) then variable a will be implicitly converted by the Python into float (as float data type is bigger
that int data type and there will no information loss) like, a = 2.0 and b = 2.5 which will give output as
4.5.
2. Explicit Type Conversion or Type Casting: In this the conversion will be done by the programmer itself.
For example:
>>> 22 / 2 will give 11.0 whereas int(22 / 2) will give 11. In the first statement (22 / 2), the interpreter
change the numbers into float like (22.0 / 2.0) by performing Implicit conversion and gives the result
as 11.0 whereas in the second statement int(22 / 2) will give the output as 11 only just because the
conversion was Explicitly done by the programmer.
CHAPTER: 8TH
CONDITIONAL AND ITERATIVE STATEMENTS
1. Sequence Construct Statement: The Sequence constructs statement in the default flow of
control which executes the statements sequentially.
Statement 1
Statement 2
Statement 3
|
|
Statement n
2. Selection Construct Statement: The Selection Construct statement means the execution of the
statements depending upon the condition-test. If the condition becomes TRUE then a set of
statements will be followed otherwise another set of instruction will followed. This is also called
Decision Construct Statement.
FALSE
course-of-action
. Statement 1
Another
Statement 2
FALSE
Condition ?
The Exit condition and the control will
come out of the loop.
TRUE
Statement 1
The Loop Body
Statement 2
Algorithm: An Algorithm is a step-by-step procedure ( well defined instructions) to solve the given problem.
For example: Write an algorithm to find the sum of three integer numbers.
Flow Chart: A Flow Chart is the graphical representation of steps in algorithm to solve a given problem. There
are some different types of Flow Chart symbols which are most commonly used:
3. Process Box
6. Document Box
Statement 2
------------
------------
Statement N
else:
Statement 1
Statement 2
------------
------------
Statement N
# WAP in Python to check whether the number input by the user is even or odd using if -- else statement.
Python Code Output
Number=int(input(“Enter any integer number: ”)) Enter any integer number: 25
if Number % 2 == 0: Entered number is Odd Number
print(“Entered number is Even Number”) Sorry
print(“Thank You”)
else:
print(“Entered number is Odd Number”)
print(“Sorry”)
Statement 2
------------
------------
Statement N
else if <conditional expression>: # here we can also write elif <condition expression>:
Statement 1
Statement 2
------------
------------
Statement N
Syntax 2: if <conditional expression>:
Statement 2
------------
------------
Statement N
else if <conditional expression>: # here we can also write elif <condition expression>:
Statement 1
Statement 2
------------
------------
Statement N
else: # Here in case elif becomes false then else part becomes true.
Statement 1
Statement 2
------------
------------
Statement N
# WAP in Python to accept 5 subjects marks from the user and print the grade according to the percentage.
The range() Function: The range() function in Python generates a list of special sequence type like: List, Tuple,
String etc. A sequence in Python is a succession of values bound together by a single name. The general use of
range() function is given below:
range(<lower limit>,<upper limit, step value>, where both limit should be integers.
1. Lower limit indicates from where the loop counting will start.
2. Upper limit indicates up to where the loop will continue.
3. Step value indicates the difference between the Upper limit and the lower limit and it must be same /
constant throughout the execution process. If step value is not mentioned then by default the common
difference will be +1. It can be +ve or –ve.
For example:
1. range(0,5,1) or range(0,5) indicate the sequences 0,1,2,3,4
2. range(5,0,-1) indicate the sequences 5,4,3,2,1
3. range(1,20,2) indicate the sequences 1,3,5,7,9,11,13,15,17,19
4. range(10) indicate the sequences 1,2,3,4,5,6,7,8,9
OUTPUT:
Enter the first string: Himanshu
Enter the second string: Saxena
Both strings are not equal.
The Iteration / Looping / Repetitive Statements allows a set of instructions to be performed until a certain
specific condition is fulfilled. Python provides two kinds of Loops:
1. Counting Loops 2. Conditional Loops
1. Counting Loops: The loops that repeat a certain number of times. For example: for loop
2. Conditional Loop: The loop that repeat until a certain condition evaluates TRUE. For example: while
loop.
The for Loop
The for loop in Python is designed to process the items of any sequence, such as list or string, one by one. The
loop variable contains the highest value of the list after the for loop is over.
The general form of for loop is given below:
for <variable> in <Sequence>:
Statement1
Statement2
-----------
Statement N
Where the sequence determines how many times the loop will get repeated and. Colon is must here and
stetement1,2,3,---N are called body-of-the-for loop.
Example:
for ch in “HIMANSHU”
print(ch)
will give the output:
H
I
M
A
N
S
H
U
The while loop
A while loop is a conditional loop that will repeat the instructions within itself as long as a conditional remains
TRUE. The general form of Python while loop is:
while <Logical expression>:
Body-of-while-loop
For example:
a=5
while a>0:
print(“Hello”, a)
a=a-3
print(“Loop Over..!!”)
OUTPUT
Hello 5
Hello 2
Loop Over..!!
OUTPUT
1
2
3
4
Thank You
JUMP STATEMENT
Python offers two kinds of JUMP Statements: break and continue within the loop-iteration.
1. The break statement: The break statement skip the over a part of the code and terminates the loop
immediately and throw the control of the program outside the loop i.e. outside the body of the while
loop.
For example:
A=1
while A<5:
print(“break statement encountered. Hence while loop terminates immediately and throw the
control outside the loop.”)
break
print(A)
print(“Sorry”)
‘’’ These two lines will be skipped
(though they are inside the body of
print(“Sorry”) while loop) and loop terminates. ’’’
OUTPUT
break statement encountered. Hence while loop terminates immediately and throw the control
outside the loop.
Sorry
The continue Statement
The continue statement is another kind of JUMP Statement like break statement as both the statement
skip over a part of the code. The continue statement instead of forcing and terminating the loop forces
towards the next iteration of the loop to take place by skipping any code in between.
For example:
A=5
while A<11:
if A==9:
continue # here continue statement will bypass the control when A will be 9.
else:
print(A)
A=A+1
print(“I Love Python Programming Language”)
OUTPUT
5
6
7
8
10
I Love Python Programming Language.