Unit 1
Unit 1
PYTHON
1
Python Character Set
Character set is the set of valid characters that a language can recognize. A character represents any letter, digit or any
other symbol.
· Letters – A to Z, a to z
· Digits – 0 to 9
· Other characters – Python can process all ASCII and Unicode characters as part of data or literals.
Tokens
In a passage of text, individual words and punctuation marks are called tokens
lexical units or lexical elements. The smallest individual unit in a program is called
token.
Python has the following tokens:
(i) Keyword (ii) Identifiers
(iii) Literals (iv) Operators
(v) Punctuators
Keywords
Used to give special meaning to the interpreter and are used by Python interpreter to
recognize the structure of program. These are reserved for special purpose and must not be
7
print ( ) statement:
To print or display output, Python provides print( ) function.
Note: We can enclose string either in double quotes or in single quotes but opening and closing
quote should be of same type. When print() statement is executed, the values are separated by
Output values 10 20 30
We can also specify some other string as the separator using the sep argument of the print() function.
Output: values*10*20*30
values-*-10-*-20-*-30
values 10 20 30
values 10 20 30
print ("value",10,20,30)
IN[1]:
IN[2]: ( )
IN[3]:
10
Elements of Python
• A Python program is a sequence of definitions and commands
(statements)
• Commands manipulate objects
• Each object is associated with a Type
• Type:
• A set of values
• A set of operations on these values
• Expressions: An operation (combination of objects and operators)
11
Types in Python
• int
• Bounded integers, e.g. 732 or -5
• float
• Real numbers, e.g. 3.14 or 2.0
• long
• Long integers with unlimited precision
• str
• Strings, e.g. ‘hello’ or ‘C’
12
Types in Python
• Scalar
• Indivisible objects that do not have internal structure
• int (signed integers), float (floating point), bool
(Boolean), NoneType
• NoneType is a special type with a single value
• The value is called None
• Non-Scalar
• Objects having internal structure
• str (strings)
13
Example of Types
14
Type Conversion (Type Cast)
15
Type Conversion Examples
Note that float to int conversion
is truncation, not rounding off
16
Type Conversion and Input
17
Operators
• Arithmetic + - * // / % **
18
Variables
• A name associated with an object m
• Assignment used for binding 64
m = 64; Acads
c = ‘Acads’; c
f = 3.1416; 3.1416
f
• Variables can change their bindings
f = 2.7183;
2.7183
19
Assignment Statement
• A simple assignment statement
Variable = Expression;
• Computes the value (object) of the expression on the right hand side
expression (RHS)
• Associates the name (variable) on the left hand side (LHS) with the
RHS value
• = is known as the assignment operator.
20
Multiple Assignments
• Python allows multiple assignments
x, y = 10, 20 Binds x to 10 and y to 20
• Evaluation of multiple assignment statement:
• All the expressions on the RHS of the = are first evaluated
before any binding happens.
• Values of the expressions are bound to the corresponding
variable on the LHS.
x, y = 10, 20
x, y = y+1, x+1
x is bound to 21
and y to 11 at the
end of the program
21
Programming using Python
Operators and Expressions
22
Binary Operations
Op Meaning Example Remarks
+ Addition 9+2 is 11
9.1+2.0 is 11.1
- Subtraction 9-2 is 7
9.1-2.0 is 7.1
* Multiplication 9*2 is 18
9.1*2.0 is 18.2
/ Division 9/2 is 4.25 In Python3
9.1/2.0 is 4.55 Real div.
// Integer Division 9//2 is 4
% Remainder 9%2 is 1
23
The // operator
• Also referred to as “integer division”
• Result is a whole integer (floor of real division)
• But the type need not be int
• the integral part of the real division
• rounded towards minus infinity
• Examples
9//4 is 2 (-1)//(-2) is 0
1//2 is 0 9//4.5 is 2.0
24
The % operator
• The remainder operator % returns the
remainder of the result of dividing its
first operand by its second.
Ideally: x == (x//y)*y + x %y
25
Conditional Statements
• In daily routine
• If it is very hot, I will skip exercise.
• If there is a quiz tomorrow, I will
first study and then sleep.
Otherwise I will sleep now.
• If I have to buy coffee, I will
go left. Else I will go
straight.
26
if-else statement
• Compare two integers and print the min.
27
Indentation
• Indentation is important in Python
• grouping of statement (block of statements)
• no explicit brackets, e.g. { }, to group statements
if x < y: 6 10
print (x)
else:
print (y) ed Output
i p p
sk the min’)
print (‘is 6
28
if statement (no else!)
• General form of the if statement
e
if boolean-expr : rt u
fals
e
S1
S1
S2
• Execution of if statement S2
29
if-else statement
• General form of the if-else statement
if boolean-expr : rt u
e
fa
S1
els
else: S1 S2
S2
S3 S3
• Execution of if-else statement
• First the expression is evaluated.
• If it evaluates to a true value, then S1 is executed and
then control moves to S3.
• If expression evaluates to false, then S2 is executed and
then control moves to S3.
• S1/S2 can be blocks of statements!
30
Nested if, if-else
if a <= b:
if a <= c:
…
else:
…
else:
if b <= c) :
…
else:
…
31
Elif
• A special kind of nesting is the chain of if-else-if-else-
… statements
• Can be written elegantly using if-elif-..-else
if cond1: if cond1:
s1 s1
else: elif cond2:
if cond2: s2
s2 elif cond3:
else: s3
if cond3: elif …
s3 else
else: last-block-of-stmt
…
32
Summary of if, if-else
33
Class Quiz
• What is the value of expression:
c) False
d) True
The correct answer is
False
34
Short-circuit Evaluation
• Do not evaluate the second operand of binary short-
circuit logical operator if the result can be deduced
from the first operand
• Also applies to nested logical operators
35
3 Factors for Expr Evaluation
• Precedence
• Applied to two different class of operators
• + and *, - and *, and and or, …
• Associativity
• Applied to operators of same class
• * and *, + and -, * and /, …
• Order
• Precedence and associativity identify the operands for each
operator
• Not which operand is evaluated first
• Python evaluates expressions from left to right
• While evaluating an assignment, the right-hand side is evaluated
before the left-hand side.
36
Class Quiz
37
Caution about Using Floats
• Representation of real numbers in a computer can not
be exact
• Computers have limited memory to store data
• Between any two distinct real numbers, there are infinitely
many real numbers.
• On a typical machine running Python, there are 53 bits
of precision available for a Python float
38
Caution about Using Floats
• The value stored internally for the decimal number 0.1
is the binary fraction
0.00011001100110011001100110011001100110011001100110011010
• Equivalent to decimal value
0.1000000000000000055511151231257827021181583404541015625
• Approximation is similar to decimal approximation 1/3
= 0.333333333...
• No matter how many digits you use, you have an
approximation
39
Comparing Floats
• Because of the approximations, comparison of floats is
not exact.
• Solution?
• Instead of
x == y
use
abs(x-y) <= epsilon
where epsilon is a suitably chosen small value
40
Programming using Python
Loops
41
Printing Multiplication Table
5 X 1 = 5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50
42
Program…
n = int(input('Enter a Too
number:
much '))
print (n, 'X', 1, '=', n*1)
repetition!
print (n, 'X', 2, '=', n*2)
Can I avoid
print (n, 'X', 3, '=', n*3)it?
print (n, 'X', 4, '=', n*4)
print (n, 'X', 5, '=', n*5)
print (n, 'X', 6, '=', n*6)
….
43
Printing Multiplication Table
Loop Exit
i <=10
TRUE FALSE
Loop
44
Printing Multiplication Table
Input n
i=1
TRUE
i <=10
FALSE n = int(input('n=? '))
i=1
Print n x i = ni Stop
i = i+1
45
While Statement
while (expression):
S1 expression
FALSE
S2
TRUE
S1 S2
1. Evaluate expression
2. If TRUE then
a) execute statement1
b) goto step 1.
3. If FALSE then execute statement2.
46
range
• range(s, e, d)
• generates the list:
[s, s+d, s+2*d, …, s+k*d]
where s+k*d < e <= s+(k+1)*d
• range(s, e) is equivalent to range(s, e, 1)
• range(e) is equivalent to range(0, e)
Exercise: What if d is negative? Use python
interpreter to find out.
47
For loop in Python
• General form
48
For Loop
• Print the sum of the reciprocals of the
first 100 natural numbers.