0% found this document useful (0 votes)
50 views12 pages

Python Variable and Data Type Exercises

The document contains a homework assignment on Python concepts for a Class 12 computer science course. It includes 25 multiple choice questions covering topics like variables, data types, operators, strings, lists, dictionaries, functions and more. It also provides 3 additional questions asking students to identify errors, differentiate between concepts, and explain output of code snippets.

Uploaded by

Prettysnow661
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)
50 views12 pages

Python Variable and Data Type Exercises

The document contains a homework assignment on Python concepts for a Class 12 computer science course. It includes 25 multiple choice questions covering topics like variables, data types, operators, strings, lists, dictionaries, functions and more. It also provides 3 additional questions asking students to identify errors, differentiate between concepts, and explain output of code snippets.

Uploaded by

Prettysnow661
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

SRI AMBAL THULASI PUBLIC SENIOR SECONDARY SCHOOL-CBSE,

ANNUR-641 653
HOMEWORK-1
(TOPICS: Python Revision Tour 1 and 2)
Subject: Computer Science (083) Class: XII Date:15.05.23
Answer the following:
1. Which of the following is an invalid variable?
(a) my_day_2 (b) 2nd_day (c)Day_two (d) _2
2. Which of the following is not a keyword?
(a) eval (b) assert (c) nonlocal (d) pass
3. Which of the following cannot be a variable?
(a) __init__ (b) in (c) it (d) on
4. Which of these is not a core data type?
(a) Lists (b) Dictionary (c) Tuples (d) Class
y
5. How would you write x in Python as an expression?
(a) x^y (b) x**y (c) x^^y (d) none of these
6. What will be the value of the expression? 14 +13 % 15
(a) 14 (b) 27 (c) 12 (d) 0
7. Evaluate the expression given below if A = 16 and B = 15. A%B//A
(a) 0.0 (b) 0 (c) 1.0 (d) 1
8. What is the value of x? x = int(13.254/2)
(a) 7 (b) 4 (c) 6 (d) 13
9. The expression 8/4/2 will evaluate equivalent to which of the following expressions:
(a) 8/(4/2) (b) (8/4)/2
10. Which among the following list of operators has the highest precedence?
+ ,-,**,%, /,<< ,>> , |
(a) <<, >> (b) ** (c) | (d) %
11. Which of the following expressions results in an error?
(a) float('12') (b) int('12') (c) float('12.5') (d) int('12.5')
12. Which value type does input() return?
(a) Boolean (b) String (c) Int (d) Float
13. Which two operators can be used on numeric values in Python?
(a) @ (b) % (c) + (d) #
14. Which of the following is valid arithmetic operator in Python:
(a) // (b) ? (c) < (d) and
15. The numbered position of a letter in a string is called _____.
(a) position (b) integer position (c) index (d) location
16. The operator _____ tells if an element is present in a sequence or not.
(a) exists (b) in (c) into (d) inside
17. The keys of a dictionary must be of _____ types.
(a) Integer (b) mutable (c) immutable (d) any of these
18. Following set of commands is executed in shell, what will be the output?
>>>str = "hello"
>>>str[ : 2]
>>>
(a) he (b) lo (c) olleh (d) hello
19. What data type is the object below?
L = [1, 23, 'hello', 1]
(a) list (b) dictionary (c) array (d) tuple
20. What data type is the object below?
L = 1, 23, 'hello', 1
(a) list (b) dictionary (c) array (d) tuple
21. To store values in terms of key and value, what core data type does Python provide?
(a) list (b) tuple (c) class (d) dictionary
22. What is the value of the following expression? 3 + 3.00, 3**3.0
(a) (6.0, 27.0) (b) (6.0, 9.00) (c) (6, 27) (d) [6.0, 27.0] (e) [6, 27]
23. List AL is defined as follows: AL = [1, 2, 3, 4, 5] Which of the following
statements removes the middle element 3 from it so that the list AL equal [1, 2, 4, 5]?
(a) del AL[2] (b) AL[2 : 3] = [] (c) AL[2:2] = [] (d) AL[2] = [] (e) [Link](3)
24. Which two lines of code are valid strings in Python?
(a) This is a string (b) 'This is a string' (c) (This is a string) (d) "This is a
string"
25. You have the following code segment:
String1 = "my"
String2 = "work"
print(String1 + String2)
What is the output of this code?
(a) my work (b) work (c) mywork

SRI AMBAL THULASI PUBLIC SENIOR SECONDARY SCHOOL-CBSE,


