Ch01 Revision of Basics of Python
Ch01 Revision of Basics of Python
C) Value of variable
To bind a value to a variable we use assignment operator (=)
x=100
X ---- Name of variable
There should be only one value to the left hand side of the assignment operator . This value is
called L-value.
There can be a valid expression on the right hand side of the assignment operator . This
expression is called R-Value.
The Statement:
L-Value = R- Value
is called assignment statement
Multiple Assignments :
We can define multiple variables in single statement. It is used to enhance readability of the
program.
Multiple assignments can be done in two ways:
i) Assigning multiple values to multiple variables:
var1,var2,var3,…. , varn=value1,value2,value3,…..,vlauen
var1=var2=var3=…. = varn=value1
use the line continuation character (\) to split a statement into multiple lines
x= 1+2+3 \
+4+5
print(x)
Tokens
Keywords:
Keywords are reserved words and you cannot use them as constant or variable or any other
identifier names. All the Python keywords contain lowercase letters only except .
Keywords in python:
None and if while break try global return from yield
continu nonloca
True or elif for e except l def with as
False not else in pass finally import lambda del assert
is raise class
Delimiters
Delimiters are symbols which are used to separate values or enclose values.
Ex: - ( ) { } [ ] : ,
Operators
A symbol or word that performs some kind of operation on given values and returns the result.
Ex: + - * ** / / % =
Expressions
Types of Operators
1. Arithmetic Operators. 2. Relational Operators.
3. Logical Operators. 4. Assignment Operators
1. Arithmetic Operators :Arithmetic Operators are used to perform arithmetic operations like
addition, multiplication, division etc. + - / * % // **
unary plus (+) ,unary minus(-)
2. Relational(comparison) Operators :
Relational Operators are used to compare the values. == != > >= < <=
We can use relational operators in following way also:
a<b and b<c can be represented as a<b<c
3. Logical Operators
Logical Operators are used to perform logical operations on the given two variables or values.
In the context of Boolean operations, and also when expressions are used by control flow
statements, the following values are interpreted as false: False, None, numeric zero of all types,
and empty strings(‘’) and empty containers like tuples(,), lists[], dictionaries{}). All other values
are interpreted as true.
Precedence
Operator precedence determines which operator is performed first in an expression with more
than one operators with different precedence. For example 10 + 20 * 30 is calculated as 10 +
(20 * 30) and not as (10 + 20) * 30.
(A**2+b**2)**(1/2)
Conditional statements
if Statement
Syntax
if test_expression:
statement(s)
num = -1
if num > 0:
print(num, "is a positive number.")
print("This is also always printed.")
if-else :
Syntax of if...else
if test expression:
Body of if
else:
Body of else
if-elif-else
Syntax of if...elif...else
if test expression:
Body of if
Body of elif
else:
Body of else
The elif is short for else if. It allows us to check for multiple expressions.
If the condition for if is False, it checks the condition of the next elif block and so on.
If all the conditions are False, body of else is executed.
Only one block among the several if...elif...else blocks is executed according to the condition.
The if block can have only one else block. But it can have multiple elif blocks.
if num > 0:
print("Positive number")
elif num == 0:
print("Zero ")
else:
print("Negative number")
The while loop in Python is used to iterate over a block of code as long as the test Expression
(condition) is true.We generally use this loop when we don't know beforehand, the number of
times to iterate.
SYNTAX:
while expression:
statement1
statement2
statementN
# Program to add natural numbers upto sum = 1+2+3+...+n
counter = 0
while counter < 3:
print("Inside loop")
counter = counter + 1
else:
print("Inside else")
In Python, break and continue statements can alter the flow of a normal loop.
Loops iterate over a block of code until test expression is false, but sometimes we wish to
terminate the current iteration or even the whole loop without checking test expression.
The break statement terminates the loop containing it. Control of the program flows to the
statement immediately after the body of the loop.
If break statement is inside a nested loop (loop inside another loop), break will terminate the
innermost loop.
Syntax of break
break
The continue statement is used to skip the rest of the code inside a loop for the current
iteration only. Loop does not terminate but continues on with the next iteration.
Syntax of Continue
continue
For loop
The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable
objects. Iterating over a sequence is called traversal.
Syntax of for Loop
Body of for
Here, val is the variable that takes the value of the item inside the sequence on each iteration.
Loop continues until we reach the last item in the sequence. The body of for loop is separated
from the rest of the code using indentation.
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
# variable to store the sum
sum = 0
# iterate over the list
for val in numbers:
sum = sum+val
print("The sum is", sum)
Ex1:-
for x in range(10):
print(x)
Ex2:-
for x in range(1, 10):
print(x)
Ex3:-
for x in range(1, 30,3):
print(x)
IDEAS OF DEBUGGING
Bug means an error. DEBUGGING means removing the errors.
Syntax:
try:
#statements in try block
except:
#executed when error in try block
else:
#executed if try block is error-free
finally:
#executed irrespective of exception occured or not
try:
print("try block")
x=int(input('Enter a number: '))
y=int(input('Enter another number: '))
z=x/y
except ZeroDivisionError:
print("except ZeroDivisionError block")
print("Division by 0 not accepted")
else:
print("else block")
print("Division = ", z)
finally:
print("finally block")
x=0
y=0
print ("Out of try, except, else and finally blocks." )
Raise an Exception
try:
x=int(input('Enter Age (0 to 125): '))
if x > 125:
raise ValueError(x)
except ValueError:
print(x, "is out of allowed range")
else:
print(x, "is within the allowed range")
SEQUENCES:
STRING
LIST
TUPLE
STRINGS
STRING DEFINITION AND REPRSENTATION IN PYTHON:
' ' " " ''' '''
>>> str1 = 'Hello World!'
>>> str2 = "Hello World!"
>>> str3 = """Hello World!"""
>>> str4 = '''Hello World!''
STRING INDEXING
POSTIVE INDICES
NEGATIVE INDICES
REPETITION(*)
>>> str1 = 'Hello'
>>> str1 * 2
MEMBERSHIP(in)
>>> str1 = 'Hello World!'
>>> 'W' in str1
True
>>> 'Wor' in str1
True
>>> 'My' in str1
False
SLICING([ start:stop:step])
>>> str1 = 'Hello World!'
#gives substring starting from index 1 to 4
>>> str1[1:5]
'ello'
#gives substring starting from 7 to 9
>>> str1[7:10]
'orl'
#index that is too big is truncated down to
#the end of the string
>>> str1[3:20]
'lo World!'
#first index > second index results in an
#empty '' string
>>> str1[7:2]
If the first index is not mentioned, the slice starts
from index.
#gives substring from index 0 to 4
>>> str1[:5]
'Hello'
If the second index is not mentioned, the slicing is
done till the length of the string.
#gives substring from index 6 to end
>>> str1[6:]
'World!'
The slice operation can also take a third index that
specifies the ‘step size’. For example, str1[n:m:k],
means every kth character has to be extracted from
the string str1 starting from n and ending at m-1. By
default, the step size is one.
>>> str1[0:10:2]
'HloWr'
>>> str1[0:10:3]
'HlWl'
Negative indexes can also be used for slicing.
#characters at index -6,-5,-4,-3 and -2 are
#sliced
>>> str1[-6:-1]
'World'
If we ignore both the indexes and give step size as -1
#str1 string is obtained in the reverse order
>>> str1[::-1]
'!dlroW olleH'
TRAVERSING A STRING
LIST INDEXING
POSTIVE INDICES
NEGATIVE INDICES
Positive 0 1 2 3 4
Index
L 10 25 34 12 14
Negative -5 -4 -3 -2 -1
Index
LIST IS MUTABLE
In Python, lists are mutable. It means that the contentsof the list can be changed
after it has been created.
LIST OPERATIONS
CONCATENATION(+)
#list1 is list of first five odd integers
>>> list1 = [1,3,5,7,9]
#list2 is list of first five even integers
>>> list2 = [2,4,6,8,10]
#elements of list1 followed by list2
>>> list1 + list2
[1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
REPETITION(*)
>>> list1 = ['Hello']
#elements of list1 repeated 4 times
>>> list1 * 4
['Hello', 'Hello', 'Hello', 'Hello']
TUPLE:
TUPLE DEFINITION AND REPRSENTATION IN PYTHON:
#tuple1 is the tuple of integers
>>> tuple1 = (1,2,3,4,5)
>>> tuple1
(1, 2, 3, 4, 5)
CREATING TUPLE WITH SINGLE ELEMENT: X= (10,)
TUPLE INDEXING – Same as List
POSTIVE INDICES
NEGATIVE INDICES
ACCESSING ELEMENTS IN TUPLE - Same as List
MAPPINGS:
DICTIONARY
DICTIONARY:
DICTIONARY DEFINITION AND REPRSENTATION IN PYTHON:
CREATING A DICT IONARY
Syntax:
Dict_name= {key1 : value1,key2:value2,……,keyN:valueN}
Example:
dict3 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
TRAVERSING A DICTIONARY
Method 2
>>> for key,value in dict1.items():
print(key,':',value)
SORTING
INSERTION SORT: similar to playing cards
BUBBLE SORT: in each pass,biggest element will bubble up to the end
INTRODUCTION TO PYTHON MODULES:
math (sqrt, cell, floor, pow, fabs, sin,cos, tan,abs)
import math
help(math)
RANDOM MODULE:
random.random()
Return the next random floating point number in the range [0.0, 1.0).
random.randint(a, b)
random.randrange(stop)
random.randrange(start, stop[, step])