0% found this document useful (0 votes)
25 views20 pages

Python Programming Basics Guide

bullshi
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)
25 views20 pages

Python Programming Basics Guide

bullshi
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

PYTHON REVISION TOUR

 Python is a widely used high-level programming language for general-purpose programming, created by
Guido Van Rossum and first released in 1991. My first program in Python is:
 print(“Hello World”)
 Python shell can be used in two ways: interactive mode and script mode.
 Interactive mode does not save commands in the form of a program. It is used for testing code.
 Script mode is useful for creating programs and then trying the programs later and getting complete output.
 Python is an interpreted language.
 Python is a case-sensitive language.

TOKENS IN PYTHON (Lexical Unit)


Smallest individual unit in a program.

1. KEYWORDS
 Predefined words with special meaning to the language processor; are reserved for special purposes and
must not be used as normal identifier names.
 Example - True, for, if, else, elif, from, is, and, or, break, continue, def, import, in, while, False, try, finally,
except, global, etc.

2. IDENTIFIERS
 Python Identifier is a name used to identify a variable, function, class, module or other object. The rules for
creating Identifiers :
 Start with the alphabet or underscore. Followed by digits or more letters
 Python keyword cannot be used as an Identifier.
 Identifier should not contain special characters except underscore.
 Identifiers are unlimited in length.
 Some valid identifiers are: Myfile, MYFILE, Salary2021, _Chk ,First_Number
 Invalid Identifies are: [Link], break, 2021salary, if#, First Number

3. LITERALS
Data items that have a fixed value.
 String Literals: are sequence of characters surrounded by quotes (single, double or triple)
 S1=”Hello” S2=”Hello” S3=”””Hello”””
 Python allows nongraphic characters in string values. E.g. \r,\n,,\a,\b,\u,\v
 Numerical Literals: are numeric values in decimal/octal/hexadecimal form. D1=10 D2=0o56 (Octal)
D3=0x12 (Hex)
 Floating point literals: real numbers and may be written in fractional form (0.45) or exponent form
(0.17E2).
 Complex number literal: are of the form a+bJ, where a, b are int/floats and J(or i) represents −1 i.e.
imaginary number. Ex: C1=2+3j
 Boolean Literals: It can have value True or False. Ex: b=False
 Special Literal None: The None literal is used to indicate absence of value.
 Ex: c=None

4. OPERATORS
Tokens that trigger some computation/action when applied to variables and other objects in an expression.
These are
 Arithmetic : +, -, *, /, %, **, //
 Bitwise : &, ^, |
 Identity : is, is not
 Relational : >, >=, <, <=,!=, ==
 Logical : and, or, not
 Assignment : =
 Membership : in, not in
 Arithmetic assignment: /=, +=, -=, *=, %=, **=, //=
PRECEDENCE OF ARITHMETIC OPERATORS
PE(MD) (AS) = read PEMDAS
P=parenthesis () → E=exponential →M, D = multiplication and division → A, S=addition and subtraction
Ex: 12*(3%4)//2+6 = 24 (Try at your end)

5. PUNCTUATORS
Punctuators are symbols that are used to organize sentence structure. Common punctuators used in
Python are: ‘ “ # \ ( ) [ ] { } @ , : .

DATA TYPES
Means to identify type of data and set of valid operations for it. These are

1. NUMBERS
To store and process different types of numeric data: Integer, Boolean, Floating-point, Complex no.

2. STRING
Can hold any type of known characters i.e. letters, numbers, and special characters, of any known scripted
language. It is immutable datatype means the value can’t be changed at place. Example: “abcd”, “12345”,”This
is India”, “SCHOOL”.
-6 -5 -4 -3 -2 -1
S C H O O L
0 1 2 3 4 5

3. LISTS
Represents a group of comma-separated values of any datatype between square brackets. Examples:
L1=list()
L2=[1, 2, 3, 4, 5]
L3=[5, ‘Neha’, 25, 36, 45]
L4=[45, 67, [34, 78, 87], 98]
In list, the indexes are numbered from 0 to n-1, (n= total number of elements). List also supports forward and
backward traversal. List is mutable datatype (its value can be changed at place).

4. TUPLE
Group of comma-separated values of any data type within parenthesis. Tuple are immutable i.e. non-
changeable; one cannot make change to a tuple.
t1=tuple()
t2=(1, 2, 3, 4, 5)
t3=(34, 56, (52, 87, 34), 67, ‘a’)

5. DICTIONARY
The dictionary is an unordered set of comma separated key:value pairs, within { }, with the requirement that
within a dictionary, no two keys can be the same. Following are some examples of dictionary:
d1=dict()
d2={1:’one’, 2:’two’, 3:’three’}
d3={‘mon’:1, ‘tue’:2, ‘wed’:3}
d4={‘rno’:1, ‘name’:’lakshay’, ‘class’:11}
In dictionary, key is immutable whereas value is mutable.
STRING PROCESSING AND OTHER FUNCTIONS