ANNUR-641 653
HOMEWORK-2
(TOPICS: Python Revision Tour 1 and 2)
Subject: Computer Science (083) Class: XII Date:16.05.23
Answer the following:
1. Which line of code produces an error?
(a) "one" + 'two' (b) 1+ 2 (c) "one"+ "2" (d) '1' + 2
2. What is the output of this code?
>>> int("3" + " 4")
(a) "7" (b) "34" (c) 34 (d) 24
3. Which line of code will cause an error?
1. num = [5, 4, 3, [2], 1]
2. print(num [0])
3. print(num[3][0])
4. print (num[5])
(a) Line 3 (b) Line 2 (c) Line 4 (d) Line 1
4. What will be the output of the following code-print("100+200")?
(a) 300 (b) 100200 (c) 100+200 (d) 200
5. Which amongst the following is a mutable data type in Python?
(a) int (b) string (c) tuple (d) list
6. pow() function belongs to which module?
(a) math (b) string (c) random (d) maths
7. Which of the following statements converts a tuple into a list?
(a) len(string) (b) list(string) (c) tup(list) (d) dict(string)
8. The statement: bval = str1 > str2 shall return..... As the output if two strings str1
and str2 contains "Delhi" and "New Delhi".
(a) True (b) Delhi (c) New Delhi (d) False
9. What will be the output generated by the following snippet?
a = [5, 10, 15, 20, 25]
k=1
i = a[1] + 1
j = a[2] +1
m = a[k+1]
print (i, j, m)

(a) 11 15 16 (b) 11 16 15 (c) 11 15 15 (d) 16 11 15


10. Which of the following Python functions is used to iterate over a sequence of
number by specifying a numeric end value within its parameters?
(a) range() (b) len() (c) substring() (d) random()
11. What is the output of the following?
d = (0: 'a', 1: 'b', 2: 'c'}
for i in d:
print(i)
12. What is the output of the following?
x = 123
for i in x:
print(i)
13. Which arithmetic operators cannot be used with strings?
(a) + (b) * (c) - (d) all of the above
14. What will be the output when the following code is executed?
>>> str1="helloworld"
>>> stri[:-1]
15. What is the output of the following statement?
print ("xyyzxyzxzxyy".count ('yy', 1))
(a) 2 (b) 0 (c) 1 (d) Error
16. Suppose list1 [0.5 * x for x in range(0, 4)], list1 is:
(a) [0, 1, 2, 3] (b) [0, 1, 2, 3, 4] (c) [0.0, 0.5, 1.0, 1.5] (d) [0.0, 0.5, 1.0, 1.5, 20]
17. Which is the correct form of declaration of dictionary?
(a) Day={1:'monday',2:'tuesday',3:'wednesday'}
(b) Day=(1;'monday',2;'tuesday',3;'wednesday')
(c) Day=[1:'monday',2:'tuesday',3:'wednesday']
(d) Day={1 monday',2
18. Why is Python interpreted? (1)
19. How are keywords different from identifiers? (2)
20. Differentiate between mutable and immutable objects in Python language with
example. (3)

SRI AMBAL THULASI PUBLIC SENIOR SECONDARY SCHOOL-CBSE,


ANNUR-641 653
HOMEWORK-3
(TOPICS: Python Revision Tour 1 and 2)
Subject: Computer Science (083) Class: XII Date:17.05.23
Answer the following:
1. Write the most appropriate list method to perform the following tasks. (5)
(a) Delete a given element from the list.
(b) Delete 3rd element from the list.
(c)Add an element in the end of the list.
(d) Add an element in the beginning of the list.
(e) Add elements of a list in the end of a list.
2. How are tuples different from lists when both are sequences? (2)
(OR)
3. How are string-literals represented and implement in Python? (2)
4. Find errors, underline them and rewrite the same after correcting the following
code:- (3)

d1 = dict[]
i=1
n = input ("Enter number of entries : ")
while i <= n :
a = input ("Enter name:")
b = input ("Enter age:")
d1 (a) = b
i=i+1
L= [Link] []
for i in L :
print (i, '\t', 'd1[ i ]')
5. What is None literal in Python? (1)

6. Can non graphic characters be used and processed in Python? How? Give examples to
support your answer. (2) (OR)
7. What is an expression and a statement? (2)
8. What is the output produced by the following code snippets: (5)
i) x=45
while x<50:
print(x)
ii) x=”apple,pear,peach”
y=[Link](“,”)
for z in y:
print(z)
iii) x=’apple,pear,peach,grapefruit’
y=[Link](“,”)
for z in y:
if z<‘m’:
print([Link](z))
else:
print([Link](z))
9. What’s a[1:1] if a is a string of at least two characters? And What if string is shorter?
(1)
10. What are the two ways to remove something from a list? How are they different? (2)
(OR)
11. How is del D and del D[<key>] different from one another if D is a dictionary?(2)
SRI AMBAL THULASI PUBLIC SENIOR SECONDARY SCHOOL-CBSE,
ANNUR-641 653
HOMEWORK-4
(TOPIC: Working with functions)
Subject: Computer Science (083) Class: XII Date:18.05.23

