Ch 5 Introdution to Python
Ch 5 Introdution to Python
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:
1. Keyword: Reserved words in the library of a language. There are 33 keywords inpython.
as elif if or yield
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.
Literal
pg. 3
CLASS: XI CH - 5 COMPUTER SCIENCE
\\ 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).
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.
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)
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:
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
FLOATING
INTEGER COMPLEX STRINGS DICTIONARY
POINT
BOOLEAN LIST
TUPLE
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
>>>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
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.
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.
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
>>>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
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
iv. Assignment operators: Assignment operator are used to assign values to the variables.
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.
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
10 not
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