STRING
 In Python, a string literal is a sequence of characters surrounded by quotes.
 Python supports single, double and triple quotes for a string
 A Character literal is a single character surrounded by single or double quotes.
 The value with triple-quote ’’’ ‘’’ is used to give multiline string literal.
Example:
strings = “This is Python”
char = “C”
multiline_str = ‘’’This is multiline string with
more than one line code.’’’
print(strings)
print(char)
print(multiline_str)

STRING REPLICATION
When a string is multiplied by a number, string is replicated that number of times.
Note: Other datatype – list and tuple also show the same behavior when multiplied by an integer number.
>>> STR=’Hi’
>>> print(STR*5)
>>>HiHiHiHiHi

>>> L=[1, 2]
>>> print(L*5)
>>> [1,2,1,2,1,2,1,2,1,2]

>>> t=(1, 2)
>>> print(t*5)
>>> (1,2,1,2,1,2,1,2,1,2)

STRING SLICE
String Slice refers to part of a string containing some contiguous characters from the string. The syntax is
str_variable[start:end:step].
start: from which index number to start
end: upto (end-1) index number characters will be extracted
step: is step value. (optional) By default it is 1
Example : Suppose S='KENDRIYA'
Backward Index no -8 -7 -6 -5 -4 -3 -2 -1
Character K E N D R I Y A
Forward Index no 0 1 2 3 4 5 6 7

Command Output Explanation


S KENDRIYA Will print entire string.
S[:] KENDRIYA Will print entire string.
S[::] KENDRIYA Will print entire string.
S[2] N Will print element at index no 2.
S[2:6] NDRI From index number 2 to (6-1) i.e. 5.
S[Link] EDI From index 1 to 5 every 2nd letter.
S[::2] KNRY From start to end … every 2nd letter.
S[::3] KDY From start to end … every 3rd letter.
S[::-1] AYIRDNEK Will print reverse of the string.
S[ : -1] KENDRIY Will print entire string except last letter
S[ -1] A Will print only last letter
S[-5::] DRIYA From index no -5 to end of the string.
S[-7:-4:] END From index no -7 to -5.
Stride when slicing string
 When the slicing operation, you can specify a third argument as the stride, which refers to the number
of characters to move forward after the first character is retrieved from the string. The default value of
stride is 1.
Example
>>> str1 = "Welcome to learn Python"
>>> print (str1[10:16])
learn
>>> print (str1[Link])
r
>>> print (str1[Link])
er
>>> print (str1[::3])
Wceoenyo

String Function Description


len(<string>) Retruns the length of its argument string
<string>.capitalize() Returns a copy of the string with its first character capitalized
<string>.count(sub[,start[,end]]) Returns the number of occurrences of the substring sub in the
string
<string>.find(sub[,start[,end]]) Returns the lowest index in the string where the substring sub
is found within the slice range
<string>.index(sub[,start[,end]]) Returns the lowest index where the specified substring is
found
<string>.isalnum() Returns True if the characters in the string are alphanumeric
and there is at least one character, False otherwise.
<string>.isalpha() Returns True if all characters in the string are alphanumeric
<string>.isdigit() Returns True if all the characters in the string are digits
<string>.islower() Returns True if all the characters in the string are lowercase
<string>.isupper() Returns True if all the characters in the string are uppercase
<string>.isspace() Returns True if there are only whitespace characters in the
string
<string>.lower() Returns a copy of the string converted to lowercase
<string>.upper() Returns a copy of the string converted to uppercase
<string>.lstrip() Returns a copy of the string with leading white-spaces
removed
<string>.rstrip() Returns a copy of the string with trailing white-spaces removed
<string>.strip() Returns a copy of the string with leading and trailing
whitespaces removed
<string>.startswith() Returns True if the string starts with the substring sub
<string>.endswith() Returns True if the string ends with the substring sub
<string>.title() Returns a title-cased version of the string where all words start
with uppercase characters and all remaining letters are
lowercase
<string>.istitle() Returns True if the string has the title case
<string>.replace(old,new) Returns a copy of the string will all occurrences of substring
old replaced by new string
<string>.join(<string iterable>) Joins a string or character after each member of the string
iterator
<string>.split(<string/char>) Splits a string based on the given string or characters and
returns a list containing split strings as members
<string>.partition(<sep/string>) Splits the string at the first occurrence of separator, and returns
a tuple containing three items as string till separation,
separator and the string after separator
LISTS
A List is a standard data type of python that can store a sequence of values belonging to any data type. List
elements are enclosed with square brackets. Lists are mutable i.e., you can change elements of a list in place.

CREATING LIST
1) Empty List
>>>L=[] OR >>> L=list()
2) From existing sequence
>>>st=’HELLO’
>>> L1=list(st) # from a string
>>> t=(1, 2, 3)
>>> L2=list(t) # from a tuple
3) from Keyboard entering element one by one
>>> L=[]
>>> for i in range(5):
n=int(input(‘Enter a number :’))
[Link](n)

TRAVERSING A LIST
>>> L=[1, 2, 3, 4, 5]
>>> for n in L:
print(n)

