Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Ch 5 Introdution to Python

Chapter 5 introduces Python as a general-purpose, high-level, object-oriented programming language developed by Guido van Rossum. It covers Python's characteristics, interpreter modes, character set, tokens, data types, and the structure of Python programs, including variables, expressions, statements, and comments. The chapter emphasizes Python's flexibility, ease of use, and dynamic typing, alongside its various data types such as numbers, sequences, sets, and mappings.

Uploaded by

ai.crimson158
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Ch 5 Introdution to Python

Chapter 5 introduces Python as a general-purpose, high-level, object-oriented programming language developed by Guido van Rossum. It covers Python's characteristics, interpreter modes, character set, tokens, data types, and the structure of Python programs, including variables, expressions, statements, and comments. The chapter emphasizes Python's flexibility, ease of use, and dynamic typing, alongside its various data types such as numbers, sequences, sets, and mappings.

Uploaded by

ai.crimson158
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

CLASS: XI CH - 5 COMPUTER SCIENCE

CH-5 INTRODUTION TO PYTHON


5.1 Introduction:
 General-purpose Object-Oriented Programming language.
 High-level language
 Developed in late 1980 by Guido van Rossum at National Research Institute for
Mathematics and Computer Science in the Netherlands.
 It is derived from programming languages such as ABC, Modula 3, small talk, Algol-68.
 It is Open-Source Scripting language.
 It is Case-sensitive language (Difference between uppercase and lowercase letters).
 One of the official languages at Google.
5.2 Characteristics of Python:
 Interpreted: Python source code is compiled to byte code as a .py file, and this bytecode can be
interpreted by the interpreter.
 Interactive
 Object Oriented Programming Language
 Easy & Simple
 Portable
 Scalable: Provides improved structure for supporting large programs.
 Integrated
 Expressive Language
5.3 Python Interpreter:
Names of some Python interpreters are:
 PyCharm
 Python IDLE
 The Python Bundle
 pyGUI
 Sublime Text etc.
There are two modes to use the python interpreter:
i. Interactive Mode
ii. Script Mode
i. Interactive Mode: Without passing python script file to the interpreter, directlyexecute code
to Python (Command line).

Example:
>>>6+3
Output: 9
Fig: Interactive Mode

Page | 1
CLASS: XI CH - 5 COMPUTER SCIENCE

Note: >> is a command the python interpreter uses to indicate that it is ready. Theinteractive mode is
better when a programmer deals with small pieces of code.
To run a python file on command line:
exec(open(“C:\Python33\python programs\program1.py”).read( ))

ii. Script Mode: In this mode source code is stored in a file with the .py extension and use the
interpreter to execute the contents of the file. To execute the script by the interpreter, you have to
tell the interpreter the name of the file.

Example:
if you have a file name Demo.py , to run the script you have to follow the followingsteps:

Step-1: Open the text editor i.e. Notepad


Step-2: Write the python code and save the file with .py file extension. (Defaultdirectory is
C:\Python33/Demo.py)
Step-3: Open IDLE ( Python GUI) python shell
Step-4: Click on file menu and select the open option
Step-5: Select the existing python file
Step-6: Now a window of python file will be opened
Step-7: Click on Run menu and the option Run Module.
Step-8: Output will be displayed on python shell window.

Fig. : IDLE (Python GUI) Fig: Python Shell

I. Python Character Set :


It is a set of valid characters that a language recognize.
Letters: A-Z, a-z
Digits : 0-9
Special Symbols
Whitespace
II. TOKENS
Token: Smallest individual unit in a program is known as token.There are
five types of tokens in python:
1. Keyword 4. Operators
2. Punctuators 5. Literal
3. Identifier
Page | 2
CLASS: XI CH - 5 COMPUTER SCIENCE

1. Keyword: Reserved words in the library of a language. There are 33 keywords inpython.

False class finally is return break

None continue for lambda try except

True def from nonlocal while in

and del global not with raise

as elif if or yield

assert else import pass

All the keywords are in lowercase except 03 keywords (True, False, None).

