0% found this document useful (0 votes)
6 views16 pages

Revision Notes

The document provides a comprehensive overview of Python programming, including its characteristics, data types, operators, control structures, and built-in functions. It covers essential concepts such as variables, mutable and immutable types, loops, strings, lists, tuples, and dictionaries, along with examples and syntax. Additionally, it includes multiple-choice questions to test understanding of Python fundamentals.

Uploaded by

ka.yht333
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views16 pages

Revision Notes

The document provides a comprehensive overview of Python programming, including its characteristics, data types, operators, control structures, and built-in functions. It covers essential concepts such as variables, mutable and immutable types, loops, strings, lists, tuples, and dictionaries, along with examples and syntax. Additionally, it includes multiple-choice questions to test understanding of Python fundamentals.

Uploaded by

ka.yht333
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

REVIEW OF PYTHON

Characteristics of Python: Object-Oriented, Open-Source, Portable, Platform-independent,


interpreted Language developed by Guido Van Rossum in 1991.
Character Set of Python: Set of all characters recognised by python. It includes:
• Letters: A- Z and a -z
• Digits: 0-9
• Special Symbols: + , - , /, % , ** , * , [ ], { }, #, $ etc.
• White spaces: Blank space, tabs, carriage return, newline, form feed
• Other Characters: All ASCII and UNICODE characters.
Tokens: Tokens are smallest identifiable units in a python program. Different tokens are:
● Keywords: reserved words which are having special meaning. Examples: int, print,
input, for, while
● Identifiers: name given by programmer to identify variables, functions, constants, etc.
● Literals: literals are constant values.
● Operators: Operators trigger an operation. Parameters provided to the operators are
called operands. Examples: + - * % ** / //
● Delimiters: Symbols used as separators. Examples: {} , [ ] ; :

Rules for identifier names:


● Keywords cannot be used
● Can contain A-Z,a-z,0-9 and underscore(_)
● Cannot start with a number.
Example: engmark, _abc , mark1, mark2

Variables and data types: Variables are used to store data. Data types of variables:
● Numeric Types: int, float, complex
● Boolean – True or False values.
● None – a special type with an unidentified value or absence of value.
● Sequence: an ordered collection of elements. String, List and Tuples are sequences.
● Mappings – Dictionaries are mappings. Elements of dictionaries are key-value pairs.

Mutable and Immutable types:


Mutable -Values can be changed in place. E.g. List, Dictionary
Immutable: Values cannot be changed in place in memory. E.g., int, float, str, tuple.

Assigning Values to Variables:


The assignment operator (=) is used to assign values to variables. E.g. a = 100

Multiple Assignments:
• Assigning same value to multiple variables - a=b=c=1
• Different values to different variables- a, b, c = 5,10,20

print statement: used to display output. If variables are specified i.e., without quotes then value
contained in variable is displayed.
E.g., x = "kve " Output:
print(x) kve

To combine both text and a str variable, Python uses the “+” character:
Example
x = "awesome" Output:
print("Python is " + x) Python is awesome

Expressions: An expression is combination of values, variables and operators. E.g. – x= 3*3//5


Operators: Operators trigger an operation. Some operators need one operand, some need more
than one operand to perform the operation. Types of operators:
• Arithmetic Operators: + - * / (division) // (Floor division) % (remainder) ** (power)
• Relational Operators > < >= <= = = (equality) != (inequality)
• Logical Operators: not and or

Precedence of Operators: The operator having high priority is evaluated first compared to an
operator in lower order of precedence when used in an expression.

Examples:
1. x = 7 + 3 * 2 2. >>> 3+4*2
13 11
* has higher precedence than +, so it first Multiplication gets evaluated before the
multiplies 3*2 and then adds into 7 addition operation