JOINING LISTS
>>> L1=[1, 2, 3]
>>> L2=[33, 44, 55]
>>> L1 + L2 # output: [1, 2, 3, 33, 44, 55]

SLICING THE LIST


>>> L=[10, 11, 12, 13, 14, 15, 16, 18]
>>> seq=L[2:6]
# it will take from index no 2 to (6-1) i.e. 5
>>> seq # output: [12, 13, 14, 15]
General syntax for slicing is L[start : end : step]

APPENDING ELEMENT
>>> L=[10, 11, 12]
>>>[Link](20) # Will append 20 at last
>>> L # output : [10, 11, 12, 20]
>>>[Link]([4,5])
# Appended data will be treated as a single element
>>> L # output: [10, 11, 12, 20, [4, 5]]

EXPANDING LIST
>>> L=[10, 11, 12]
>>>[Link]([44,55])
# Will extend given item as separate elements
>>> L # output: [10, 11, 12, 44, 55]
UPDATING LIST
>>> L=[10, 11, 12]
# Suppose we want to change 11 to 50
>>> L[1]=50
>>> L # output: [10, 50, 12]
DELETING ELEMENTS
del List[index]# Will delete the item at given index del List[start : end]# Will delete from index no start to (end-
1)
>>> L=[x for x in range(1,11)]
>>> L # list is [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> del L[2:5]
>>> L # now list is [1, 2, 6, 7, 8, 9, 10]

BUILT-IN FUNCTIONS OF LIST


Function with syntax Description
len(<list>) Returns the number of elements in the passed list
<list>(<elements>) Returns a list created from the passed arguments of sequence of
elements
<list>.index(<item>) Returns the index of first matched item from the list
<list>.append(<item>) Adds an item to the end of the list
<list>.extend(<list>) Adding multiple elements to a list
<list>.insert(<ind>,<item>) Inserts the given item in the given index
<list>.pop(<index>) Removes an element from the given position in the list
<list>.remove(<item>) Removes the first occurrence of given item
<list>.clear() Removes all the items from the list
<list>.count(<item>) Returns the count of the item in the list
<list>.reverse() Reverses the items of the list
<list>.sort() Sorts the items of the list, by default in ascending order
min(<list>) Returns minimum value from the list
max(<list>) Returns maximum value from the list
sum(<list>) Returns the sum of the elements of the list

TUPLES
The Tuples are depicted through parenthesis or Tuples are sequence of elements enclosed within parenthesis.
Tuples are immutable sequences i.e., you cannot change elements of a tuple in a place

T=()
T=(value,…)

Creating Single Element Tuple


t=(1) # (1) was treated as integer, not a tuple
t=(3,) # Now t stores a tuple, not integer

Creating Tuples from Existing Sequence


T= Tuple(<sequence>)
Where <sequence> can be strings, lists and tuples.
>>>T1= tuple(‘hello’)
>>>T1
(‘h’,’e’,’l’,’l’,o’)
>>> L=[23,25,30,40]
>>> t2=tuple(L)
>>> t2
(23,25,30,40)

Traversing a Tuple
T=(‘s’,’c’,’h’,’o’,’o’,’l’)
for a in T:
print(T)
The above loop will produce output as
s
c
h
o
o
l

Joining Tuples
The + operator, the concatenation operator, when used with two tuples, joins two tuples.
>>>T1=(10,20,30)
>>>T2 =(50,60,70)
>>>T1+T2
(10,20,30,50,60,70)

Slicing the Tuples


Tuple slices, like-slices or string slices are the sub part of the tuple extracted out.
seq = T[start:stop]
>>>T1=(10,20,30,40,50,60,70,80,90,100,110)
>>> seq=T1[4:-4]
(50, 60, 70)

DICTIONARY
Dictionaries are a collection of some unordered key:value pairs; are indexed by keys (keys must be of any non-
mutable type). Dictionaries are mutable, unordered collections with elements.

<dictionary-name> = {<key>:<value>,<key>:<value>…}

TRAVERSING A DICTIONARY
>>> d={1:’one’, 2:’two’, 3:’three’}
>>> for key in d:
print(key, “:”, d[key], sep=’\t’)
1 : one 2 : two 3 : three

ADDING ELEMENT TO DICTIONARY


>>>d[4]=’four’ # will add a new element
>>> print(d)
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}

DELETING ELEMENTS FROM DICTIONARY


>>> del d[3]
# will delete entire key:value whose key is 3
>>> print(d) # op: {1: 'one', 2: 'two', 4: 'four'}

OTHER FUNCTIONS
Here is a list of functions to recall them which work on dictionaries.
pop(key), len(), values(), items(), keys(), update()

MCQ
[Link] developed Python?
(A)Ritche (B) Guido Van Rossum (C)Bill Gates (D) Sunder Pitchai

[Link] Python prompt indicates that Interpreter is ready to accept instruction.


(A)>>> (B)<<< (C)# (D)<<
[Link] of the following shortcut is used to create new Python Program?
(A) Ctrl+C (B) Ctrl +F (C) Ctrl +B (D) Ctrl +N