2. Identifier: The name given by the user to the entities like variable name, class-name,function-
name etc.

Rules for identifiers:


 It can be a combination of letters in lowercase (a to z) or uppercase (A to Z) ordigits (0 to
9) or an underscore.
 It cannot start with a digit.
 Keywords cannot be used as an identifier.
 We cannot use special symbols like !, @, #, $, %, + etc. in identifier.
 _ (underscore) can be used in identifier.
 Commas or blank spaces are not allowed within an identifier.
Valid Identifier Examples: Invalid Identifier Examples:
Myfile Data-rec (Contains special character)
date7_7_77 29CLCT (Starting with digit)
z2tozp break (Reserved keyword)
_ds My.file (Contains special character)
_chk
3. Literal: Literals are the constant value. Literals can be defined as a data that is given ina variable or
constant.

Literal

Numeric String Boolean Special Literal


Collections

int float complex

True False None

pg. 3
CLASS: XI CH - 5 COMPUTER SCIENCE

A. Numeric literals: Numeric Literals are immutable.


Example: 5, 6.7, 6+9j
B. String literals:
 String literals can be formed by enclosing a text in the quotes. We can use both single aswell as
double quotes for a String.
Example: "Aman" , '12345'
 Python allows certain nongraphic characters in string values.
 Nongraphic characters are those characters that cannot be typed directly from the keyboard.
Example: backspace, tab, etc.
 These can be represented by using Escape sequences.
 Escape sequences: It represents a single character & hence consume 1 byte in ASCII representation.

Escape sequence characters:

\\ Backslash
\’ Single quote
\” Double quote
\a ASCII Bell
\b Backspace
\f ASCII Formfeed
\n New line charater
\t Horizontal tab
\r Carriage return
\v ASCII vertical tab

C. Boolean literal: A Boolean literal can have any of the two values: True (Boolean true) or False
(Boolean false).

D. Special literals: Python contains one special literal i.e. None.


None value in Python means “There is no useful information” or “There’s nothing here”

None is used to specify to that field that is not created. It is also used for end of lists inPython.

Note: Boolean literals and special literals. None are some built-in constants/literals of Python.
E. Literal Collections: Collections such as tuples, lists and Dictionary are used in Python.
4. Operators: An operator performs the operation on operands. Basically, there are two types of
operators in python according to number of operands:
A. Unary Operator: Performs the operation on one operand.
Example:
+ Unary plus
- Unary minus
~ Bitwise complement not
B. Binary Operator: Performs operation on two operands.
pg. 4
CLASS: XI CH - 5 COMPUTER SCIENCE

5. Separator or punctuator : Punctuators are symbols that are used in programming languages to organize
programming-sentence, structures, and indicate the rhythm and emphasis of expressions, statements, and
program structure.
Most common punctuators are: . , ; ( ) { } [ ] # \, etc.

 Mantissa and Exponent Form:


A real number in exponent form has two parts:
 mantissa
 exponent
Mantissa : It must be either an integer or a proper real constant.
Exponent : It must be an integer. Represented by a letter E or e followed by integer value.
Valid Exponent form Invalid Exponent form
123E05 2.3E (No digit specified for exponent)
1.23E07 0.24E3.2 (Exponent cannot have fractional part)
0.123E08 23,455E03 (No comma allowed)
123.0E08
123E+8
1230E04

III. BAREBONES / Components of a Python Programs:


A. Expressions.
B. Statements
C. Comments
D. Functions
E. Blocks and Indentation
A. Expressions: A legal combination of symbols and values that produce a result. An expression is defined as a
combination of constants, variables, and operators. An expression always evaluates to a value. A value or a
standalone variable is also considered as an expression, but a standalone operator is not an expression.
Some examples of valid expressions are given below.
(i) 100
(ii) num
(iii) num – 20.4
(iv) 3.0 + 3.14
(v) 23/3 -5 * 7(14 -2)
(vi) "Global" + "Citizen"
B. Statements: A line which has the instructions or expressions. In Python, a statement is a unit of code that
the Python interpreter can execute.
Example:
>>> x = 4 #assignment statement
>>> cube = x ** 3 #assignment statement
>>> print (x, cube) #print statement
Difference between Expression & Statement:

pg. 5
CLASS: XI CH - 5 COMPUTER SCIENCE

C. Comments: Comments are not executed. Comments explain a program and make a program
understandable and readable. All characters after the # and up to the end of the physical line are part of
the comment and the Python interpreter ignores them.
There are three types of comments in python:
i. Full line comment
ii. Inline comment
iii. Multi-line comment

i. Full line comment: The physical lines beginning with # are the full line comments.
Example:
#This program shows a program’s component .#Definition
of function SeeYou() follows.
#Main program code follows now.
ii. Inline comment: It starts in the middle of a physical line, after Python code.
Example:
if b<5: # colon means it requires a block
if a>b: # Relational operator compares two values.
iii. Multi-Line comment(block comment): It can be done in two ways
a) Add a # symbol in the beginning of every physical line part of the multi – line comments.
Example:
#Multi-line comments are useful for detailed description
#Related to the program in question
#It helps clarify certain important things.
b) Triple quoted (‘ ’ ’ or “ ” ”) multi-line comments may be used in python. It is also known as
docstring.
Example:
‘ ‘ ‘ Multi-line comments are useful for detailed description
Related to the program in question
It helps clarify certain important things.’ ‘ ‘
D. Functions: A function is a code that has a name, and it can be reused by specifying its name in the
program, where needed.
E. Blocks and Indentation:
Blocks: A group of statements which are part of another statement, or a function are called block or
code-block or suite in Python.
Indentation: Python uses indentation to create blocks of code. Statements at same indentation level are
part of same block/suite. Statements requiring suite/ code- block have a colon (:) at their end.

 Python provides no braces to indicate blocks of code for class and function definition orflow control.
 A group of statements which are part of another statement or a function.
 Maximum line length should be maximum 79 characters.
 Blocks of code are denoted by line indentation, which is rigidly enforced.
 The number of spaces in the indentation is variable, but all statements within the blockmust be
indented the same amount.
Example:
if True:
print(“True”)
else:
print(“False”)

pg. 6
CLASS: XI CH - 5 COMPUTER SCIENCE

Example:
‘’’ This program will calculate the average of 10 values.
First find the sum of 10 values
and divide the sum by number of values.‘’’
Multiple Statements on a Single Line: The semicolon ( ; ) allows multiple statements on the single line given
that neither statement starts a new code block.

Example:
x=5; print(“Value =” x)

IV. Variable/Label in Python:


Definition: Named location that refers to a value and whose value can be used and processedduring program
execution.
Variables in python do not have fixed locations. The location they refer to changes every timetheir values
change.

Creating a variable: A variable is created the moment you first assign a value to it.Example:
x=5

y = “hello”
Variables do not need to be declared with any particular type and can even change type after they have
been set. It is known as dynamic Typing.
Example:
x=4 # x is of type int
x = "python" # x is now of type str
print(x)
Rules for Python variables:

 A variable name must start with a letter or the underscore character


 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and underscore (A-z, 0-9,and _ )
 Variable names are case-sensitive (age, Age and AGE are three different variables).

i. Python allows assign a single value to multiple variables.


Example: x = y = z = 5
pg. 7
CLASS: XI CH - 5 COMPUTER SCIENCE

ii. You can also assign multiple values to multiple variables.


Example:
x , y , z = 4, 5, “python”
4 is assigned to x, 5 is assigned to y and string “python” assigned to variable z respectively.x=12
y=14
x, y=y, x
print(x, y)
The result will be:
14 12

Lvalue and Rvalue:


An expression has two values. Lvalue and Rvalue.
Lvalue: the LHS part of the expression
Rvalue: the RHS part of the expression
Python first evaluates the RHS expression and then assigns to LHS.
Example:
p, q, r= 5, 10, 7
q, r, p = p+1, q+2, r-1
print (p, q, r)
The result will be:
6 6 12