Comments: Comments are ignored by the Python interpreter. Comments gives some message
to the Programmer. It can be used to document the code. Comments can be:
• Single-line comments: It begins with a hash(#) symbol and the whole line is considered
as a comment until the end of line.
• Multi line comment is useful when we need to comment on many lines. In python, triple
double quote (" " ") and single quote (' ' ') are used for multi-line commenting.
Example:
# This is a single line comment
' ' 'I am a multi
line comment ' ' '

input() function:An input() function is used to receive the input from the user through the
keyboard. Example: x=input('Enter your name')
age = int( input ('Enter your age'))
Selection Statements: It helps us to execute some statements based on whether the condition
is evaluated to True or False.
if statement: A decision is made based on the result of the comparison/condition. If condition is
True then statement(s) is executed otherwise not.
Syntax:
if <expression>:
statement(s)
Example:
a=3 Output:
if a > 2: 3 is greater
print(a, "is greater") done
print("done")

If-else statement:
If condition is True then if-block is executed otherwise else-block is executed.
Syntax:
if test expression:
Body of if stmts
else:
Body of else
Example:
a=int(input('enter the number')) Output:
if a>5: enter the number 2
print("a is greater") a is smaller than the input given
else:
print("a is smaller than the input given")

If-elif-else statement: The elif statement allows us to check multiple expressions for TRUE
and execute a block of code as soon as one of the conditions evaluates to TRUE.
Syntax:
If <test expression>:
Body of if stmts
elif < test expression>:
Body of elif stmts
else:
Body of else stmts
Example:
var = 100 Output:
if var == 200: 3 - Got a true expression value
print("1 - Got a true expression value") 100
print(var)
elif var == 150:
print("2 - Got a true expression value")
print(var)
elif var == 100:
print("3 - Got a true expression value")
print(var)
else:
print("4 - Got a false expression value")
print(var)

Iteration/Repetition: Repeated execution of a set of statements is called iteration. The


for-statement and while- statements can be used

While loop: while loop keeps iterating a block of code defined inside it until the desired
condition is met.

Syntax: Example: Output:


while(expression): i=1 KV School
Statement(s) while i<=3: KV School
print("KV School") KV School
i=i+1

For loop: for loop iterates over the items of lists, tuples, strings, the dictionaries and other
iterable objects.
Syntax:
for <loopvariable> in <sequence>:
Statement(s)
Example 1: Output is:
L = [ 1, 2, 3, 4, 5] 12345
for var in L:
print( var, end=’ ‘)
Example 2: output: 0,1,2,3,4,5,6,7,8,9
for k in range(10):
print(k, end =’ , ‘)

‘break’ statement: Terminates the loop upon execution


‘continue’ Statement: Skips the current iteration / rest of the and continues on with the next
iteration in the loop.

Strings: A string is a sequence of characters. E.g. 'banana', "apple", '''orange'''

String slices: A segment or a part of a string is called a slice.


Syntax: string_object[Start: stop: steps]
● Slicing will start from index and will go up to stop(excluding stop) in step of steps.
● steps default is 1. If negative step then sequence will be decreasing order
● Default value of start is 0 if step is positive and the last item if step is negative
Example:
str = 'Hello World!' Output:
print (str[2:5] ) llo
print (str[2:]) llo World!

String concatenation: ‘+’ is string concatenation operator.


String repetition operators: ‘*’ is called repetition operator
print ( 'hello' * 2 ) Output:
print('hello' + 'world') hellohello
helloworld

String functions and methods:


Sno Method name Description
1. isalnum() Returns true if string has at least 1 character and all characters are
alphanumeric and false otherwise.
2. isalpha() Returns true if string has at least 1 character and all characters are
alphabetic and false otherwise.
3. isdigit() Returns true if string contains only digits and false otherwise.
4. islower() Returns true if string has at least 1 cased character and all cased
characters are in lowercase and false otherwise.
5. isnumeric() Returns true if a string contains only numeric characters and false
otherwise.
6. isspace() Returns true if string contains only whitespace characters and false
otherwise.
7. istitle() Returns true if string is properly “titlecased” and false otherwise.
8. isupper() Returns true if string has at least one cased character and all cased
characters are in uppercase and false otherwise.
9. replace(old,new[ Replaces all occurrences of old in string with new or at most max
, max]) occurrences if max given.
10. split() Splits string according to delimiter str (space if not provided) and
returns list of substrings;
11. count() Occurrence of a string in another string
12. find() Finding the index of the first occurrence of a string in another string
13. swapcase() Converts lowercase letters in a string to uppercase and viceversa
14. startswith(str, Determines if string or a substring of string (if starting index beg
beg=0, end= and ending index end are given) starts with substring str; returns
len(string)) true if so and false otherwise.

List:Lists are ordered mutable data types enclosed in square brackets. E.g., [ 'A', 87, 23.5 ]
Python has a set of built-in methods that you can use on lists
Method Description

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

extend() Add the elements of a list (or any iterable), to the end of the current list

index() Returns the index of the first element with the specified value

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the first item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list

Basic List Operations:


Lists respond to the + and * operators much like strings; they mean concatenation and repetition
here too, except that the result is a new list, not a string.

Python Expression Results Description


len([1, 2, 3]) 3 Length
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation
['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition
3 in [1, 2, 3] True Membership
for x in [1, 2, 3]: print x, 123 Iteration
Note: indexing and slicing are similar to that of strings. For example:
L= ['kvsch', 'school', 'KVSCH!']
Python Expression Results Description

L[2] KVSCH Offsets start at zero


L[-2] school Negative: count from the right

L[1:] ['school', 'KVSCH!'] Slicing fetches sections

Tuples: A tuple is a collection which is ordered and unchangeable. In Python tuples are
created by enclosing items within round brackets. Tuple is immutable. We can create tuple in
different ways.
X=( ) # an empty tuple
X=(1,2,3) # a tuple with three elements
X=tuple(list1)
X=1,2,3,4
Accessing elements of a tuple:
We can use index to access the elements of a tuple. From left to right, index varies from 0 to n-
1, where n is total number of elements in the tuple. From right to left, the index starts with -1 and
the index of the leftmost element will be –n, where n is the number of elements.
T = ( 1, 2,4,6) Output:
print(T[0]) 1
print(T[-1]) 6

Some important functions which can be used with tuple:


count (): Returns the number of times a specified value occurs in a tuple
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2) output: 4
>>> x.count(2)
index (): Searches the tuple for a specified value and returns its position in the tuple.
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2) Output: 1
>>> x.index(2)
len(): To know the number of items or values present in a tuple, we use len().
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2) output: 12
>>> y=len(x)
>>> print(y)

