0% found this document useful (0 votes)
33 views

Ch01 Revision of Basics of Python

This document discusses the basics of Python including variables, data types, operators, and expressions. It covers key topics like: 1. Variables are memory locations that store values and have an identity, type, and value. Common data types in Python include integers, floats, booleans, strings, and lists. 2. Operators like arithmetic, relational, logical, and assignment are used to perform operations on values in Python. 3. Expressions combine operators and operands to evaluate to a single value. Operator precedence and associativity determine the order calculations are performed.

Uploaded by

Jagan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

Ch01 Revision of Basics of Python

This document discusses the basics of Python including variables, data types, operators, and expressions. It covers key topics like: 1. Variables are memory locations that store values and have an identity, type, and value. Common data types in Python include integers, floats, booleans, strings, and lists. 2. Operators like arithmetic, relational, logical, and assignment are used to perform operations on values in Python. 3. Expressions combine operators and operands to evaluate to a single value. Operator precedence and associativity determine the order calculations are performed.

Uploaded by

Jagan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

CHAPTER 1 : REVISION OF BASICS OF PYTHON

Variables(Objects) and Types


Variables are memory locations used to store data.
Every object has:
A. An Identity, - can be known using id (object)
B. A type – can be checked using type (object) and
C. A value
Variablea memory location which has data ie eg if memory location 22034145 is assigned a
variable x and vaue 5 then 22034145 is x and its value is 5
A. Identity of the object: It is the object's address in memory and does not change
once it has been created.
(We would be referring to objects as variable for now)
B. Type (i.e data type): It is a set of values, and the allowable operations on those
values. It can be one of the following:

C) Value of variable
To bind a value to a variable we use assignment operator (=)
x=100
X ---- Name of variable

100 ---- Value of variable


2004
2000 ---- address(id) of
variable
100

We should not write

100 = x #this is an error

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

Ex:- x,y,z=21, 43,56 is equivalent to


x=21
y=43
z=56

ii) Assigning same value to multiple variables:

var1=var2=var3=…. = varn=value1

ex:- total=count=0 # it will assign total and count to zero

Explicit Line Continuation

use the line continuation character (\) to split a statement into multiple lines

x= 1+2+3 \
+4+5
print(x)

Implicit Line Continuation


Implicit line continuation is when you split a statement using either of parentheses ( ),
brackets [ ] and braces { }.

result = (10 + 100


*5-5
/ 100 + 10
)
print(result)

Tokens

A python token is smallest individual unit in a program/script that is meaningful to interpreter.


The following categories of tokens exist in python:
Keywords,
Identifiers,
Literals,
Delimiters,
Operators.

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

Identifiers: (Similar to variables)


The name of any variable ,constant,function or module is called an identifier.
Rules for naming identifiers:

Rules for writing identifiers


1. Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or
digits (0 to 9) or an underscore _. 

Names like myClass, var_1 and print_this_to_screen, all are valid example.

2. An identifier cannot start with a digit.


 1variable is invalid, but variable1 is perfectly fine.
3. Keywords cannot be used as identifiers.
4. Identifier cannot use special symbols/characters( LIKE . , whitespaces)except
underscore(_)
5. Identifier can be of any length.
6. UPPER CASE and lower case letters are different as python is case sensitive
7. Identifiers can start with underscore( _ ) or a letter.

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: + - * ** / / % =

Literals (similar to datatypes)


A fixed numeric or non numeric value is called a literal.
Ex:- 10, 20.3, “abc”, ‘xyx’, True

Literals -Escape sequence


An escape sequence is a sequence of characters that does not represent itself when used inside
a string literal, but is translated into another character or a sequence of characters that may be
difficult or impossible to represent directly.

Escape Sequence Description


\\ Backslash (\)
\' Single quote (')
\" Double quote (")
\n ASCII Linefeed (LF)
\r ASCII Carriage Return (CR)
\t ASCII Horizontal Tab (TAB)
Expressions and Operators

Expressions

An expression is combination of operators and values(operands). An expression is evaluated to


a single value.
Ex:- 5+2 *4 =13
Converting mathematical expressions to python expressions
4b 4*b
x
y= 3( ) y= 3 * x/2
2
x+2
a= a=(x+2)/(b-1)
b−1
Operators
Operators can be defined as symbols that are used to perform operations on operands.

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(-)

Types of operators based on no. of operands:


Unary operator: takes only one operand
Binary operator: takes two operands
Note + is also used for string concatenation

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.

Operators Description Example