Note: Expressions separated with commas are evaluated from left to right and assigned in sameorder.

Example:

Name Error: A variable is defined only when you assign some value to it. Using an undefined variable in an
expression/ statement causes an error called Name Error.
Example:
print(x) # error name ‘x’ not defined
x = 20
print(x)

pg. 8
CLASS: XI CH - 5 COMPUTER SCIENCE

DATA HANDLING

 Data Types in Python:


Python has five data types –
1. Numbers
2. Sequences
3. Sets
4. None
5. Mapping
DATA TYPE

NUMBER SETS SEQUENCE NONE MAPPING

FLOATING
INTEGER COMPLEX STRINGS DICTIONARY
POINT

BOOLEAN LIST

TUPLE

a. Numbers: Number data types store numeric values.


There are three numeric types in Python:
 int
 float
 complex
Example:
w=1 # int
y = 2.8 # float
z = 1j # complex

 Integer : There are two types of integers in python:


 int
 boolean
 int:
It is the normal integer representation of whole number.
Integer in python 3.x can be of any length
int or Integer, is a whole number, positive or negative, without decimals.

Example:
x=1
y = 35656222554887711
z = -3255522
 boolean: It has two values: True and False. True has the value 1 and False has thevalue 0.
Example:
>>>bool(0)
False
>>>bool(1)
pg. 9
CLASS: XI CH- 5 COMPUTER SCIENCE
True
>>>bool(‘ ‘)
False
>>>bool(-34)
True
>>>bool(34)
True
 float : 
A number having fractional part is a floating-point number.
float or "floating point number" is a number, positive or negative, containing one or more
decimals.
Fractional number can be written in two forms
i. Fractional form (Normal Decimal Notation)
ii. Exponential Notation
Float can also be scientific numbers with an "e" to indicate the powerof 10.
Floating point numbers have precision of 15 digits (double precision).
Example:
x = 1.10
y = 1.0
z = -35.59
a = 35e3
b = 12E4
c = -87.7e100
 complex : 
Python represent complex number as a pair of floating point number.
Complex number are a composite quantity made of two parts
 Real part
 Imaginary part
Complex numbers are written with a "j" as the imaginary part.
You can retrieve the components using attribute reference: real and imag
 var_name.real
 var_name.imag
Example:
>>>x = 3+5j
>>>y = 2+4j
>>>z=x+y
>>>print(z)
OUTPUT: 5+9j
>>>z.real
OUTPUT: 5.0
>>>z.imag
OUTPUT: 9.0
Python displays complex number in parenthesis when they have a non-zero real part.
Example:
>>>C=0+4.5j
>>>D=1.1+3.4j
>>>print(C)
OUTPUT: 4.5j
>>>print(D)
OUTPUT: (1.1+3.4j)

Page | 10
CLASS: XI CH- 5 COMPUTER SCIENCE

b. Sequence: Sequence data type stores values in sequence.


There are three sequence types in Python:
i. String
ii. List
iii. Tuple
 String: String of characters represented in the quotation marks.
 Python allows for either pairs of single or double quotes. Example: 'hello' is the sameas "hello" .
 Python does not have a character data type; a single character is simply a string with alength of 1.
 The python string store Unicode characters.
 Each character in a string has its own index.
 String is immutable data type means it can never change its value in place.
 The index (also called subscript) is the numbered position of a letter in the string.
 Indices begin 0 onwards in the forward direction & -1,-2, …. in the backward direction.
 Syntax for access any character:
<stringname>[index number]
Example:
>>>name=’hello’
>>>name[0]
OUTPUT: ‘h’
 List: A list in Python represents a list of comma-separated values of any datatype between square brackets.
It is mutable data type.
Example: #To create a list
>>> list1=[5, 3.4, “Khobar”, “25B”, 58]
>>>print(list1)
OUTPUT: [5, 3.4, “Khobar”, “25B”, 58]
 Tuple: Tuple is a sequence of items separated by commas and items are enclosed in parenthesis ().