[Link] of the following character is used to give comments in Python Program?


(A)# (B)& (C)@ (D)$

[Link] symbol is used to print more than one item on a single line.
(A)Semicolon(;) (B) Dollor($) (C)comma(,) (D) Colon(:)

[Link] of the following is not a token?


(A)Interpreter (B) Identifiers (C)Keyword (D) Operators

[Link] of the following is not a Keyword in Python?


(A)break (B) while (C)continue (D) operators

[Link] operator is also called as Comparative operator?


(A)Arithmetic (B)Relational (C)Logical (D) Assignment

[Link] of the following is not logical operator?


(A) AND (B) OR (C)Not (D)Assignment

10. Python language was released in the year


a) 1992 b) 1994 c) 2001 d) 1991

11. Escape sequences starts with a


a) / b) // c) \” d) \

[Link] Python, the script mode programs can be stored with the extension.
a) .pyt b) .py c) .pyh d) .pon

[Link] mode displays the python code result immediately?


a) Compiler b) Script c) Interactive d) Program

[Link] operator replaces multiline if-else in Python?


a)Logical b) Conditional c) Relational d) Assignment

15. Which of the following is a sequence of characters surrounded by quotes?


a) Complex b) String literal c) Boolean d) Octal

[Link] python, comments begin with


a) / b) # c) \ d) \\

[Link] python _________ is a simple assignment operator.


a) != b) = c) == d) >>>

18. Python uses the symbols and symbol combinations as _____ in expressions
a) literals b) keywords c) delimiters d) identifiers

19. All data values in Python are__________


a) class b) objects c) octal d) functions

20. Hexadecimal number contains _____


a) h b) o c) d d) x

[Link] of the following command is used to execute Python Script?


a) Run → Python Module b) File → Run Module
c) Run → Module Run d) Run → Run Module
22. In Python shell window opened by pressing
a) Alt + N b) Shift + N c) Ctrl + N d) Ctrl+Shift+N

23. elif can be considered to be abbreviation of


(A)nested if (B)if..else (C)else if (D)if..elif

24. What plays a vital role in Python programming?


(A)Statements (B) Control (C)Structure (D) Indentation

25. The condition in the if statement should be in the form of


(A) Arithmetic or Relational expression (B) Arithmetic or Logical expression
(C) Relational or Logical expression (D) Arithmetic

26. What is the output of the following snippet?


i=1
while True:
if i%3 ==0:
break
print(i,end='')
i +=1
(A)12 (B)123 (C)1234 (D)124

27. What is the output of the following snippet?


T=1
while T:
print(True)
break
(A)False (B) True (C)0 (D)no output

28. Which amongst is not a jump statement?


(A)for (B)goto (C)continue (D)break

29. A loop place within another loop is called as ____________ loop structure
a) entry check b) exit check c) conditional d) nested

30. Which statement is used to skip the remaining part of a loop and start with next iteration?
a) condition b) continue c) break d) pass

31 Pick odd one in connection with collection data type


(a) List (b)Tuple (c)Dictionary (d)Loop

32. Let l i s t 1= [2,4,6,8,10], t h e n p r i n t (List1[-2]) will result in


(a)10 (b)8 (c)4 (d)6

33. Which of the following function is used to count the number of elements in a list?
(a)count() (b)find () (c)len() (d)index()

[Link] List= [10,20,30,40,50] then List [2]=35 will result


(a)[35,10,20,30,40,50] (b)[10,20,30,40,50,35]
(c)[10,20,35,40,50] (d)[10,35,30,40,50]

[Link] List=[17,23,41,10] then [Link](32) will result


(a)[32,17,23,41,10] (b)[17,23,41,10,32]
(c)[10,17,23,32,41] (d)[41,32,23,17,10]

36. Which of the following Python function can be used to add more than one element within an existing
list?
(a)append() (b)append_more (c)extend() (d)more()

[Link] will be the result of the following Python code?


S = [ x**2 for x in range(5)]
print (S)
a) [0,1,2,4,5] b) [0,1,4,9,16] c) [0,1,4,9,16,25] d) [1,4,9,16,25]

[Link] is the use of type() function in Python?


a) To create a Tuple b) To know the type of an element in tuple
c) To know the data type of python object d) To create a list

39. Which of the following statement is not correct?


(a) A list is mutable b)A tuple is immutable
(c) The append() function is used to add an element.
(d)The extend() function is used in tuple to add elements in a list.

40. The keys in Python, dictionary is specified by


a) = b) ; c) + d) :
41. Which of the following is an ordered collection of values?
(a)Set (b)Tuples (c)List (d)Dictionary

42. Which of the following is used to delete known elements where the index value is known?
(a)del (b)delete (c)remove() (d)del()

43. Which function is used to convert the result of range() function into list?
(a)convert() (b)range() (c)list() (d)listrange()

44. Which of the following argument is optional in sort()?


(a)Reverse (b)Key (c)True/false (d)a and b

45. Which is a powerful feature in python.


(a)Tuple assignment (b)List assignment (c)Assignment statement (d)Set