and The expression x and y first evaluates x; Syntax :-
if x is false, its value is returned; x and y
otherwise, y is evaluated and the resulting
value is returned. >>> 3>2 and 7>5
True
>>> 5 and 8
8
>>> 0 and 8
0
or The expression x or y first evaluates x; if x is Syntax :-
true, its value is returned; otherwise, y is x or y
evaluated and the resulting value is >>> 3>2 or 7>5
returned. True
>>> 5 or 8
5
>>> 0 or 8
8
not The operator not  returns  True Syntax: not expression

 if its argument is false, False otherwise.

4. Assignment Operators & Short Hand(Augmented ) assignment operators:


Used to assign values to the variables.
= += /= *= -= %= //= **=

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)

Associativity is used when two operators of same precedence appear in an expression.


Associativity can be either Left to Right or Right to Left. For example ‘*’ and ‘/’ have same
precedence and their associativity is Left to Right, so the expression “100 / 10 * 10” is treated
as “(100 / 10) * 10”.
Operator Description
() [ ] { } Parenthesis, square brackets,curly braces
** Exponentiation (raise to the power)
~+- Complement, unary plus and minus

* / % // 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
not or and Logical operators

Right to Left associativity


print(4 ** 2 ** 3)
Exponentiation ** has Right to Left associativity in python
4 ** 2 ** 3
4**8

What Are Nonassociative Operators In Python?


Python does have some operators such as assignment operators and comparison operators
which don’t support associativity. Instead, there are special rules for the ordering of this type of
operator which can’t be managed via associativity.

Conditional statements
if Statement

Syntax

if test_expression:

statement(s)

Python interprets non-zero values as True. None and 0 are interpreted as False.

# If the number is positive, we print an appropriate message


num = 3
if num > 0:
print(num, "is a positive number.") #OBSERVE INDENTATION
print("This is always printed.")

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

# Program checks if the number is positive or negative


# And displays an appropriate message
num = int(input(" Enter a number:"))
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")

if-elif-else

Syntax of if...elif...else

if test expression:

Body of if

elif test expression:

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.

num = int(input(" Enter a number:"))

if num > 0:
print("Positive number")
elif num == 0:
print("Zero ")
else:
print("Negative number")

Notion of iterative computation and control flow

Loops/REPETITIVE STATEMENTS/ITERATIVE STATEMENTS are used in programming to repeat a


specific block of code.
while loop

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

# To take input from the user,


n = int(input("Enter n: "))

# initialize sum and counter


sum = 0
i=1
while i <= n:
sum = sum + i
i = i+1 # update counter

# print the sum


print("The sum is", sum)

While loop iterates till the condition is true.


It is an entry controlled loop
i=1
while i < 6:
print(i)
i += 1
Note: Remember to update the value of i ,otherwise it will continue forever.

while loop with else


we can have an optional else block with while loop.
The else part is executed if the condition in the while loop evaluates to False.
The while loop can be terminated with a break statement. In such case, the else part is ignored.
Hence, a while loop's else part runs if no break occurs and the condition is false.

counter = 0
while counter < 3:
print("Inside loop")
counter = counter + 1
else:
print("Inside else")

break and continue

What is the use of break and continue in Python?

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 and continue statements are used in these cases.

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

Python continue statement

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

for val in sequence:

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.

Program to find the sum of all numbers stored in a list

# 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)

The range() function


We can generate a sequence of numbers using range() function. range(10) will generate
numbers from 0 to 9 (10 numbers).
We can also define the start, stop and step size as range(start,stop,step size).
step size defaults to 1 if not provided.

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)

for loop with else


A for loop can have an optional else block as well. The else part is executed if the. items in the
sequence used in for loop exhausts.
break statement can be used to stop a for loop. In such case, the else part is ignored.
Hence, a for loop's else part runs if no break occurs.

IDEAS OF DEBUGGING
Bug means an error. DEBUGGING means removing the errors.

Errors And Exceptions


Exceptions are python way of notifying errors.
Exception Name When it is raised or thrown
SyntaxError Raised by interpreter when syntax error is encountered.
IndentationError Raised when there is incorrect indentation.
Raised when a function gets argument of correct type but improper
ValueError
value.
Raised when second operand of division or modulo operation is
ZeroDivisionError
zero.
NameError Raised when a variable is not found.
Raised when a function or operation is applied to an object of
TypeError
incorrect type.
ImportError Raised when the imported module is not found.
IndexError Raised when index of a sequence is out of range.
KeyError Raised when a key is not found in a dictionary.

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

Python also provides the raise keyword to be used in the context of exception handling. It


causes an exception to be generated explicitly. Built-in errors are raised implicitly. However, a
built-in or custom exception can be forced during execution.

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

ACCESSING CHARACTERS IN STRING

#initializes a string str1