It is immutable data type.
Example: #To create a tuple
>>> tup=(5, 3.4, “Dammam”, “25B”, 58)
>>>print(tup)
OUTPUT: (5, 3.4, “Dammam”, “25B”, 58)
c. None: It is a special data type with a single value. It is used to signify the absence of value in a
situation.
None supports no special operations, and it is neither False nor 0(zero)
Example:
>>> var = none
>>>print(type(var))
OUTPUT: <class ‘NoneType’>
>>>print(var)
OUTPUT: None
d. Mapping: Mapping is an unordered data type in Python. There is only one standard mapping data
type in Python called dictionary.
 Dictionary: It is an unordered set of comma-separated key:value pairs, within { }
The keys are usually strings and their values can be any data type.
No two keys can be the same i.e., there are unique keys within a dictionary.
To access any value in the dictionary, the key has to specify in square brackets [ ].
Example:
>>> vowels:{‘a’ : 1, ‘e’ : 2, ‘i’ : 3, ‘o’ : 4, ‘u’ : 5}
>>>print(vowels)
OUTPUT: {‘a’ : 1, ‘e’ : 2, ‘i’ : 3, ‘o’ : 4, ‘u’ : 5}
11
CLASS: XI CH- 5 COMPUTER SCIENCE

>>>print(vowels[‘e’])
OUTPUT: 2
 MUTABLE & IMMUTABLE Type:
The Python data objects can be broadly categorized into two types.
 Mutable Data Type
These are changeable. In the same memory address, new value can be stored.
Example: List, Set, Dictionary
 Immutable Data Type:
These are unchangeable. In the same memory address new value cannot be stored.
Example: Integer, Float, Boolean, String and Tuple.

 VARIABLE INTERNALS:
 If you want to know the type of variable, you can use type( ) function :
Syntax:
type (variable-name)
Example:
>>>x=6
>>>type(x)
The result will be: <class ‘int’>
 If you want to know the memory address or location of the object, you can use id( ) function.
Example:>>>id(5)
The result will be: 1561184448
>>>b=5
>>>id(b)
The result will be: 1561184448
 You can delete single or multiple variables by using del statement.
Example:
del x
del y, z

 Input from a user:


input( ) method is used to take input from the user.
Example:
print("Enter your name:")
x = input( )
print("Hello, " + x)
Reading a number from a user:
x= int (input(“Enter an integer number”))
 input( ) function always returns a value of string type.
 OUTPUT using print( ) statement:
Python uses the print() function to output data to standard output device — the screen.
The print()outputs a complete line and then moves to the next line for subsequent output.

Syntax:
print (object, sep=<separator string >, end=<end-string>)
object : It can be one or multiple objects separated by comma.
sep: sep argument specifies the separator character or string. It separates the objects/items.
By default, sep argument adds space in between the items when printing.
end: It determines the end character that will be printed at the end of print line. By default, ithas newline
character( ‘\n’ ).
12
CLASS: XI CH- 5 COMPUTER SCIENCE

Example:
x=10
y=20
z=30
print(x,y,z, sep=’@’, end= ‘ ‘)
Output:
10@20@30
 Type conversion: The process of converting the value of one data type (integer, string, float, etc.) to
another data type is called type conversion. Python has two types of type conversion:
 Implicit Type Conversion (Coercion / Type promotion)
 Explicit Type Conversion (Type casting)

 Implicit Type:
 Implicit conversion, also known as coercion, happens when data type conversion is done automatically
by Python and is not instructed by the programmer.

 In a mixed arithmetic expression, Python converts all operands into a wider-sized data type without
any loss of information. This is called type promotion.

Example: num1 = 10 #num1 is an integer


num2 = 20.0 #num2 is a float
sum1 = num1 + num2 #sum1 is sum of a float.

Note: In Python, if the operator is the division operator (/), the result will always be a floating-point number,
even if both the operands are of integer types (an exception to the rule)
 Explicit Type:
To convert one data type into another data type.