46. While creating a tuple from a list, the element should been closed within
(a)[] (b)() (c){} (d)[()]

47. Write the output for the [Link]=(1,2,4,4,5,6) print(Tu[4:])


(a)4,5,6 (b)6 (c)5,6 (d)4,4,5,6

48. Which of the following is the output of the following python code?
str1="TamilNadu"
print(str1[::-1])
(a) Tamilnadu (b) Tmlau (c) udanlimaT (d) udaNlimaT

49. What will be the output of the following code?


str1 = "Chennai Schools"
str1[7] = "-"
(a) Chennai-Schools (b) Chenna-School (c) Type error (d) Chennai

50. Which of the following operator is used for concatenation?


(a) + (b) & (c) * (d) =

51. Defining strings within triple quotes allows creating:


(a) Single line Strings (b) Multiline Strings
(c) Double line Strings (d) Multiple Strings

52. Strings in python:


(a) Changeable (b) Mutable (c) Immutable (d) flexible
53. Which of the following is the slicing operator?
(a) { } (b) [ ] (c) <> (d) ( )

54. What is stride?


(a) index value of slide operation (b) first argument of slice operation
(c) second argument of slice operation (d) third argument of slice operation

55. Which of the following formatting character is used to print exponential notation in upper case?
(a) %e (b) %E (c) %g (d) %n

56. Which of the following is used as placeholders or replacement fields which get replaced along with format(
) function?
(a) { } (b) <> (c) ++ (d) ^^

57. The subscript of a string may be:


(a) Positive (b) Negative (c) Both (a) and (b) (d) Either (a) or (b)

58. Which of the following is used to handle array of characters in python?


a) Functions b) Composition c) Arguments d) String

59. String index values are also called as


a) class b) function c) subscript d) arguments

60. A substring can be taken from the original string by using


a) { } b) <> c) ( ) d) [ ]

62. Which function returns the number of sub strings occurs within the given range?
a) count() b) range() c) return() d) format()

ASSERTIONS AND REASONS


In the following questions, a statement of assertion (A) is followed by a statement of reason (R).
Mark the correct choice as:
(a) Both A and R are true and R is the correct explanation of A.
(b) Both A and R are true but R is not the correct explanation of A.
(c) A is true but R is false (or partly true).
(d) A is false (or partly true) but R is true.
(e) Both A and R are false or not fully true.

1. Assertion. Assigning a new value to an int variable creates a new variable internally.
Reason. The int type is immutable data type of Python.
2. Assertion. """"A Sample Python String"""" is a valid Python String.
Reason. Triple Quotation marks are not valid in Python.
3. Assertion. If and For are legal statements in Python.
Reason. Python is case sensitive and its basic selection and looping statements are in
lower case.
4. Assertion. if and for are legal statements in Python.
Reason. Python is case sensitive and its basic selection and looping statements are in
lower case.
5. Assertion. The break statement can be used with all selection and iteration statements.
Reason. Using break with an if statement is of no use unless the if statement is part of a looping
construct.
6. Assertion. The break statement can be used with all selection and iteration statements.
Reason. Using break with an if statement will give no error.
7. Assertion. Lists and Tuples are similar sequence types of Python, yet they are two different
datatypes.
Reason. List sequences are mutable and Tuple sequences are immutable.
8. Assertion. Modifying a string creates another string internally but modifying a list does not create
a new list.
Reason. Strings store characters while lists can store any type of data.
9. Assertion. Modifying a string creates another string internally but modifying a list does not create
a new list.
Reason. Strings are immutable types while lists are mutable types of Python.
10. Assertion. Dictionaries are mutable, hence its keys can be easily changed.
Reason. Mutability means a value can be changed in place without having to create new
storage for the changed value.
11. Assertion. Dictionaries are mutable but their keys are immutable.
Reason. The values of a dictionary can change but keys of dictionary cannot be changed
because through them data is hashed.
12. Assertion. In Insertion Sort, a part of the array is always sorted.
Reason. In insertion sort, each successive element is picked and inserted at an appropriate
position in the sorted part of the array.
13. Assertion: The documentation for a Python module should be written in triple-quoted strings.
Reason: The docstrings are triple-quoted strings in Python that are documentation when help
<module> command is issued.
14. Assertion: After importing a module through import statement, all its function definitions,
variables, constants etc. are made available in the program.
Reason: Imported module's definitions do not become part of the program's namespace if
imported through an import <module> statement.
15. Assertion: If an item is imported through from <module> import <item> statement then you do
not use the module name along with the imported item.
Reason: The from <module> import command modifies the namespace of the program and
adds the imported item to it.
16. Assertion: Python's built-in functions, which are part of the standard Python library, can directly
be used without specifying their module name.
Reason: Python's standard library's built-in functions are made available by default in the
namespace of a program.
17. Assertion: Python standard library consists of number of modules.
Reasoning: A function in a module is used to simplify the code and avoids repetition.
18. Assertion: Python offers two statements to import items into the current program : import and
from<module>import, which work identically.
Reason. Both import and from <module> import bring the imported items into the current
program.
Answers
1. a 2. c 3. d 4. a 5. a 6. b 7. a 8. c 9. a 10. d 11. a 12. a 13. A
14. b 15. a 16.a 17.b 18.e