Dictionaries: A dictionary is a collection which is unordered, changeable and indexed. In


Python dictionaries are created with curly brackets, and they have keys and values. Values can
be of any type. Keys should be distinct and immutable data type.
Example: X={1:’A’,2:’B’,3:’c’}
X=dict([(‘a’,3) (‘b’,4)]
X=dict(A=1, B=2)
Functions available for handling dictionary:
Method Description
clear() Remove all items form the dictionary.
copy() Return a shallow copy of the dictionary.
Return a new dictionary with keys from seq and value equal to v
fromkeys(seq[, v]) (defaults to None).
Return the value of key. If key does not exit, return d (defaults
get(key[,d]) to None).
items() Return a new view of the dictionary's items (key, value).
keys() Return a new view of the dictionary's keys.
Remove the item with key and return its value or d if key is not
pop(key[,d])
found. If d is not provided and key is not found, raises KeyError.
Remove and return an arbitary item (key, value). Raises
popitem() KeyError if the dictionary is empty.

setdefault(key[,d]) If key is in the dictionary, return its value. If not, insert key
with a value of d and return d (defaults to None).

update([other]) Update the dictionary with the key/value pairs from other,
overwriting existing keys.
values() Return a new view of the dictionary's values
remove() It removes or pop the specific item of dictionary
del( ) Deletes a particular item
len( ) we use len() method to get the length of dictionary

Multiple Choice Questions


1. Which of the following is not a keyword?
a) Eval b) assert c) nonlocal d) pass
2. What is the order of precedence in python?
(i) Parentheses ii) Exponential iii) Multiplication iv) Division v) Addition vi)
Subtraction
a) i,ii,iii,iv,v,vi
b) ii,i,iii,iv,v,vi
c) ii,i,iv,iii,v,vi
d) i,ii,iii,iv,vi,v

3. What will be the value of X in the following Python expression?


X = 2+9*((3*12)-8)/10
a) 30.0 b) 30.8 c) 28.4 d) 27.2

7. Which of the following can be used as valid variable identifier(s) in Python?


a) total b) 7Salute c) Que$tion d) global