1. Rewrite the correct code after removing the errors: -


def SI(p,t=2,r):
return (p*r*t)/100

[Link] the following function headers. Identify the correct statement: -


a) def correct(a=1,b=2,c): b) def correct(a=1,b,c=3):
c) def correct(a=1,b=2,c=3): d) def correct(a=1,b,c):

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


a=1
def f():
a=10
print(a)

4. Find the output of the following code:


def CALLME(n1=1,n2=2):
n1=n1*n2
n2+=2
print(n1,n2)
CALLME()
CALLME(2,1)
CALLME(3)

5. Predict the output of the following code fragment?


def check(n1=1, n2=2):
n1=n1+n2
n2+=1
print(n1,n2)
check()
check(2,1)
check(3)

6. Find the output of the give program :


def Change(P ,Q=30):
P=P+Q
Q=P-Q
print( P,"#",Q)
return (P)
R=150
S=100
R=Change(R,S)
print(R,"#",S)
S=Change(S)
7. Find the output of the give program :
x = "abcdef"
i = "a"
while i in x:
print(i, end = " ")

8. Find the output of the following:


def power (b , p):
r = b ** P
return r
def calcSquare(a):
a = power (a, 2)
return a
n=5
result = calcSquare(n)
print (result)

9. Find the output of the following:


count =1
def dothis():
global count
for I in (1,2,3):
count+=1
dothis()
print (count)

10. Find the output of the following:


a=10
def call():
global a
a=15
b=20
print(a)
call()

SRI AMBAL THULASI PUBLIC SENIOR SECONDARY SCHOOL-CBSE,


ANNUR-641 653
HOMEWORK-5
(TOPIC: File handling)
Subject: Computer Science (083) Class: XII Date:19.05.23

1. Observe the code and answer the following :


f1=open("mydata","a")
______#blank1
[Link]()

(i)what type of file is mydata


(ii) Fill in the blank1 with statement to write "abc" in the file "mydata"

2. In which of the following file modes the existing data of the file will not be lost?
i) rb ii) w iii) a+b iv) wb+ v) r+ vi) ab vii) w+b viii)wb ix) w+

3. What would be the data types of variables Data in following statements?


i) Data=[Link]( ) ii) Data=[Link](10) iii) Data=[Link]()
iv)Data=[Link]()

4. Suppose a file name [Link] store alphabets in it then what is the output of the
following code:
f1=open("[Link]")
size=len([Link]())
print([Link](5))

5. Write a user defined function in python that displays the number of lines starting with
'H'in the file [Link].

6. Write a function countmy() in python to read the text file "[Link]" and count the
number of times "my" occurs in the file.

For example if the file [Link] contains-


"This is my website. I have diaplayed my preference in the CHOICE section ".

The countmy() function should display the output as:"my occurs 2 times".

7. Write a program that copies a text file "[Link]" onto "[Link]" barring the lines
starting with @ sign.

SRI AMBAL THULASI PUBLIC SENIOR SECONDARY SCHOOL-CBSE,


ANNUR-641 653
HOMEWORK-6
(TOPICS: Stack & File handling)
Subject: Computer Science (083) Class: XII Date: 22.05.23

1. Write PushOn(Book) and Pop(Book) methods/functions in Python to add a new Book and
delete a Book from a list of Book titles, considering them to act as push and pop operations
of the Stack data structure.

2. Write a function AddCustomer(Customer) in Python to add a new Customer information


NAME into the List of CStack and display the information.

3. Write a function DeleteCustomer() to delete a Customer information from a list of


CStack. The function delete the name of customer from the stack.

4. Write a program to Count the number of characters from a file. (Don’t count white
spaces).
5. Write a program to Count number of lines in a text file.

6. Write a program to Count number of vowels in a text file.

SRI AMBAL THULASI PUBLIC SENIOR SECONDARY SCHOOL-CBSE,