Short Question and Answers


1. Find the invalid identifier(s) from the following:
a) MyName b) True c) 2ndName d) My_Name
Ans: b) True, as it is a keyword c) 2ndName, Because it is starting with a digit.

2. Given the lists L=[1, 3, 6, 82, 5, 7, 11, 92], write the output of print(L[2:5]).
Ans: [6,82,5], as it will start from index no 2 to (5-1) i.e. 4.

3. Identify the valid arithmetic operator in Python from the following:


a) ? b) < c) ** d) and
Ans: c) ** as it is used to find power

4. Suppose tuple T is T = (10, 12, 43, 39), Find incorrect?


a) print(T[1]) b) T[2] = -29 c) print(max(T)) d) print(len(T))
Ans : b) T[2]= -29 (as tuple is immutable and we can’t change its value)
5. Declare a dictionary Colour, whose keys are 1, 2, 3 and values are Red, Green and Blue respectively.
Ans : Colour={1:'Red', 2:'Green', 3:'Blue'}

6. A tuple is declared asT = (2, 5, 6, 9, 8) What will be the value of sum(T)?


Ans : It will give the sum of all elements of tuple i.e. 2+5+6+9+8 = 30 abs()
7. Name the built-in mathematical function / method that is used to return an absolute value of a number.
Ans : Abs()

8. Identify declaration of L = [‘Mon’,‘23’,‘Bye’, ’6.5’]


a) dictionary b) string c) tuple d) list
Ans: d) list, as a list is collection of heterogeneous data.

9. Find the output of the following code?


>>>name="ComputerSciencewithPython"
>>>print(name[3:10])
Ans : It will print string from index no 3 to (10-1) i.e. 9 means 7 characters. So
output will be puterSc
10. Write the full form of IDLE.
Ans : Integrated Development Learning Environment

11. Find the output:


>>>A = [17, 24, 15, 30]
>>>[Link](2, 33)
>>>print (A[-4])
Ans : [Link](2,33) will insert 33 at index no 2. Now the list is [17, 24, 33, 15, 30]. So print(A[-4)) will start
counting from last element starting from -1, -2…
Hence will give 24.

12. Name tython Library modules which need to be imported to invoke the following functions:
(a) ceil() (b) randrange()
Ans : (a) math (b) random

13. What will be the result of the following code?


>>>d1 = {“abc” : 5, “def” : 6, “ghi” : 7}
>>>print (d1[0])
(a) abc (b) 5 (c) {“abc”:5} (d) Error
Ans : (d) Error, because dictionary works on the principle of key:value. These is no key as 0, so it will
produce an error.

14. STR=”VIBGYOR”
colors=list(STR) >>>del colors[4]
>>>[Link]("B")
>>>[Link](3)
>>>print(colors)
Ans : It will create a list as colors=['V', 'I', 'B', 'G', 'Y', 'O', 'R']. del colors[4] will delete the element at index
no 4 i.e. so list will be ['V', 'I', 'B', 'G', 'O', 'R']. [Link]("B") will remove ‘B’. so list will be ['V', 'I', 'G',
'O', 'R']. [Link](3) will extract ‘O’. So finally colors will be ['V', 'I', 'G', 'R'].

15. Suppose list L is declared as