>>> str1 = 'Hello World!'
#gives the first character of str1
>>> str1[0]
'H'
#gives seventh character of str1
>>> str1[6]
'W'
#gives last character of str1
>>> str1[11]
'!'
#gives error as index is out of range
>>> str1[15]
IndexError: string index out of range
STRING IS IMMUTABLE
A string is an immutable data type. It means that the contents of the
string cannot be changed after it has been created. An attempt to do this
would lead to an error.

>>> str1 = "Hello World!"


#if we try to replace character 'e' with 'a'
>>> str1[1] = 'a'
TypeError: 'str' object does not support item assignment
STRING OPERATIONS
CONCATENATION(+)
>>> str1 = 'Hello' #First string
>>> str2 = 'World!' #Second string
>>> str1 + str2 #Concatenated strings
'HelloWorld!'
#str1 and str2 remain same
>>> str1 #after this operation.
'Hello'
>>> str2
'World!'

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

str1 = 'Hello World!'


for ch in str1:
print(ch,end = '')

Hello World! #output of for loop


STRING BUILT IN METHODS AND FUNCTIONS
len() startswith() lstrip()
title() isalnum() rstrip()
lower() isalpha() strip()
upper() isdecimal() replace(oldstr,newstr)
count(str,start, end) islower() join()
find(str,start,end) isupper() partition()
index(str, start, end) isspace(), split()
endswith() istitle()  
LIST:
LIST DEFINITION AND REPRSENTATION IN PYTHON:
The data type list is an ordered sequence which is mutable and made up of one
or more elements.
A list can have elements of different data types, such as integer, float, string,
tuple or even another list.

Elements of a list are enclosed in square brackets and are separated by


comma.
Syntax:
List_Name=[value1,value2,……...,valueN]
Index: 0 1 N-1

#list1 is the list of six even numbers


>>> list1 = [2,4,6,8,10,12]
>>> print(list1)
[2, 4, 6, 8, 10, 12]

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

ACCESSING ELEMENTS IN LIST


#initializes a list list1
>>> list1 = [2,4,6,8,10,12]
>>> list1[0] #return first element of list1
2
>>> list1[3] #return fourth element of list1
8

LIST IS MUTABLE

In Python, lists are mutable. It means that the contentsof the list can be changed
after it has been created.

#List list1 of colors


>>> list1 = ['Red','Green','Blue','Orange']

#change/override the fourth element of list1


>>> list1[3] = 'Black'
>>> list1 #print the modified list list1
['Red', 'Green', 'Blue', 'Black']

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']

MEMBERSHIP(in) – Same as Strings

SLICING([ start:stop:step]) – Same as Strings


TRAVERSING A LIST
list1 = ['Red','Green','Blue','Yellow','Black']
for item in list1:
print(item)

LIST BUILT IN METHODS AND FUNCTIONS


len() count() sort()
sorted(
list() index() )
append( remove(
) ) min()
extend() pop() max()
reverse(
insert() ) sum()

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

TUPLE IS IMMUTABLE - Same as String

TUPLE OPERATIONS -- Same as String


CONCATENATION(+)
REPETITION(*)
MEMBERSHIP(in)
SLICING([ start:stop:step])
TRAVERSING A TUPLE - - Same as List
TUPLE BUILT IN METHODS AND FUNCTIONS
len() min()
tuple() max()
sorted(
) sum()
count() index()

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}

ACCESSING ELEMENTS OF DICTIONARY

>>> dict3 = {'Mohan':95,'Ram':89,'Suhel':92,


'Sangeeta':85}
>>> dict3['Ram']
89
>>> dict3['Sangeeta']
85
#the key does not exist
>>> dict3['Shyam']
KeyError: 'Shyam'
DICTIONARY IS MUTABLE

We can add a new item to the dictionary as shown in


the following example:
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
>>> dict1['Meena'] = 78
>>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 92,
'Sangeeta': 85, 'Meena': 78}
>>>dict1['Suhel'] = 93.5 #modifies existing value

DICTIONARY OPERATIONS: MEMBERSHIP

>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,


'Sangeeta':85}
>>> 'Suhel' in dict1
True

TRAVERSING A DICTIONARY

>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,


'Sangeeta':85}
Method 1
>>> for key in dict1:
print(key,':',dict1[key])

Method 2
>>> for key,value in dict1.items():
print(key,':',value)

DICTIONARY BUILT IN METHODS AND FUNCTIONS


len() get()
update(
dict() )
keys() del()
values(
) clear()
items()  

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)

statistics (mean, median,mode)


import statistics
help(statistics)

RANDOM MODULE:

random (random, randint, randrange)


import random
help(random)

random.random()

Return the next random floating point number in the range [0.0, 1.0).

random.randint(a, b)

Return a random integer N such that a <= N <= b.

random.randrange(stop)

random.randrange(start, stop[, step])

Return a randomly selected element from range(start, stop, step).

You might also like