8. Which of the following statement is correct for an AND operator?


a) Python only evaluates the second argument if the first one is False
b) Python only evaluates the second argument if the first one is True
c) Python only evaluates True if any one argument is True
d) Python only evaluates False if any one argument is False

10. Which point can be considered as difference between string and list?
a. Length c. Indexing and Slicing
b. Mutability d. Accessing individual elements

11.Which of the following statement is true for extend () list method?


a) adds element at last c) adds multiple elements at last
b) adds element at specified index d) adds elements at random index
12.The statement del l[1:3] do which of the following task?
a) delete elements 2 to 4 elements from the list
b) delete 2nd and 3rd element from the list
c) deletes 1st and 3rd element from the list
d) deletes 1st, 2nd and 3rd element from the list
13. If l=[11,22,33,44], then output of print(len(l)) will be
a)4 b)3 c) 8 d) 6
15. The step argument in range() function .
a. indicates the beginning of the sequence
b. indicates the end of the sequence
c. indicates the difference between every two consecutive numbers in the sequence
d. generates numbers up to a specified value

16. If D=1,2,3
What will be the data type of D?
a) List b)tuple c)set d)invalid type

17.Consider the following code


L=[‘a’,’b’,’c’,’d’]
L.pop(-1)
print(L)
What would be the output?
a)’d’ b)[‘a’,’b’,’c’,’d’] c)[‘a’,’b’,’c’] d)error

18 What is the output when the following code is executed?


>>>name=[‘Aadi’,’Beena’,’Charlie’,’David’]
>>>print(name[-1][-1])
a) ’d’ b)’D’ c)’i’ d)Charlie
19. T=(“See You”)
What is the data type of T?
a) tuple b)string c)List d)set

20. Assertion(A):After adding element in a list, its memory location remains same
Reason(R):List is a mutable data type
a) Both A and R are True and R is the correct explanation for A
b) Both A and R are True and R is not the correct explanation for A
c) A is True but R is False
d) A is False but R is True

21. Assertion(A):An identifier may be combination of letters and numbers.


Reason(R):No special symbols are permitted in an identifier name
a)Both A and R are True and R is the correct explanation for A
b) Both A and R are True and R is not the correct explanation for A
c) A is True but R is False
d) A is False but R is True

Answers of MCQ:
1)a 2)a 3)b 4)a 5)d 6)c 7)a 8)b 9) d 10)b 11)b 12)b 13)a 14)c
15)c 16)b 17)c 18)a 19)b 20)a 21)c

Very Short Answer Type Questions


1. Give the output of the following
Sum = 0
for k in range(5):
Sum = Sum+k
print(Sum)

2. Give the output of the following


Sum = 0
for k in range(10 , 1, -2):
Sum = Sum+k
print(Sum)

3. Give the output of the following


for k in range(4):
for j in range(k):
print(‘*’, end = ‘ ‘)
print()

4. Give the output of the following


for k in range(5,0, -1):
for j in range(k):
print(‘*’, end=’ ‘)
print()

5. How many times the following loop will execute? Justify your answer
A=0
while True:
print(A)
A =A+1
6. Give the output of the following. Also find how many times the loop will execute.
A=0
while A<10:
print(A, ‘ , ‘)
A =A+1

7. Give the output of the following. Also find how many times the loop will execute.
A=0
while A<10:
print(A, ‘ , ‘)
A =A+1
print(‘\n’, A)

8. Give the output of the following


T = (5)
T = T*2
print(T)

9. Give the output of the following


T = (5, )
T = T*2
print(T)
10. What kind of error message will be generated if the following code is executed
A=5
B = ‘hi’
d = A+B
print(D)
11. Give the output of the following
L = [1,2,3,4,5,6,7,8,9]
print(L[:])

12. Give the output of the following


L = [1,2,3,4,5,6,7,8,9]
print(L[: -1])

13. Find the output of the following


S = ‘abcdefgh’
L = list(S)
print(L[1:4])

14. Give the output of the following


