Chapter 1 Python Revision Tour
Chapter 1 Python Revision Tour
# This is comment
a=10
def hello():
pass
for x in range(1,6):
print(x)
In the above program
➢ a, x, and hello are Identifier (Variable)
➢ = and in are Operators
➢ 10, 1 and 6 are Literals
➢ def, for and pass are Keywords
➢ : and ( ) are Punctuaters
➢ print and range are python Inbuilt functions
Questions
➔ Who invented Python and when?
➔ Smallest unit in a python program is known as _______
➔ What is the role of interpreter.
➔ Python files ends with ______ extension.
➔ What is the use of comments in python.
Keywords
Also known as Reserved words.
These are pre-defined words in python programming reserved for specific
work or task.
Example – if, else, for, while, continue, break, import, def, True, False,
None etc.
Identifies
These are the names given by the programmer.
Identifier can be names of variables, functions, classes etc.
Rules for Declaring Identifiers
✔ Keywords are not allowed.
✔ We can only use letters, digits or underscore.
✔ It cannot start with a digit.
✔ No spaces are allowed.
✔ Identifiers are case sensitive.
Punctuators
Also known as Separators.
These are special symbols used for organizing python code.
Example - “ , #, \, [ ], { }, = etc
Questions
➔What is the smallest unit in Python?
➔Find the valid Identifier
1) while
2) 12hello
3) _today
4) for
➔what are seperators?
➔What is “true” Identifier or Keyword?
Literals
These are constant values.
Types
Numeric Literals
Integer
Decimal (34) Octal (0o17) Binary (0b101)
Hexadecimal (0x45)
Float
(14.2), (-18.34)
Complex
(a+bj) –
a = (5+4j) (a.real)(a.imge)
Boolean Literals
This constant only includes True and False.
Sequences
Sequences supports indexing this includes String, list and Tuple.
String Literals
Single line literals
It is enclosed within single quotes. ‘Hello 123’
Multi line literals
It is enclosed within triple quotes.
‘ ‘ ‘ hello world 123
we are learning python’ ’ ’
or
“hello ------\
today”
Escape Sequence - \n, \t and \a
Sets – {34,45,12,44}
Inbuilt
Python inbuilt basically includes python built in functions like print(),
input(), int(), float() etc. These are used to create python statements.
Basic Inbuilt Functions
print() - Print data on screen.
input() - Takes input from user in string form.
id () - It returns unique id (physical address of an object)
identifier.
type () - Return type of data value.
int () - Converts data to integer form.
float() - Converts data to floating point form.
str() - Converts data to string sequence.
list() - Converts data to list sequence.
tuple() - Converts data to tuple sequence.
eval() - It evaluates and expression and gives a specific result.
Questions
✔ Literals are also known as ______ values.
✔ Name the literal (3).
✔ What type of argument is “end”
✔ What is the default data type returned by input().
Operators
A Symbol or word that operates on operands and perform specific task.
These can be operated in Binary or Unary form.
Unary
(-, ~ and not)
Binary
Questions
✔ What is difference between is and == operator
✔ What are operands?
✔ What is the use of memebership operator.
✔ Find the odd one from the following
==
<
>
and
Variable in Python
These are named memory location used to store data values.
Creating Variable
Variable in python is declared when we first assign value to it.
Examples
a= 10 #integer
b=78.45 #Floating point
c=23+56j #Complex
p= “Hello” #String
c=[“hello”, 34, 56.65] #list
d= (45,67,78) or 45,67,78 #Tuple
e= {1: “hello” ,2: “Today”}#Dictionary
s={45,56,78,80} #Sets
Expressions
These are the combination of constant variable and operators.
Comments
These are non executable additional statements in python programming
used for clarifying python source code.
Types – Single line or Inline or multi line.
Questions
✔ What is None in Python?
✔ What is the use of comments?
✔ Write expression for declaring multiple variables in python.
✔ Justify the statement python is implicit langauge.
Data Types
Datatype is type of Data. It can be numeric, string, float, boolean
etc.
Types of Data Types in Python
1. Numeric
1.1. Integer
a) Decimal (67)
b) Binary (0b1010)
c) Octal (0o357)
d) Hexadecimal (0x 2A)
1.2. Floating Point (45.565)
1.3. Complex (45+44b)
2. String – Single line, Multi line and Escape sequence.
3. Python Collection – List and Tuple
4. Mapping – Dictionary
5. Sets
6. Special Type – None (or non type)
Immutable Types
In same address new value cannot be saved. (Value change will also
change address or id). Integer, float, boolean, string and tuple.
Example
a=5
print(id(a)) #id or address
a=9
print(id(a)) #Same id or address
Question
✔ Name any two ordered data types in Python?
✔ What is null data type?
✔ What is difference between Mutable and Immutable data type?
✔ What is use of int()?
✔ State true or false (Python is Implicitly typed)
Python Statements
These are the set of instructions which are written using python
programming rules and executed on python interpreter.
Programming Statements
Set of instructions that are written according programming rules.
Compound Statement
These are group of statements that acts as a single unit.
It includes a header part followed by a colon (:).
Syntax
header :
statement
if condition :
statement(s)
for variable in sequence:
statement(s)
Flow of Control
It defines order of execution.
Sequence
Executed line by line.
Selection/Conditional/Branching
Executed based on a condition test. (if elif else)
Iterative/Looping
Executed until a condition is True. (for and while)
Jumping
When we jump at different position within a program.
Questions
✔ What is Empty Statement.
✔ What are compound statements. Give two example?
✔ What is use of colon(:)?
✔ What is flow of execution, give an example of conditional statement.
Selection/Conditional/Branching
Executed based on a condition test. (if elif else)
Simple if
if True:
print("Hi") Output
if 10:
print("Hi")
Hi
a=90 Hi
if a>10: Hi
print("Hi")
if else
if False:
print("Hi")
else:
print("Bye")
a=100
if a!=100:
print("It is 100")
else: Output
print("It is not 100") Bye
a=100 It is not 100
if a==100: It is 100
print("It is 100")
else:
print("It is not 100")
if elif else
a=int(input("Enter a Number : "))
if a==10:
print("Number is exactly 10")
elif a>10 and a<=40:
print("Number is between 10 and 40")
elif a>40 and a<100:
print("Number is between 50 and 100")
else:
print(" Number is greator than 99 ")
Output
Enter a Number : 90
Number is between 50 and 100
Nested if
a=9
if True: Output
if a<10:
if False:
Hello
print("Hi")
else:
print("Hello")
else:
print("Outer else")
Questions
✔ What is difference between if and else?
✔ What is difference between nested if and if else.
✔ Find the output
a=3
if a:
print(print("Hello"))
Iterative Statements(Loops)
These statements are used to repeat statement(s) until a condition is True.
Types for and while
There are four mandatory parts of Iterative/Looping Statements.
1. Start/Initialization
2. End/Destination
3. Steps (Increment or Decrement)
4. Body of the loop/Statements to be repeated.
For loop
Syntax of for loop
for variable in range(values)/Sequence:
statement(s)
Sequence can be – String list tuple and dictionary.
range() - It is used to create a sequence.
Examples
String
for x in “Hello”:
print(x,end= “-”)
Output – H-e-l-l-o
List
for y in [2,4,45]:
print(y)
Output
2
4
45
range(1,10,2) – 1 3 5 7
range(5,1,-1) – 5 4 3 2
range(5,-3,-1) – 5, 4, 3, 2, 1, 0, -1, -2
While loop
Syntax of while loop
a=1 #Initialization (Start)
while a<=5: #Conditional test (end)
print(a) #Body of loop statement
a=a+1 #update (Increment or decrement)
Questions
✔ What is the default starting value of range()?
✔ Why steps are mandatory part of while loop.
✔ Find the output
for x in [3,4,5]:
print(x**2)
✔ Print all two digits number using while loop.
Nesting of Looping
When one is inside the body of another loop it is known as nesting of loop.
Example: Output
for x in range(1,6):
for y in range(1,6):
12345
print(y, end= “ ”) 12345
print() 12345
12345
12345
x=1
while x<=5:
y=1
while y<=5:
print(y, end= “ ”)
y=y+1
print()
x=x+1
Jumping Statements
Break Statement
It terminates the current loop and transfers the controls to the next python
statement.
Example
for x in range(10):
print(x, end = “ ”)
if x==5:
break
Output: 0 1 2 3 4
Continue Statement
It skips the statement(s) followed by continue keyword and transfers
control to the top of the loop.
Example
for x in range(10):
if x==3:
continue
print(“Hello”, x, end= “ ”)
Output
012456789
Questions
✔ What is the use of nesting?
✔ What is difference between break and continue
✔ __________ statement skips the upcoming code.
✔ Can we use break and continue within same loop.
String
It is a sequence of ASCII or Unicode characters enclosed within single
(‘hello’) or double (“hello world”) or triple (‘ ‘ ‘ hello world’ ’ ’).
It is Immutable (Non Changeable)
Note:- input() function is used to input string from user.
String Indexing
String supports both positive and negative indexing.
Example – “HELLO 123@”
Positive Indexing
0 1 2 3 4 5 6 7 8 9
H E L L 0 1 2 3 @
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Negative Indexing
Accessing elements of String (Hello)
1. Accessing Single element through index number
Example –
print(a[1]) or print(a[-4])
Output – e
2. Using loop
for x in “Hello”:
print(x, end= “ ”)
Output
Hello
String Functions
str() - Converts from other sequence to string.
a=[1,4,6]
b=str(a)
len() - Returns length of string. (Elements in String)
a=”Hello”
print(len(a)) – 5
capitalize() - Capitalize a string.
a= “hello”
print(A.capitalize()) - Hello
upper() and lower() - Converts to uppercase and lowercase.
a= ‘hello WORLD’
print(a.upper()) = HELLO WORLD
print(a.lower()) - hello world
count() - Counts a sub string in a main string.
a= “Today is great”
print(a.count(‘a’)) – 2
replace() - Replace old string with new one.
a= “Hello we are learning’
print(a.replace(‘We’, ‘it’) – Hello it are learning.
Strip() - It strips out the unwanted spaces from a string.
a=“ Hello ”
print(a.strip()) - Hello
we can also use lstrip(), rstrip() for string from left or right.
Data Checking Functions
Syntax – String.function()
isalnum() - Checks for alphabets or number.
isdigit() - Checks digits.
isspace() - Checks for space.
isalpha() - Checks for alphabets.
islower() - Checks for lowercase letters.
isupper() - Check for uppercase letters.
Questions
✔ What is the role of Escape sequence \n
✔ Write a program to find total number of vowels in the following
string.
“This is python programming”
✔ Name the function used for converting other sequences to string.
✔ Find the output
a = “This is a sequence”
print(a[2:12:2])
List
It is a datatype (Inbuilt Data Structure) in which we can store different data
values in an ordered sequence. (Indexing)
It is mutable (Changeable).
Examples
a=[] #Empty List
a= [1,4,8] #Integer List
a = [2, 8, [14, “Hello”], 18] #Nested List
a= [4, 8, 6, 9, #Long List
16, 1, 17,
18, 13]
Note – list() is used to convert other sequence to list. It is also used to
create a copy (different address).
a = “Hello”
print(list(a)) = [‘H’, ‘e’, ‘l’, ‘l’, ‘o’]
a={1:4, 8:14, 5:58}
print(list(a)) – [1, 8, 5]
print(list(a.values()) - [4, 14, 58]
List Indexing
Supports both positive and negative indexing.
Example
a=[14, 8, “Hello”, [2,4], 81, 41]
Positive Indexing
0 1 2 3 4 5
14 8 Hello [2,4] 81 41
-6 -5 -4 -3 -2 -1
Negative Indexing
List Slicing
a=[14, 8, “Hello”, [2,4], 81, 41]
Input Output
print(a[:]) [14, 8, “Hello”, [2,4], 81, 41]
print(a[2:]) [“Hello”, [2,4], 81, 41]
print(a[0:5:2]) [14, “Hello”, 81]
List Operators
1. Membership Operator (in, not in)
print(14 in [12, 14, 18]) → True
2. Concatenation/Addition ( + )
print([3,2,4] + [18, 19]) → [3, 2, 4, 18, 19]
3. Replication Operator ( * )
print([2,4,6]*2) → [2,4,6,2,4,6]
4. Relational/Comparison Operators (<, <=, >, >=, !=, ==)
print([2,4,6]==[4,8,6]) → False
List Functions
list()
Converts all other sequences to list. Also make a real copy.
print(list(“Hello”)) → [‘H’, ‘e’, ‘l’, ‘l’, ‘o’]
len()
Returns length of string (Elements of list)
print(len(14,2,8, ‘Hello’)) → 4
append()
It is used to add new element at the end of list.
a=[2,4,6]
a.append(“Hello”)
print(a) → [2,4,6, “Hello”]
insert()
It is used to add element at specific index.
a=[1,2,5]
a.insert(1,100)
print(a) → [1, 100, 2, 5]
extend()
It is used to add new list to existing list.
a=[2,8,7]
a.extend(2,4]) → [2, 8, 7, 2, 4]
pop()
It deletes (popes out) last element from list. It can also delete element
based on Index number.
a=[2,8,7,9]
a.pop()
print(a) → [2,8,7]
a.pop(1)
print(a) → [2,7]
clear()
It clear the list element and makes a empty list.
a=[4, 2, 7]
a.clear()
print(a) →[]
remove()
It removes given first element from the list.
a=[4,2,7,4,5]
a.remove(4)
print(a) → [2,7,4,5]
index()
It returns first index of an element.
a=[4,7,13]
print(a.index(7)) → 1
reverse()
It reverses list elements.
a=[4,13, “Hello”)
a.reverse()
print(a) → [“Hello”, 13, 4]
sort()
Sort a list and works only with same data types.
a=[4, 9, 1, 7 , 2]
a.sort()
print(a) → [1, 2, 4, 7, 9]
min(), max() and sum()
a=1, 2, 8, 7]
b=["Karan","Suraj", "Vijay","Riya"]
print(max(b)) → Vijay
print(min(a)) →1
print(sum(a)) → 23
Note: - del keyword can also be used for deleting data with variable. For
example del a, b, c
Questions
✔ What is list data type, what is difference between string and list.
✔ Find the output
a=[3,5,[5,6],6]
print(a[2][-1])
✔ Find the output
a=[3,5,9]
a.append(“Hello”)
a.pop(2)
a.append(90)
print(a)
✔ What is the difference between insert and extend.
Tuple
It is a datatype used to store different data values in an ordered sequence.
It is Immutable (Non Changeable).
Examples
a = 2, 4 #Tuple without ( )
a= (1,4,8) #Integer Tuple
a =(2, 8, [14, “Hello”], 18) #Nested Tuple
a= (4, 8, 6, 9, #Long Tuple
16, 1, 17,
18, 13)
Note – tuple() is used to convert other sequence to Tuple.
a = “Hello”
print(tuple(a)) = (‘H’, ‘e’, ‘l’, ‘l’, ‘o’])
a={1:4, 8:14, 5:58}
print(tuple(a)) – (1, 8, 5)
print(tuple(a.values()) - (4, 14, 58)
Tuple Indexing
Supports both positive and negative indexing.
Example
a=(4, 8, “Hello”, [2,4], 81, 41)
Positive Indexing
0 1 2 3 4 5
14 8 Hello [2,4] 81 41
-6 -5 -4 -3 -2 -1
Negative Indexing
Tuple Slicing
a=(14, 8, “Hello”, [2,4], 81, 41)
Input Output
print(a[:]) (14, 8, “Hello”, [2,4], 81, 41)
print(a[2:]) (“Hello”, [2,4], 81, 41)
print(a[0:5:2]) (14, “Hello”, 81)
Tuple Operators
1. Membership Operator (in, not in)
print(14 in (12, 14, 18)) → True
2. Concatenation/Addition ( + )
print((3,2,4) + (18, 19)) → (3, 2, 4, 18, 19)
3. Replication Operator ( * )
print((2,4,6)*2) → (2,4,6,2,4,6)
4. Relational/Comparison Operators (<, <=, >, >=, !=, ==)
print((2,4,6)==(4,8,6)) → False
Questions
✔ What is tuple data type, what is difference between list and tuple.
✔ Find the output
a=(3,5,8,[5,6,4],6]
print(a[-2][-1])
✔ Give an example of unpacking in tuple
✔ What is the difference between mutable and immutable data types.
Dictionary
It is a data type that is used to store different data values in Key:Value
format.
It is mutable (Changeable).
Syntax
variable = {Key:Value, Key:value, _ _ _ _ _ }
Keys can be Immutable type only – Integer, Float, String and Tuple.
Values can be of any data type.
Example
a = {‘Hello’:14, 18:(8, ‘Today’)}
Using loop
for x in a or a.keys():
print(x)
Output
Hello
18
for x in a.values():
print(x)
Output
14
(8, ‘Today’)
for x in a.items():
print(x)
Output
(‘Hello’,14)
(18, (8, ‘Today’))
Dictionary Operator
Membership Operators
a = { 1:20, 2:80, 4: ‘Hello’ }
print(2 in a) → True
Note: It only checks for keys.
For values
a = { 1:20, 2:80, 4: ‘Hello’ }
print(80 in a.values()) → True
Dictionary Functions
len()
Returns total number of key:value pair in dictionary.
a={1:14, 2:18}
print(len(a)) →2
pop()
Pops out a pair, based on key.
a={1:14, 2:18}
a.pop(1)
print(a) → {2:18}
clear()
Clears the dictionary elements.
a={1:14, 2:18}
a.clear()
print(a) →{}
update()
It is used to add new dictionary to existing dictionary.
a={1:14, 2:18}
b={5:28}
a.update(b)
print(a) → {1:14, 2:18, 5:28}
Note:- To completely delete dictionary data with variable we can use
del keyword.
enumerate() function/method
k=(2,3,4,5,6)
v=(20,30,40,50,60)
d=dict(enumerate(v))
print(d)
Output
{0: 20, 1: 30, 2: 40, 3: 50, 4: 60}
Using tuples
k=[(2,3),(4,5),(6,7)]
d=dict(k)
print(d)
Output
{2: 3, 4: 5, 6: 7}
Using loop
a=[2,3,4,5,6]
d={x:x**3 for x in a}
print(d)
Output
{2: 8, 3: 27, 4: 64, 5: 125, 6: 216}
Questions
✔ Write any two applications of Dictionary data type.
✔ Given two list [3,4,5] and [“Karan”, “Diya”, “Suraj”] create a new
dictionary in key value form.
✔ Explain the working of pop() function
✔ What is the use of items().