ANNUR-641 653
HOMEWORK-7
(TOPIC: File handling)
Subject: Computer Science (083) Class: XII Date: 23.05.23
1. Differentiate between a text file and a binary file.

2. Write code to print just the last line of a text file “[Link]”.

3. Write a function DisplayHeShe() in python that counts the number of „He‟ or She‟
words present in a text file „[Link]‟

4. Write a method/function SHOW_TODO() in python to read contents from a text file


[Link] and display those lines which have occurrence of the word “TO” or “DO”.
For example : If the content of the file is: “THIS IS IMPORTANT TO NOTE THAT
SUCCESS IS THE RESULT OF HARD WORK. WE ALL ARE EXPECTED TO DO HARD
WORK. AFTER ALL EXPERIENCE COMES FROM HARDWORK.”
The method/function should display:
THIS IS IMPORTANT TO NOTE THAT SUCCESS IS THE RESULT OF HARD WORK.
WE ALL ARE EXPECTED TO DO HARD WORK.

5. A binary file “[Link]” has structure as [ Code, Description, Price ].


(i). Write a user defined function MakeFile( ) to input multiple items from the user and
add to [Link]
(ii). Write a function SearchRec(Code) in Python which will accept the code as parameter
and search and display the details of the corresponding code on screen from [Link]

6. Write a python program to append a new records in a binary file –“[Link]”. The
record can have Rollno, Name and Marks.

7. Write a python program to search and display the record of the student from a binary
file “[Link]” containing students records (Rollno, Name and Marks). Roll number of
the student to be searched will be entered by the user.

SRI AMBAL THULASI PUBLIC SENIOR SECONDARY SCHOOL-CBSE,


ANNUR-641 653
HOMEWORK-8
(TOPIC: Interface Python with MySQL)
Subject: Computer Science (083) Class: XII Date: 24.05.23

Write a python interface program for performing the following:


1. CREATE DATABASE
2. SHOW DATABASE
3. CREATE TABLE
4. SHOW TABLES
5. DESCRIBE TABLE
6. SELECT QUERY using where clause
7. DYNAMIC INSERTION

SRI AMBAL THULASI PUBLIC SENIOR SECONDARY SCHOOL-CBSE,


ANNUR-641 653
HOMEWORK-9
(TOPIC:MySQL)
Subject: Computer Science (083) Class: XII Date: 25.05.23

1.

2.
3.

SRI AMBAL THULASI PUBLIC SENIOR SECONDARY SCHOOL-CBSE,


ANNUR-641 653
HOMEWORK-10
Subject: Computer Science (083) Class: XII Date: 26.05.23

1. Name the Python Library modules which need to be imported to invoke the following
functions : (i) load () (ii) pow () (iii) Uniform () (iv) fabs () (v) sqrt() (vi)dump() (vii)ceil()
(viii)randrange()

2. Find the invalid identifier from the following


a) def b)For c)_bonus d)First_Name

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


a) ? b) < c) ** d) and

4. Which of the following are Keywords in Python ?


(i) break (ii) Check (iii) For (iv) while

5. Given the lists L=[23,21,45,76,44,89,76] , write the output of print(L[2:5])


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

6. Evaluate the following expressions:


a) 12*(3%4)//2+6
b) not 12 > 6 and 7 < 17 or not 12 < 4
c) 2 ** 3 ** 2
d) 7 // 5 + 8 * 2 / 4 – 3

7. If given A=2,B=1,C=3,What will be the output of following expressions:


(i) print((A>B) and (B>C) or(C>A)) (ii) print(A**B**C)

8. Explain with a code about Positional arguments, Keyword arguments and Default
arguments.

9. What possible outputs(s) are expected to be displayed on screen at the time of


execution of the program from the following code. Select which option/s is/are correct.
import random
print([Link](15,25) , end=' ')
print((100) + [Link](15,25) , end = ' ' )
print((100) -[Link](15,25) , end = ' ' )
print((100) *[Link](15,25) )
(i) 15 122 84 2500 (ii) 21 120 76 1500
(iii) 105 107 105 1800 (iv) 110 105 105 1900

10. What possible outputs(s) are expected to be displayed on screen at the time of
execution of the program from the following code? Also specify the minimum and maximum
values that can be assigned to the variable End.
import random
Colours = ["VIOLET","INDIGO","BLUE","GREEN", "YELLOW","ORANGE","RED"]
End = randrange(2)+3
Begin = randrange(End)+1
for i in range(Begin,End):
print(Colours[i],end="&")
(i) INDIGO&BLUE&GREEN& (ii) VIOLET&INDIGO&BLUE& (ii)
BLUE&GREEN&YELLOW& (iv) GREEN&YELLOW&ORANGE&