Casting in python is therefore done using constructor functions:

 int( ) - constructs an integer number from an integer literal, a float literal or a string literal.
Example:
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
 float( ) - constructs a float number from an integer literal, a float literal or a string literal.
Example:
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2
 str( ) - constructs a string from a wide variety of data types, including strings, integerliterals and
float literals.
Example:
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'
• chr( ) – Converts ASCII value of x to character.
• ord( ) – returns the character associated with the ASCII code x

13
CLASS: XI CH- 5 COMPUTER SCIENCE
Type Error: When you try to perform an operation on a data type not suitable for it ( Eg: dividing or
multiplying a string), Python raises an error called Type Error.

 OPERATORS IN PYTHON:
i. Arithmetic Operator
ii. Relational Operator
iii. Logical Operators
iv. Assignment Operators
v. Augmented Operators
vi. Identity Operators
vii. Membership operators
i. Arithmetic Operators: To perform mathematical operations.
RESULT
OPERATOR NAM SYNTA (X=14, Y=4)
E X
+ Addition x+y 18
_ Subtraction x–y 10
* Multiplication x*y 56
/ Division (float) x/y 3.5
// Division (floor) x // y 3
% Modulus x%y 2
** Exponent x**y 38416
Example:
x= -5
>>>x**2
OUTPUT: -25
ii. Relational Operators: Relational operators compare the values. It either returns True or
False according to the condition.
RESULT
OPERATOR NAME SYNTAX (IF X=16, Y=42)
> Greater than x>y False
< Less than x<y True
== Equal to x == y False
!= Not equal to x != y True

False
>= Greater than or equal to x >= y
True
<= Less than or equal to x <= y
iii. Logical operators: Logical operators perform Logical AND, Logical OR and LogicalNOT
operations.
OPERATOR DESCRIPTION SYNTAX
and Logical AND: True if both the operands are true x and y

14
CLASS: XI CH- 5 COMPUTER SCIENCE
or Logical OR: True if either of the operands is true x or y
not Logical NOT: True if operand is false not x

Examples: of Logical Operator:

and operator: The and operator works in two ways:


a. Relational expressions as operands
b. numbers or strings or lists as operands
a. Relational expressions as operands:
X Y X and Y
False False False
False True False
True False False
True True True
>>> 5>8 and 7>3
False
>>> (4==4) and (7==7)
True
b. numbers or strings or lists as operands:
In an expression X and Y, if first operand has false value, then return first operand X as aresult,
otherwise returns Y.
X Y X and Y
false false X
false true X
true false Y
true true Y

>>>0 and 0
0
>>>0 and 6
0
>>>‘a’ and
‘n’’n’
>>>6>9 and ‘c’+9>5 # and operator will test the second operand only if the first operandFalse
# is true, otherwise ignores it, even if the second operand is wrong

or operator: The or operator works in two ways:


a. Relational expressions as operands
b. numbers or strings or lists as operands
a. Relational expressions as operands:
X Y X or Y
False False False
False True True
True False True
True True True

15
CLASS: XI CH- 5 COMPUTER SCIENCE
>>> 5>8 or 7>3
True
>>> (4==4) or (7==7)
True
b. Numbers or strings or lists as operands:
In an expression X or Y, if first operand has true value, then return first operand X as aresult,
otherwise returns Y.

X Y X or Y
false false Y
false true Y
true false X
true true X
>>>0 or 0
0
>>>0 or 6
6
>>>‘a’ or ‘n’’a’
>>>6<9 or ‘c’+9>5 # or operator will test the second operand only if the first operand True
# is false, otherwise ignores it, even if the second operand is wrong

not operator:
>>>not 6
False
>>>not 0
True
>>>not -7
False

Chained Comparison Operators:


>>> 4<5>3 is equivalent to >>> 4<5 and 5>3
True True

iv. Assignment operators: Assignment operator are used to assign values to the variables.

OPERATOR DESCRIPTION SYNTAX

= Assign value of right side of expression to left side operand x=y+z

