Chapter-5 XIC CS Python Introduction (1)
Chapter-5 XIC CS Python Introduction (1)
CHAPTER-5
Name derived from famous BBC [Getting Started
comedy show namely Monty with Python]
Python‟s flying circus
Prepared by:
VIJAY CHAWLA, PGT CS,
PM SHRI KV PITAMPURA,
DELHI – 110034
Python is widely used general purpose, high level programming
language.
Python is a programming language that lets you work quickly
and integrate systems more effectively.
Python was created by Guido Van Rossum
The language was released in February I991
Python got its name from a BBC comedy series from seventies-
“Monty Python‟s Flying Circus”
Python can be used to follow both Procedural approach and
Object Oriented approach of programming
It is OSS , free to use and can be freely downloaded from
www.python.org/downloads
Easy to use Object oriented language
Expressive language
Interpreted Language
Its completeness
Cross-platform Language
Fee and Open source
Variety of Usage / Applications
• Python is compact and very easy to use object oriented
language with very simple syntax rules. It is a high level
language and very programmer-friendly.
In C++ In Python
int a=2, b=3, tmp; a,b=2,3
tmp=a; a,b=b,a
a=b;
b=tmp; VINOD KUMAR VER MA, PGT(CS), KV OEF KANPUR &
• It is interpreted not compiled, thus executes code line by line
and it makes python easy-to-debug and suitable for beginners
and advanced users
Note – Download only that python distribution/MSI Installer, which is best suited for
the Operating system on which you want to install it.
Installing Python
Note – Download only that python distribution/MSI Installer, which is best suited for
the Operating system on which you want to install it.
Interactive Mode
(Immediate
Python working Mode)
Ways
Script Mode
Interactive modes – one command at a time
Python executes the given command and gives the output.
In interactive mode we type command at IDLE prompt ( >>> )
For e.g if you type 20 + 30 in from of IDLE prompt
>>> 20 + 30 (command give by user)
50 (output given by python)
From the above example you can see than at >>> we have to
just give the command to execute and python we execute it if it
is error free otherwise gives an error.
( )
( )
( )
( )
( )
print (“Hello”)
Script Mode – multiple commands can be saved in a file as a
program and then we can execute the entire program
we type Python program in a file and then use the interpreter
to execute the content from the file.
Working in interactive mode is convenient for beginners and for
testing small pieces of code, as we can test them immediately.
But for coding more than few lines, we should always save our
code so that we may modify and reuse the code
In Python IDLE :
Click File New
In new window type the commands you want to save in program
For example:
print(“Hello World!”)
NOTE:
Interactive mode
supports displaying of data ,
both with print() function
and also directly writing
the data (contents) on the
Python shell prompt >>>
NOTE: But, to display in Script mode , print() function is required to
display the data (contents), otherwise nothing is printed
More on INPUT through input() function and
OUTPUT through print() statement…….
# input () takes
string value by
default.
# But price
should be of
numeric value
K eywords
I dentifiers
Li terals
P unctuators
O perators
My funda of remembering Tokens: KILPO it’s just a shortcut given by me for remembrance ;)
TOKEN KEYWORDS
Keywords are the words that convey a special meaning to the
language compiler/interpreter. They are reserved for special
purpose and must not be used as normal identifier names.
and exec not
as finally or
assert for pass
break from print
class global raise
continue if return
def import try
del in while
elif is with
else lambda yield
except
TOKEN IDENTIFIERS
Identifiers are the fundamental building blocks of a program which
are used to identify a variable, function name, class name, module
name or any object.
RULES OF WRITING AN IDENTIFIER
An identifier starts with a letter A to Z, a to z or an underscore ( _ ) followed by
zero or more letters, underscores and digits (0 to 9).
Identifier name canNOT start with a digit.
Python does NOT allow special characters other than underscore ( _ ).
Identifier must NOT be a keyword of Python.
Python is a case sensitive programming language that is uppercase letters
(capital letters) and lowercase letters (small letters) are treated differently.
Eg. Marks and marks are two different identifiers in Python.
• Some valid identifiers : Mymarks , file12 , tv9r , Avg_2 , _no
Boolean Literals
True and False are the only two Boolean
values
‘ “ # \ ( ) [] {} @ , : . ` =
TOKEN OPERATORS
Operators are tokens that trigger some computation/ action when
applied to variables and other objects in an expression.
UNARY OPERATORS
- ~ Bitwise complement , not logical negation
Unary + , Unary ,
BINARY OPERATORS
ARITHMETIC OPERATORS: +,-,*,/,%,//,**
AUGMENTED ASSIGNMENT OPERATORS: = , +=,-=,*=,/=,%=,//=,**=
RELATIONAL OPERATORS: >,<,>=,<=,==,!=
LOGICAL OPERATORS: and , or, not
MEMBERSHIP OPERATORS: in, not in
IDENTITY OPERATORS: is, is not
BITWISE OPERATORS: &(Bitwise AND), ^(Bitwise XOR), |(Bitwise OR)
SHIFT OPERATORS: << (Shift Left) , >> (Shift Right)
DATA TYPES
The kind of data for handling the data used in a
program code is the data type.
Boolean
Strings Tuple List
MUTABLE AND IMMUTABLE TYPES
• Mutable types:
The mutable types are those whose values can be
changed in place.
Only three types are mutable in Python.
These are: Lists, dictionaries and sets.
• Immutable types:
The immutable types are those that can never
change their value in place.
In python , the following are the immutable types:
Integers, floating point numbers, booleans, strings, tuples
DATA TYPE: Number in Python
It is used to store numeric values.
1. Integers
2. Floating point numbers
3. Complex numbers.
DATA TYPE: NUMBER Integer
Integer or int are
positive or negative numbers
with no decimal point.
Integers in Python are of
unlimited size.
Type Conversion to Integer , int( ) function
NOTE:-
The index (also called subscript) is the numbered position of a letter
in the string. In python, indices begin from
0,1,2,…. upto (length-1) in the forward direction and
-1,-2,-3,….. (-length) in the backward direction.
where length is the length of the string.
DATA TYPE: working with STRING examples
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
C omp u t e r S c i e n c e ! ! !
-19 -18 -17 -16 -15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
DATA TYPE: String contd..
Python allows to have two string types:
1) Single line strings (Basic strings)
Text enclosed in single quote ‘India’ or in double quotes “Bharat”
are normally single line strings i.e. they must terminate in one line.
2) Multiline strings
Text spread across multiple lines as one single string.
Two ways of treating multiline strings:-
(i) By adding a backslash at the (ii) By typing the text in triple quotation or
end of normal single apostrophe mark (No backslash
quote/double quote strings. needed at the end of line)
DATA TYPE: LIST in Python
A list in Python represents a list of comma-separated values of any data type
between square brackets e.g. following are some lists:
LIST is mutable- one can change/add/delete a list’s element)
FORWARD INDEX DIRECTION
0 1 2 3 4 5
10 20 30 40 50 60
-6 -5 -4 -3 -2 -1
BACKWARD INDEX DIRECTION
DATA TYPE: TUPLE in Python
Tuples are represented as list of comma-separated values of any data
type within parentheses. Some examples of tuples:
Tuple is immutable - one cannot change the values of a tuple.
FORWARD INDEX DIRECTION
0 1 2 3 4 5
10 20 30 40 50 60
-6 -5 -4 -3 -2 -1
BACKWARD INDEX DIRECTION
DATA TYPE: DICTIONARY in Python
Dictionary data type is an unordered set of comma-separated key: value
pairs, within { } , with the requirement that within a dictionary, no two keys can be
the same (i.e. there are unique keys within a dictionary). Some examples of Dictionary:
Value
D = { 10 : ' CS' , ' IP': 50 }
Key
CONCEPT OF VARIABLES
• Variable is a name (Named Labels)
given to a memory location that refers
to a value and whose values can be
used and processed during program
run.
NOTE:
• Python variables are created by
Here, marks, Name and
assigning value of desired data type to Item_price are the named labels
them. The assignment operator = is used (variables) with datatype inferred
to assign the values from RHS to LHS as Integer, String and Float for the
variable. Eg. Assign integer value to values 100, ‘Agni’, 999.90
create integer variable, string value to a respectively.
variable to create string variable.
• Python is a type infer language that
marks Name
means you don't need to specify the 100 ‘Agni’
datatype of variable. Python
automatically get variable datatype Item_price
depending upon the value assigned to
the variable. 999.90
ASSIGNING VALUES TO VARIABLES
• A Variable is not created until ASSIGNING SAME VALUE TO MULTIPLE
VARIABLES
some value is assigned to it.
SWAPPING VARIABLES’
ASSIGNING VALUES TO VARIABLES ASSIGNING None VALUES
THROUGH AN EXPRESSION. VALUE (nothing) TO
A VARIABLE
L-VALUE and R-VALUE OF A VARIABLE
Lvalue: Expressions which Rvalue: Expressions which
can be given on the LHS(Left can come on the RHS(Right
Hand Side) of an assignment. hand side) of an assignment.
NOTE: In Python, assigning a value
to a variable means, variable’s
label is referring to that value
VARIABLE INTERNALS
VARIABLE
DATA
VALUE ID
TYPE
id of an object (Identity)
The id of an object is generally the memory location of the object. Although id is
implementation dependent but in most implementations it returns the memory
location of the object. id() is a built-in function that returns the id of an object.
Consider, the following code
marks marks
100
100 int 1852878304
UNARY OPERATORS
Unary + , Unary - , ~ Bitwise complement , not logical negation
BINARY OPERATORS
ARITHMETIC OPERATORS: +,-,*,/,%,//,**
AUGMENTED ASSIGNMENT OPERATORS: = , +=,-=,*=,/=,%=,//=,**=
RELATIONAL OPERATORS: >,<,>=,<=,==,!=
LOGICAL OPERATORS: and , or, not
MEMBERSHIP OPERATORS: in, not in
IDENTITY OPERATORS: is, is not
BITWISE OPERATORS: &(Bitwise AND), ^(Bitwise XOR), |(Bitwise OR)
SHIFT OPERATORS: << (Shift Left) , >> (Shift Right)
ARITHMETIC OPERATORS
1) BINARY OPERATOR: requires two A + B , where A and B
values(or operands) to calculate a final answer are Operands and + is the
SYMB BINARY DESCRIPTION Operator
OL OPERATOR
+ ADDITION returns sum of two values
Operator
// FLOOR DIVISION divides the first operand with the second operand
Operator in which the whole part of the result is given in the
output , the fractional part is truncated
P Q
int 10
1805363264
R
int 20
Here, P and Q can be an expression or a variable object. 1805363424
MEMBERSHIP OPERATOR
Membership operator tests for Membership in a sequence.
Returns Boolean True or False
OPERATOR DESCRIPTION
in Results to True value if it finds a variable at the LHS of in operator in the
sequence mentioned in the RHS of the in operator, else it returns False
not in Results to True value if it does not find a variable at the LHS of in operator in
the sequence mentioned in the RHS of the in operator, else it returns False
Program
written in
script
mode
Output
visible on
Interpreter
shell
LOGICAL OPERATORS
or , and , not
Logical operators are used to
perform logical operations on the
given two variables or values.
or operator
The or operator combines two expressions, which make its operands.
i) Relational expression as operands X Y
X Y
Tea or Coffee X Y X or Y
False False False
False True True
NOTE: If either Tea or Coffee is True False True
available at home, you can have X Y
it, hence True. If nothing available True True True
out of the two then, False
Y
OPERATOR PRECEDENCE
Operator Description
** Exponentiation (raised to the power) Highest
~+- Complement unary plus and minus(method Priority
names for last two are +@ and -@)
*/%// 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 Lowest
not , or , and Logical operators Priority
DATA TYPE
CONVERSIONS
The process of converting the value of one data
type (integer, string, float, etc.) to another
data type is called type conversion.
HINT:
Imagine a room between the two integer points on
the y axis where the given value will lie.
ceiling
Now, the integer value which comes in the ceiling of
- 2.7
the room is the answer for ceil function . Similarly floor
integer value which comes in the floor of the room is
the answer for floor function.
FUNCTIO Prototype Description
N (General
form)
math.exp(arg) The exp() function
exp returns the natural
logarithm e raised to
the arg power
Value of e is 2.718
math.sin(arg) The sin() functions
sin returns the sine of
arg.the value of arg must
be in radians.
math.cos(arg) The cos() functions
Cos returns the cosine of
arg. The value of arg
must be in radians
math.tan(arg) The tan() function
tan returns the tangent of
arg. The value of arg
must be in radians.
FUNCTION Prototype Description
(General form)
math.log The log() function
log (num,[base]) returns the natural
logarithm for num. A
domain error occurs if
num is negative and a
range error occurs if the
argument num is zero.
math.log10(num) The log10() function
log10 returns the base 10
logarithm for num. A
domain error occurs if
num is negative and
range error occurs if the
argument is zero.
math.degrees(x) The degrees()
degrees converts angle x from
radians to degree
u*t+(1/2)*f*math.pow(t,2)
ii) |e2y-x|
Ans.
math.fabs(math.exp(2*y)-x)
TIME TO SOLVE……………
Q1) Give the output for the Q2) Write the corresponding
Python Expressions from the
print statements mathematical expressions:
import math
i) |a|+b >= |b|+a
a=math.pow(2,5)
print(a) ii)
print(math.sqrt(81))
print(math.ceil(12.8)) (iii) Cos(x) - 5x
Tan(x)
print(math.floor(12.8)
print(math.ceil(-38.5)) iv) p+ q
(r+s) 4
print(math.floor(-38.5))