L = [1,2,3,4,5,6,7,8,9]
print(L.count(2))
print(L.index(2)
15. Write python code to sort the list, L, in descending order.

16. Give the output of the following


x=[4,5,66,9]
y=tuple(x)
print( y)
17.Guess the output?
if 8:
print(“Hello”)
if(-5):
print(“Hai”)

18.Find output.
vowels=['a','e','i']
vowels.append('o')
vowels.append(['u'])
vowels.extend(['A','E'])
print("New List:",vowels)
19.Given the following declaration, what will be the output of the following:
Lst=(1,2,3,4,5)
del Lst[2]
print(Lst)
20.Identify the statement(s) from the following options which will raise TypeError exception.
a)print(‘5’*’3’)
b)print(5*3)
c)print(‘5’+3)
d)print(‘5’+’3’)
e)print(‘5’*3)

Answers for VSA Questions

1)10
2)30
3)
*
* *
* * *

4) * * * * *
* ***
* * *
* *
*
5)infinite loop. Condition / test expression is always Ture.

6) 0,1,2,3,4,5,6,7,8,9

7) 0,1,2,3,4,5,6,7,8,9
10

8) 10 Note: here T is an integer

9) (5, 5), Note: here T is tuple

10)TypeError

11) [1,2,3,4,5,6,7,8,9]

12) [1,2,3,4,5,6,7,8]

13) ['b', 'c', 'd']


14) 1
1
15) L.sort(reverse= True)
16) (4, 5, 66, 9)
17)Hello
Hai
18) New List: ['a', 'e', 'i', 'o', ['u'], 'A', 'E']
19)Error
20) a)print(‘5’*’3’)
c)print(‘5’+3)

Short Answer Type Questions


1. Consider the following dictionary ‘D’. Display all the items of the dictionary as individual
tuple
D = {‘A’: 20, ‘B’: 30, ‘C’:40. ‘D’: 50}
2. Write Python code to remove an element as entered by the user form the list, L

3. Create a list k, by selecting all the odd numbers within the given range, m and n. User will
input the values of m , n at run time
4. Write Python code to create and add items to a dictionary. Ask the user to input key value
pairs. Continue as long as the user wishes.

5. Write Python code to find whether the given item is present in the given list using for loop.

6.Create a list, L, with the squares of numbers from 0 to 10


7. Write a program to accept a list of numbers and to create a dictionary with two keys ODD
and EVEN whose values are all the odd numbers from the list and all the even numbers from
the list respectively.

8. Mr. Rahul wants created a dictionary to store the details of his students and to
manipulate the data. He wrote a code in Python, help him to complete the code:
studentDict = # stmt 1
n = int(input("How Many Students you Want To Input?"))
for i in range( ): # stmt 2 - to enter n number of students data
rollno = input("Enter Roll No:")
name = input("Enter Name:")
physicsMarks = int(input("Enter Physics Marks:"))
chemistryMarks = int(input("Enter Chemistry Marks:"))
mathMarks = int(input("Enter Maths Marks:"))
studentDict[rollno]= # stmt 3
Answers /Hints: Short answer Type Questions.
1) for k in D.items():
print(k)
2) a =int(‘input the item to be deleted’)
l.remove(a)
3) m = int(input(‘lower limit’))
n = int(input(‘upper limit’))
n = n+1
L = [x for x in range(m, n) if x%2!=0]
4)D = { }
while True:
K = input(‘type a key’)
V = int(input(‘type the value’)
D[K] = V
C = input(‘type ‘y’ to add more’)
if C!=’y’:
break
5) flag = 0
L = eval(input(‘input a list on numbers’))
E = int(input(‘item to be searched’)
K =len(L)
for p in range(K):
if E ==L(p):
flag = 1
print(‘found and index is ‘,p)
if flag==0:
print(‘not found’)
6) list1=[]
for x in range(10):
list1.append(x**2)
list1
Output:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
OR
list1=list(map(lambda x:x**2, range(10)))
7) L=eval(input("Enter a list"))
D={"ODD":[],"EVEN":[]}
for i in L:
if i%2!=0:
D["ODD"].append(i)
else:
D["EVEN"].append(i)
print(D)
8) Statement 1 : StudentDict = dict( )
Statement 2 = for i in range( n ):
Statement 3: studentDict[rollno]=[name, physicsMarks, chemistryMarks, mathMarks]

You might also like