v. Augmented Assignment operators: Augmented Assignment operators are used to replace those statements
where binary operator takes two operands.
OPERATOR DESCRIPTION SYNTAX
+= Add AND: Add right side operand with left side operand and a+=b
then assign to left operand a=a+b
-= Subtract AND: Subtract right operand from left operand and a-=b a=a- b
then assign to left operand
*= Multiply AND: Multiply right operand with left operand and a*=b
then assign to left operand a=a*b

16
CLASS: XI CH- 5 COMPUTER SCIENCE
/= Divide AND: Divide left operand with right operand and then a/=b a=a/b
assign to left operand
%= Modulus AND: Takes modulus using left and right operands and a%=b
assign result to left operand a=a%b

//= Divide(floor) AND: Divide left operand with right operand a//=b a=a//b
andthen assign the value(floor) to left operand
**= Exponent AND: Calculate exponent(raise power) value using a**=b
operands and assign value to left operand a=a**b
&= Performs Bitwise AND on operands and assign value to a&=b
left operand a=a&b
|= Performs Bitwise OR on operands and assign value a|=b a=a|b
to left operand
^= Performs Bitwise xOR on operands and assign value a^=b a=a^b
to left operand
>>= Performs Bitwise right shift on operands and assign value to left a>>=b
operand a=a>>b
<<= Performs Bitwise left shift on operands and assign value to a <<=b a=a << b
left operand
vi. Identity operators- is and is not are the identity operators both are used to check if two values are located
on the same part of the memory. Two variables that are equaldoes not imply that they are identical.

is True if the operands are identical


is not True if the operands are not identical
Examples:Let
a1 = 3
b1 = 3
a2 = 'Python Programming'
b2 = 'Python Programming'
a3 = [1,2,3]
b3 = [1,2,3]
print(a1 is not b1)
print(a2 is b2) # Output is False, since lists are mutable.
print(a3 is b3)
Output:
False True False
Examples::
>>>str1= “Hello”
>>>str2=input(“Enter a String :”)
Enter a String : Hello
>>>str1==str2 # compares values of string
True
>>>str1 is str2 # checks if two address refer to the same memory addressFalse
vii. Membership operators- in and not in are the membership operators; used to testwhether a value or
variable is in a sequence.

in True if value is found in the sequence


not in True if value is not found in the sequence

17
CLASS: XI CH- 5 COMPUTER SCIENCE
Examples: Let Output:
x = 'Digital India'
y = {3:'a',4:'b'}
True
print('D' in x) True
print('digital' not in x) False
print('Digital' not in x) True
print(3 in y) False
print('b' in y)
 Operator Precedence and Associativity:
Operator Precedence: It describes the order in which operations are performed when anexpression is
evaluated. Operators with higher precedence perform the operation first.
Operator Associativity: whenever two or more operators have the same precedence, then associativity
defines the order of operations.

Order of
Operators Description
precedence

1 () Parenthesis

2 ** Exponentiation

3 ~, +, - Complement, Unary plus, Unary minus

4 * , / , % , // Multiply, divide, modulus, floor division

5 +,- Addition, Subtraction

6 <= , < , >, >=, ==, != Relational and Comparison operators


= , %=, /=, //=, -=, +=, Assignment and Augmented assignment operators
7 *=, **=

8 is, is not Identity operators

9 in, not in Membership operators

10 not

11 and Logical operators


12 or

 Debugging:
The process of identifying and removing mistakes, flaw, faults also known as bug or errors, from a program is
called debugging.
Errors in a program can be categorized as:
i. Syntax errors: The Python Syntax Error occurs when the interpreter encounters invalid syntax (as
per the rules of Python) in code.
ii. Logical errors: A logical error is a bug in the program that causes it to behave incorrectly.
A logical error produces an undesired output but without abrupt termination of the execution of
the program.
iii. Runtime errors: A runtime errors causes abnormal termination of program while it is
executing. Runtime error is when the statement is correct syntactically, but the
interpreter cannot execute it. It does not appear until after the program starts running
or executing.
18

You might also like