L = [5 * i for i in range (0,4)], list L is
a) [0, 1, 2, 3,] b) [0, 1, 2, 3, 4] c) [0, 5, 10, 15] d) [0, 5, 10, 15, 20]
Ans : It is List Comprehension. Expression L = [i for i in range (0,4)] will generate [0, 1, 2, 3]. Since here
we are writing 5*i, so correct answer will be c) [0, 5, 10, 15]
16. Find possible output(s) at the time of execution of the program from the following code? Also specify the
maximum values of variables Lower and Upper. import random as r AR=[20, 30, 40, 50, 60, 70];
Lower = [Link](1,3)
Upper =[Link](2,
for K in range(Lower, Upper +1):
print (AR[K],end=”#“)
(i) 10#40#70# (ii) 30#40#50# (iii) 50#60#70# (iv) 40#50#70#

17. Write a function LShift(Arr,n), which accepts a list Arr of numbers and n is a numeric value by which all
elements of the list are shifted to left.
Sample Input Data of the list
Arr= [ 10,20,30,40,12,11], n=2
Output:
Arr = [30,40,12,11,10,20]

18. How do you convert a string into an int in python?


If a string contains only numerical characters, we can convert it into an integer using the int() function,
however, we cannot convert alphabetic and alphanumeric strings to integer in Python.

19. How do you convert a number to a string?


To convert a number into a string, we can use the inbuilt function str(). For octal or Hexadecimal
representation, we can use the inbuilt function oct() or hex().

20. What is Indentation?


 Python uses whitespace such as spaces and tabs to define program blocks of codes for selection, loop,
functions and class.
 The indentation is not fixed, but all statements within block must by indented with same amount spaces

21. What are the assignment operators that can be used in Python?
 In Python, = is a simple assignment operator to assign values to variable.
 There are various compound operators in Python like +=, -=, *=, /=, **= and //= are also available.
 Let us consider a=5 i.e. the value 5 from right side is assigned to the variable a to the left side
 Assume a+=5 i.e. the value 5 is added to the operand a and assign back the result to the left operand
a itself (a=a+5)

[Link] a short note on comment statement.


 In Python, comments begin with hash symbol(#).
 The lines that begin with # are considered as comments and ignored by the Python interpreter.
 Comments may be single line or multiline.
 The multiline comments should be enclosed within a set of ‘’’ ‘’’(triple quotes)

23. Write a program to check if a number is Positive, Negative or zero.


num = int(input("Enter the number "))
if num > 0:
print(" The given number is Positive")
elif num ==0:
print("The given number is Zero")
else:
print("The given number is Negative")

24. Write a program to display


A
A B
A BC
ABC D
A B C DE
Program:
for i in range (65, 70):
for j in range (65, i+1):
print(chr(j), end=' ')
print("")

25. Write a program to display all 3 digit even numbers.


for i in range(100,1000,2):
print(i,end=’\t’)

26. Write a python program to display following pattern


*****
****
***
**
*
for i in range(5,0,-1):
for j in range(1,i+1,1):
print("*",end=" ")
print("\n")

[Link] a program to check if the year is leap year or not


def leap(year):
if((year%4==0 and year%100!=0) or (year%400==0)):
print(year, " is a Leap year")
else:
print(year, " is not a Leap year")

y=int(input("Enter a year : "))


leap(y)

28. Write a program to display all 3 digit odd numbers.


for i in range(101,1000,2):
print (i,end='\t')
[Link] a program to display multiplication table for a given number.
num=int(input("Display of Multiplication Table for : "))
for i in range(1,11):
print(num," X ", i, " = ", num*i)
Output:
Display of Multiplication Table for : 7
7 X 1 = 7
7 X 2 = 14
7 X 3 = 21
7 X 4 = 28
7 X 5 = 35
7 X 6 = 42
7 X 7 = 49
7 X 8 = 56
7 X 9 = 63
7 X 10 = 70
30. What is the use of format( )? Give an example.
 The format() function used with strings is very versatile and powerful function used for formatting strings.
 The curly braces {} are used as placeholders or replacement fields which get replaced along with
format() function.
Example:
num1=int (input("Number 1: "))
num2=int (input("Number 2: "))
print ("The sum of {} and {} is {}".format(num1, num2,(num1+num2)))
output :
Number 1: 34
Number 2: 54
The sum of 34 and 54 is 88

31. How index value allocated to each character of a string in Python?


 Once you define a string, python allocate an index value for its each character. These index values are
otherwise called as subscript which are used to access and manipulate the strings. The subscript can
be positive or negative integer numbers.
 The positive subscript 0 is assigned to the first character and n-1 to the last character, where n is the
number of characters in the string. The negative index assigned from the last character to the first
character in reverse order begins with -1.
 Example

32. Write the output


tup = (10)
print(type (tup))
tup1 = (10,)
print(type(tup1))
Output: <class‘int’>
<class‘tuple’>
33 Give an example of joining two tuples.
Tup1=(2,4,6,8,10)
Tup2=(1,3,5,7,9)
Tup3=Tup1+Tup2
print(Tup3)
Output :
(2,4,6,8,10,1,3,5,7,9)
34. What is nested tuple? Explain with an example.
 In Python, a tuple can be defined inside another tuple; called Nestedtuple.
 In a nested tuple, each tuple is considered as anelement.
 The for loop will be useful to access all the elements in a nestedtuple.
Example:
Toppers =(("Vinodini", "XII-F", 98.7),("Soundarya", "XII- H",97.5),("Tharani","XII-F",95.3),
("Saisri","XII-G",93.8))
for i in Toppers:
print(i)
Output:
('Vinodini', 'XII-F', 98.7)
('Soundarya', 'XII-H', 97.5)
('Tharani', 'XII-F',95.3)
('Saisri', 'XII-G', 93.8)
35. How is a List different from Tuple object in Python?
List Tuple
Mutable(can be changed) Immutable(Cannot be changed)
Elements are enclosed with square Elements are enclosed with parantheses
brackets []
Elements can be added, removed and Elements cannot be modified after
changed after creation creation
Takes more memory usage Takes less memory usage
Slower due to mutability Faster because it’s immutable
36. Write a detail note on for loop
 The for loop is the most comfortable loop.
 It is also an entry check loop.
 The condition is checked in the beginning and the body of the loop is executed if it is only True otherwise
the loop is not executed.
Syntax:
for counter_variable in sequence:
statements-block 1
[else: # optional block
statements-block 2]
 Usually in Python, for loop uses the range() function in the sequence to specify the initial, final and
increment values.
 The range() generates a list of values starting from start tillstop-1.
The syntax of range():
range (start,stop,[step])
start – refers to the initial value
stop – refers to the final value
step – refers to increment value, this is optional part.
Example program:
for i in range(2,10,2):
print (i,end=' ')
Output:
2468

37. Write a detail note on if..else..elif statement with suitable example.


 When we need to construct a chain of if statement(s) then ‘elif’ clause can be used instead of ‘else’.
Syntax:
if <condition-1>:
statements-block 1
elif<condition-2>:
statements-block 2
else:
statements-block n
 In the syntax of if..elif..else mentioned above, condition-1is tested if it is true then statements- block1 is
executed, otherwise the control checks condition-2, if it is true statements block2 is executed and even if
it fails statements-block n mentioned in else part is executed.
 ‘elif’ clause combines if..else-if..else statements to one if..elif…else. ‘elif’ can be considered to be
abbreviation of ‘else if’. In an ‘if’ statement there is no limit of ‘elif’ clause that can be used, but an ‘else’
clause if used should be placed at the end

Example:
m1=int (input(“Enter mark in first subject : ”))
m2=int (input(“Enter mark in second subject : ”))
avg= (m1+m2)/2
if avg>=80:
print (“Grade : A”)
elif avg>=70 and avg<80:
print (“Grade : B”)
elifavg>=60 and avg<70:
print (“Grade : C”)
elifavg>=50 and avg<60:
print (“Grade : D”)
else:
print (“Grade : E”)
Output:
Enter mark in first subject : 34
Enter mark in second subject : 78
Grade : D
38. Explain while loop with example.
While loop belongs to entry check loop type, that is it not executed even once if the condition is tested False
in the beginning.
SYNTAX
While <condition>:
statements block 1
[else:
statements block2]
In while loop, the condition is any valid Boolean expression returning True or False
The else part of while is optional part of while. The statement block1 is kept executed till the condition is True
If the else part is written, it is executed when the condition is tested false
EXAMPLE
i=1 #initializing part of control variable
while (i<=5): # test condition
print (i,end='\t')
i=i+1 # updation of the control variable
Output:
1 2 3 4 5

39. Write a shot note about sort( ).


 The sort( )is used to sorts the elements in a list.
 The sorting process affects the original list.
 The general format: [Link](reverse=True|False, key=myFunc)
 Both, reverse and key arguments are optional
 If reverse is set to True, the list will be sorted in descending order
 Ascending is default.
Example: MyList=['B','G','Z','A','V']
[Link]()
print(MyList)
Output:
['A', 'B', 'G', 'V', 'Z']

40. Explain the difference between del and clear() in dictionary with an example
 In python dictionary, del keyword is used to delete a particular element.
 The clear() function is used to delete all the elements in a dictionary
 To remove the dictionary, we can use del keyword with dictionary name.
Example:
Dict = {‘Roll’: 12101, ‘SName’: ‘Raman’,’Tamil’:98, ‘Eng’:86}
Del Dict[‘Tamil’]
[Link]()
del Dict
Worksheet – 1
1. Identify the output of the following code snippet:
x="AnnualMeetattheCampus"
x=[Link]('a')
y=x[0]+"."+x[1]+"."+x[2]+x[3]
print(y)

2. What is the output of the expression?


S= "SUPER NOVA @ 2025"
A=[Link] (" ")
print (A)

3. What will be the output of the following code snippet?


message= "Cbse Examination 2025"
print(message[-3::-3])

4. What will be the output of the following code?


tup1 = (1,2,[1,2],3)
tup1[2][1]=3.14
print(tup1)

5. What does the [Link](x) method do?


(A) Extend method helps you to insert the list of element from the starting of the list
(B) Extend method helps you to insert the list of element at the end of the list
(C) Extend methods helps you to insert the list of element anywhere we want
(D) Extend method helps you to insert the element from the starting of the list

6. Suppose a tuple T is declared as T = (10, 12, 43, 39), which of the following is incorrect?
(A) print(T[1]) (B) T[2] = -29 (C) print(max(T)) (D) print(len(T))

7. Identify the output of the following code snippet:


x = ['xy', 'yz']
for i in x:
[Link]()
print(x)

8. What happens when '2' = 2 is executed?


9. For a list L=[9,5,6,7,8], L[0:10] gives
10. What will be the output of this statement?
str1 = “javat”
str1[-1:]

11. State True or False:


Syntax errors in Python occur when the parser detects an incorrect statement that prevents your
code from being parsed and, therefore, run.
Worksheet – 1 Answers
1. [Link]

2. ('SUPER', ' ', 'NOVA @ 2025')

3. 0ntixeC

4. (1, 2, [1, 3.14], 3)

5. (B) Extend method helps you to insert the list of element at the end of the list

6. (B) T[2] =-29 Tuples in Python are immutable, meaning their elements cannot be changed after the tuple is
created.

7. ['xy', 'yz']

8. SyntaxError: cannot assign integer to literal

9. [9, 5, 6, 7, 8] Since slicing in Python is safe, it does not throw an error if stop exceeds the list length.
Instead, it returns as many elements as possible.

10. 't'

11. True

You might also like