11. In SQL, what is the error in following query :


SELECT NAME, SAL, DESIGNATION WHERE DISCOUNT=NULL;

12. A non-key attribute, whose values are derived from primary key of some other table.
i. Alternate Key ii. Foreign Key iii. Primary Key iv. Candidate Key

13. Differentiate between DDL and DML with one Example each.

14. Differentiate between fetchone() and fetchmany() methods with suitable examples for
each.

15. What is the difference between CHAR & VARCHAR data types in SQL? Give an
example for each.
16. Differentiate between an Attribute and a Tuple in a Relational Database with suitable
example.

Common questions

Powered by AI

Python typically raises a `TypeError` when operations mix incompatible data types, such as trying to concatenate a string and an integer. For example, attempting `'1' + 2` triggers a `TypeError` because Python cannot implicitly convert an integer to a string or vice versa in this context . Proper handling would involve converting one of the data types, such as using `str(2)` to match the string type .

Tuples can be used as keys in Python dictionaries whereas lists cannot, due to tuples being immutable. This immutability ensures that the hash of a tuple remains consistent during its lifetime, making it a reliable key for dictionaries. Using tuples as keys allows for storing complex data types composed of multiple values that won't change, preserving the integrity of the key-value relationship in the dictionary . Attempting to use lists as keys results in a `TypeError` .

String-literals in Python are used to represent text-based data. They can be created using single quotes (' '), double quotes (" "), or triple quotes for multi-line strings (''' ''' or """ """). They are implemented as sequences of Unicode characters, allowing for the representation of textual information in a versatile manner . For example, `'hello'`, `"world"`, or `'''multi line'''` are all string literals.

Python function arguments can be specified as positional, keyword, or default. Positional arguments are those passed to functions based on the order of parameters in the function definition, for example, `func(1, 2)`. Keyword arguments are explicitly named in function calls, such as `func(a=1, b=2)`, allowing arguments to be passed in any order. Default arguments are predefined in the function signature and used when no corresponding positional argument is provided: `def func(a, b=2)` allows `func(1)` to use the default value `2` for `b` .

In SQL, Data Definition Language (DDL) and Data Manipulation Language (DML) serve different purposes. DDL is used for defining and modifying database schema objects, such as `CREATE TABLE table_name(column1 TYPE, column2 TYPE);`, which creates a new table. DML, on the other hand, is used for data manipulation within the schema, involving operations like inserting or updating data, exemplified by `INSERT INTO table_name (column1, column2) VALUES (value1, value2);`. DDL operations affect the structure, while DML operations affect the data itself .

Tuples in Python differ from lists primarily in their mutability; tuples are immutable while lists are mutable. This means once a tuple is created, its elements cannot be changed, added, or removed, whereas a list can be modified. One might choose a tuple over a list to ensure data integrity, as tuples prevent accidental modifications. Additionally, since tuples are immutable, they can be used as dictionary keys, unlike lists .

The `range()` function in Python generates a sequence of numbers, commonly used in loops, with a specified start, stop, and step value. In contrast, `randrange()` from the `random` module returns a randomly selected element from the range of numbers defined by the start, stop, and step arguments. `randrange()` is preferred when there's a need to select a random number within a specific range rather than iterating through it sequentially, such as in games or simulations requiring random data generation .

An expression in Python is a piece of code that evaluates to a value, such as `2 + 3` or `x * y`, whereas a statement is a unit of code that performs an action, such as `print(x)` or `if x > 0:`. Expressions can be part of statements, for example, in the expression `x + 2` in the statement `y = x + 2`, where the expression calculates a value and the statement assigns it to a variable .

In Python, mutable objects are those that allow modifications to their values, whereas immutable objects do not permit changes once they are created. An example of a mutable object is a list, which can have its elements changed: `l = [1, 2, 3]; l[0] = 4` results in `l` being `[4, 2, 3]`. Conversely, a tuple is an example of an immutable object; trying to alter an element like `t = (1, 2, 3); t[0] = 4` would result in an error .

In Python, elements from a list can be removed using methods like `remove()` and `pop()`. The `remove()` method deletes the first occurrence of a specified value: `list.remove(value)`. In contrast, `pop()` removes the element at a specific position or the last element if no index is specified: `list.pop(index)`. The primary difference is that `remove()` operates based on value, while `pop()` operates based on index position .

You might also like