Python

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

LESSON 1

I. Fill in the blanks.


1. Python supports concatenating strings using the addition operation.
2. Python was created by Guido van Rossum.
3. Every Variable in Python is an Object.
4. Using two multiplication symbols makes a power relationship.
5. Any line starting with # in Python programming is a comment.

II. Choose the correct answer.


1. Python was named after a/an _____________.
a. Snake b. Actor c. Chocolate d. English TV show
2. Python has __________ built-in types of sequences.
a. Six b. Seven c. Five d. Eight
3. New file option is found under the ______________ menu.
a. Format b. Options c. File d. Windows
4. The ______________ function prints the output to the screen.
a. Output() b. Print() c. OnScreen() d. function()
5. Variable defined either with a single quote or a double quotes is ____________.
a. Numbers b. Floating point c. Strings d. Variable

III. State true or false.


1. Lists can be joined with the multiplication operator. False
2. Modulo operator returns the integer remainder of the division. True
3. Semicolons are necessary to end the statement. False
4. Python is a powerful low-level programming language. False
5. Python can be easily integrated with C, C++ and Java. True
IV. Answer in one word.
1. Which key on the keyboard is pressed to run a program in Python? F5
2. Name the creator of Python. Guido van Rossum
3. Which statement is completely ignored by compilers and interpreters? Comment
4. Name the operator used to form new list with a repeating sequence. Multiplication
operator

V. Answer the following.


1. What is the use of the comment statement in a program?
Comments are used in programming to describe the purpose of the code. It
also helps to understand the intent of the code.
2. Write a short note on Lists.
The list is a most versatile data type available in Python which can be written
as a list of comma separated values (items) between square brackets. The items
in a list need not be of the same type.
3. Mention the applications of Python.
Web development - Django, Bottle
Scientific and Mathematical computing - Orange, SymPy, NumPy
Desktop graphical user interfaces - Pygame, Panda3D
4. Write the steps to execute a program in Python.
To execute a program,
Click on the Run menu  choose Run Module option or
Press F5 key.
VI. Write the program for the following output.
1. a=10
b=5
c=a-b
print("Difference between the two numbers is")
print(c)

2. print([2]*10)

VII. Find the output for the following programs.


1. N1=3 Output: 27
N2=9
N3=N1*N2
print(N3)

2. h="How" Output: How are you


r="are"
u="you"
hru=h+" "+r+" "+u
print(hru)

LESSON 2

I. Fill in the blanks.


1. len( ) will display the length of the string value that is stored in the variable.
2. Run the program by pressing F5 from keyboard.
3. len ( ) will include punctuation and space.
4. index ( ) is used to find the location or position of a character in a string.
5. Strings are bits of text.
II. Choose the correct answer.
1. _____________ operator is used to concatenate strings.
a. - b. * c. + d. /
2. Strings are defined as anything between _________________.
a. quotes b. commas c. fullstop d. brackets
3. _____________ function will return the length of the string variable.

a. Text ( ) b. length ( ) c. String ( ) d. len ( )

4. Count ( ) is used to count the number of _____________ in a string.


a. length b. characters c. slice d. reverse

III. State true or false.


1. There is no string reverse function. True
2. count( ) will return the length of the string variable. False
3. index() can be used to slice a string. False
4. The / operator does concatenation in Python. False

IV. Answer in one word.


1. Where are the values stored in Python? Variable
2. Name the function used to count the number of characters in a string. Count
3. Which key is pressed to run a program? F5
4. Is there a function to reverse a string? No

V. Answer the following.


1. What is called concatenation?
Joining of two or more strings into a single one is called concatenation.
2. What are strings in programming?
Strings are bits of text. They can be defined as anything between quotes.
3. Write a short note on Index value.
index() function is used to find the location or position of a character in a
string variable.
4. Name the two functions used to convert the case of characters.
upper() and lower() are the functions used to convert the case of characters.

VI. Spot the error in the program and rewrite the program.
1. a1="Test Program"
print(len(a1))

2. A1="PYTHON"
print(A1[2:5])

LESSON 3

I. Fill in the blanks.


1. len( ) function is used to get the length of a list.
2. You can test if an item exists in a list or not, using the in keyword.
3. You can use index operator ([ ]) to access an item.
4. The pop( ) method removes and returns an element at the given index.
5. You can use clear( ) method to empty a list.
6. del is the keyword which is used to delete one or more items from a list.

II. State True or False.


1. Lists are enclosed in curly brackets. False
2. Python allows negative indexing for its sequence. True
3. You cannot reverse the order of items in the list. False
4. You can only use integer type for indexing in Python. True
5. Let us assume list1=[‘t’,’r’,’u’,’e’]
then print(‘f’ not in list1) returns True as output. True

III. Answer the following questions.


1. Define list.
Lists are collections of items where each item in the list has an assigned index
value.
2. How will you create a list?
A list is created by placing all the items inside square brackets [ ], separated by
commas.
3. Write the syntax for insert( ) method and explain it.
list.insert(x,y)
4. Give an example for reverse( ) method.
my_list=[3,8,1,6,0,8,4]
my_list.reverse()
print(my_list)

IV. Answer the following questions in detail.


1. How will you access elements from a list? Refer Pg.no.: 27
2. Explain the methods used to add items to the list. Refer Pg.no.: 32
3. How will you delete or remove elements from a list? Explain its methods.
Refer Pg.no.: 34-35
4. Name the list methods in Python. Explain any two of them. Refer Pg.no.: 36
V. Find the output for the following.
1. Let us assume my_list=[‘T’,’E’,’C’,’H’,’N’,’O’,’S’,’C’,’H’,’O’,’O’,’L’]
Output
a. print(‘S’ in my_list) - True
b. print(‘A’ in my_list) - False
c. print(my_list.count(‘O’)) - 3
d. print(‘e’ not in my_list) - True
e. my_list.reverse()
print(my_list) - ['L', 'O', 'O', 'H', 'C', 'S', 'O', 'N', 'H', 'C', 'E', 'T']
f. my_list.sort()
print(my_list) - ['C', 'C', 'E', 'H', 'H', 'L', 'N', 'O', 'O', 'O', 'S', 'T']

2. Let us assume my_list=[‘s’,’u’,’c’,’c’,’e,’s’]


Output
a. print(len(my_list)) - 6
b. print(my_list[5]) - s
c. my_list.append('s')
print(my_list) - ['s', 'u', 'c', 'c', 'e', 's', 's']
d. my_list.remove(‘u’)
print(my_list) - ['s', 'c', 'c', 'e', 's']
e. print(my_list[-4]) - c

3. Let us assume my_list=['Roger','Rudy','Kevin']


Output
a. print(my_list.index('Rudy')) - 1
b. del my_list[1] - ['Roger', 'Kevin']
print(my_list)
c. my_list.extend(['Dravid','Rafael']) - ['Roger', 'Rudy', 'Kevin', 'Dravid', 'Rafael']
print(my_list)
d. my_list.clear() - []
print(my_list)

VI. Crossword.
Across:
1. This list can have another list as an item. nested
4. It removes an item from the list. remove
7. It adds an element to the end of the list. append

Down:

1. This type holds numbers like integers and floats. numeric


2. It contain no elements. empty
3. Used to add several items to the list. extend
5. It returns the count of number of items passed as an argument. count
6. It removes all items from the list. clear

LESSON 4

I. Fill in the blanks.


1. Decision Making is required when we want to execute a code only if the condition
is satisfied.
2. Python interprets non-zero values as True.
3. In if statement, if the test expression is False, the statement(s) will not be executed.
4. One way to get data directly from the user is by using the input function.
5. elif statement allows to check for multiple test expressions.
II. Choose the correct answer.
1. None and 0 values are interpreted as __________
a. True b. False c. None
2. The __________ method reads a line input.
a. read() b. get() c. input()
3. ____________ is used to separate the blocks.
a. Indentation b. Enter key c.Next
4. The ___________ is short form for else if.
a. Elf b. Elis c. Elif
5. The syntax for input() is ______________.
a. input{prompt} b. input([prompt]) c. (input[])

III. State True or False.


1. Any number of statements can be nested inside one another. True
2. input() method converts the input into a string and returns it. True
3. If block can have more than one else block. False
4. Prompt is a string which is optional. True

IV. Answer the following.


1. What is a nested if statement? Refer Pg.no.: 46
2. Write a short note on the input function. Refer Pg.no.: 45
3. Write the syntax for if…else statement. Refer Pg.no.: 42
4. What is the use of decision making? Refer Pg.no.: 41

V. Draw flowchart for the following.


1. If…else statement Refer Pg.no.: 43
2. If…statement Refer Pg.no.: 42
3. If…elif…else statement Refer Pg.no.: 44

VI. Observe the program and answer the following questions.


1.
a. Positive or Zero
b. num
c. 3
d. if the variable ‘num’ is assigned to 0 or greater than 0.
2.
a. 12 is a great age to be
b. inst
c. input([prompt])
d. Enter your age:

LESSON 5

I. Fill in the blanks.


1. The range( ) function is used to indicate how many times the loop will be repeated.
2. The relational operators compare the values on either sides of them and decide the
relation among them.
3. In while..else loop, the else clause is executed when the condition becomes false.
4. The range( ) function is one of Python’s built-in functions.
5. In Python, for and while loop can have optional else statement.
6. range(10) will generate numbers from 0 to 9.

II. Write down the description for the following loops:


1. while loop Refer Pg.no.: 50 2. for loop Refer Pg.no.: 50
III. Answer the following questions:
1. Define loop.
A loop statement allows us to execute a statement or a group of statements
multiple times.
2. What is the syntax of the range function? Explain its arguments. Refer Pg.no.: 57
range(start, upto, step)
3. Define while loop. Refer Pg.no.: 50
4. Draw the flow diagram of for loop. Refer Pg.no.: 56

IV. Write down the syntax for the following:


1. while. Refer Pg.no.: 51
2. while…else Refer Pg.no.: 53
3. for Refer Pg.no.: 56

V. Answer the following questions in detail:


1. In how many ways the range function can be used? Explain them with examples.
Refer Pg.no.: 57
2. Explain for loop with else clause. Give example. Refer Pg.no.: 59

VI. Skill Test:


1. Write a program to find whether the given letter is a vowel or not using if..else
statement.
ch = input("Enter any letter: ")
if(ch=='a' or ch=='A' or ch=='e' or ch=='E' or ch=='i' or ch=='I'or ch=='o' or
ch=='O' or ch=='u' or ch=='U'):
print(ch, "is a vowel.\n")
else:
print(ch, "is not a vowel.\n")
2. Write a program to get two numbers and perform arithmetic operations.
print("Enter any two number: ")
num1 = input()
num2 = input()
ch = input("Enter the operator (+,-,*,/): ")
if ch == '+':
res = int(num1) + int(num2)
print(num1, "+", num2, "=", res)
elif ch == '-':
res = int(num1) - int(num2)
print(num1, "-", num2, "=", res)
elif ch == '*':
res = int(num1) * int(num2)
print(num1, "*", num2, "=", res)
elif ch == '/':
res = int(num1) / int(num2)
print(num1, "/", num2, "=", res)
else:
print("Strange input")

3. Write a Python program to print all the prime numbers in an interval.


lower=int(input("Enter the lower range:"))
upper=int(input("Enter the upper range:"))
print("Prime numbers between",lower,"and",upper,"are:")
for num in range(lower,upper + 1):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)
VII. Spot the errors in the given program and rewrite it to get the following output:
1. Program to find the factorial of the given number.
num = int(input("Enter a number: "))
factorial = 1
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)

2. Program to find the sum of natural numbers up to n where n is provided by user.


num = int(input ("Enter a number:"))
if num < 0:
print("Enter a positive number")
else:
sum = 0
while (num > 0):
sum += num
num -= 1
print("The sum is",sum)

LESSON 6
I. Fill in the blanks.
1. A group of data which can be processed in a single unit is termed as data structure.
2. Data are stored sequentially in a linear data structure.
3. Lists are enclosed in square brackets.
4. Arranging a list in either ascending or descending order is called as sorting a list.
5. A stack data structure follows the Last-in First-Out principle.
6. Operations of stack data structure are pop( ) and append( ).
II. Answer in one line.
1. Give some example for linear data structure.
Arrays, Lists, Stacks, Queues, Linked Lists
2. What are the two types of Data structure?
Linear and Non-Linear
3. Mention the techniques used for sorting.
Selection sort, Bubble sort, Insertion sort
4. What is push and pop?
Push and Pop are the operations used for adding and removing elements.
5. Explain the term ‘top of the stack’.
In stack, insertion and deletion of elements can be done only at one end, which is
called as the top of the stack.

III. Answer the following.


1. Define data structure. Refer Pg.no.: 63
2. Distinguish between the Linear and Non-linear data structure. Refer Pg.no.: 63
3. Write a note on selection sort. Refer Pg.no.: 63
4. Differentiate a stack and a queue.
A stack data structure follows the Last-In-First-Out principle. i.e the element
added to the last can be accessed first.
A queue data structure follows the First-In-First-Out principle.

IV. Answer the following briefly.


1. Explain queue with an example. Refer Pg.no.: 68-69
2. Write note on stack. Refer Pg.no.: 67
3. Explain the three sorting techniques with simple examples. Refer Pg.no.: 63-67
V. Relate the real time examples with the techniques learnt.
1. Make the students to stand in height order (from small to high). Sorting
2. Booking tickets in the Railway station counter. Queue
3. Picking up the balls from the basket. Selection sort
4. When we are playing cards each time we take new card and insert at its proper
position. Insertion sort

LESSON 7

I. Fill in the blanks.


1. You can use clear( ) function to delete all elements from the dictionary.
2. Python dictionary is a/an unordered collection of items.
3. To delete a single element from Python Dictionary, use del keyword.
4. To display each element of the dictionary on screen, for-loop can be used.
5. The dict( ) function is used to create a new dictionary with no items.
6. {} represents a/an empty string.
7. Python dictionary is basically a sequence of key-value pairs.

II. Answer the following questions.


1. Define Python dictionary. Refer Pg.no.: 71
2. How will you create a dictionary? Refer Pg.no.: 72
3. How will you delete a single element from the dictionary?
del keyword will delete a single element from the Python dictionary.
III. Answer the following questions in detail.
1. How will you add elements to the dictionary? Give example. Refer Pg.no.:73-74
2. How will you display the elements of the dictionary using for loop? Give example.
Refer Pg.no.: 73
3. How will you delete the elements from dictionary? Give example. Refer Pg.no.: 74-75

LESSON 8

I. Fill in the blanks.


1. Functions in Python are defined using the keyword def.
2. You can provide a default value to an argument by using the assignment operator.
3. A colon (:) is used to mark the end of function header.
4. Any input you give to a function is called as an argument.
5. Use Asterisk (*) before the parameter name to denote the arbitrary number of
arguments.

II. Identify the term.


1. It avoids repetition and makes code reusable. Function
2. This keyword marks the start of function header. def
3. It has no def keyword, but has a function name followed by parentheses. Function call

III. Choose the correct answer.


1. Which of the following statement is true?
a. Functions are used to create objects in Python.
b. Functions make your program run faster.
c. Functions break your program into smaller chunks.
d. All of the above.
2. What is the output of the following code?
def printLine(text):
print(text, 'is awesome.')
printLine('Python')

a. Python
b. Python is awesome.
c. text is awesome.
d. is awesome.
3. What is the output of the following code?
def greetPerson(*name):
print('Hello', name)

greetPerson('Avril', 'Roger')

a. Hello Avril
Hello Roger
b. Hello ('Avril', 'Roger')
c. Hello Roger
d. Syntax Error! greetPerson() can take only one argument.
4. Which keyword is used for function?
a. func
b. define
c. def
d. function
5. What is the output of the following code?
def printMax(a, b):
if a > b:
print(a, 'is maximum')
elif a == b:
print(a, 'is equal to', b)
else:
print(b, 'is maximum')
printMax(3, 4)

a. 3
b. 4
c. 4 is maximum
d. None of the mentioned

IV. Answer the following questions.


1. What is a function? Refer Pg.no.: 77
2. What are the uses of function? Refer Pg.no.: 77
3. What is an argument in function? Refer Pg.no.: 80
4. Give general syntax for function definition.
def function_name( ):
body of the function

V. Answer the following questions in detail.


1. How will you define a function? Give example. Refer Pg.no.: 77
2. How will you call a function? Give example. Refer Pg.no.: 77
3. Explain Python Arbitrary arguments with example. Refer Pg.no.: 82
LESSON 9

I. Fill in the blanks.


1. Polymorphism is the ability of an object to take on many forms.
2. A class is the best example for encapsulation.
3. The new class that is formed is called derived class.
4. A method is a procedure associated with a class in OOP.
5. A class is a group of objects that has common properties.
6. The existing class is called as base class.

II. Answer the following in one word.


1. Which concept shows essential features and hides non-essential features to the user?
Abstraction
2. What defines the behavior of the objects? Method
3. What is called as an instance of a class? Object
4. What is the process of binding the variables, codes, properties and methods into a
single unit? Encapsulation
5. What language does the computer understand? Binary language

III. True or False.


1. Class is a blueprint from which objects are created. True
2. The word polymorphism means inheriting a property from one another. False
3. In encapsulation, the irrelevant data is hidden from the user. True
4. Class is the result of the object. False
5. The derived class is also known as the Parent class or Super class. False
IV. Answer the following questions.
1. What are the three main characteristics of an object? State, Behaviour and Identity
2. Define Polymorphism.
Polymorphism is the ability of an object to take on many forms.
3. Write a few benefits of OOP. Refer Pg.no.: 91
4. What is a computer program?
A computer program is a set of instructions that the user or programmer writes to
tell the computer what to do and how to carry out a certain task.
5. Expand OOP. Object Oriented Programming

V. Answer the following questions in detail.


1. Define inheritance and mention its advantages. Refer Pg.no.: 92
2. Mention the features of OOP. Refer Pg.no.: 91

LESSON 10

I. Fill in the blanks.


1. Functions are also called as methods.
2. Objects are an encapsulation of variables and functions into a single entity.
3. The variables and functions can be accessed along with class_name and dot operator.
4. Constructor is always gets called when creating an object.
5. The self keyword can access the attributes and methods of the class in Python.

II. True or False.


1. Objects get their variables and functions from classes. True
2. The __init__( ) function is called as the constructor. True
3. Objects are essentially a template to create your classes. False
4. In Python, a class is created by the keyword class. True
5. A class function that begins with a single underscore (_). False

III. Choose the correct answer.


1. Which of the following is required to create a new instance of the class?
a. A function
b. A class
c. A constructor
d. All of the above
2. Which of the following keyword mark the beginning of the class definition?
a. def
b. return
c. class
d. cls
3. What is Instantiation in terms of OOP terminology?
a. Creating an instance of a class
b. Deleting an instance of a class
c. Copying an instance of a class
d. Modifying an instance of a class
4. What is the output of the following code?
class test:
def __init__(self,a="Hello World"):
self.a=a
def display(self):
print(self.a)
obj=test()
obj.display()
a. “Hello World”
b. self.a
c. Hello World
d. a
5. What is the output of the following code?
class Test:
a="Hello! How are you?"
def fun(self):
print("Hello World")
print(Test.a)
a. Hello World
b. Hello! How are you?
c. Test.a
d. Error

IV. Answer the following questions.


1. Which function gets called whenever a new object of that class is instantiated?
__init__( ) function
2. How to access the variables and functions that are inside the class?
The variables and functions can be accessed along with the class name and dot
operator.
3. What are called class attributes?
The variables owned by the class are sometimes called class attributes.
4. How will you create instances of a class?
To create an instance of a class, you call the class using class name and pass in
whatever arguments its __init__ method accepts.
V. Answer the following questions in detail.
1. How will you define a class in Python? Give syntax and example. Refer Pg.no.: 99
2. Explain Constructors in Python with an example. Refer Pg.no.: 101

LESSON 11

I. Fill in the blanks.


1. The process of inheriting a derived class from another derived class is known as
multi-level inheritance.
2. The main class from which it inherits the properties is called base class or parent
class.
3. Inheritance is the feature which facilitates re-usability of code.
4. The child class or derived class inherits the features from the parent class.

II. Answer the following questions.


1. Define inheritance.
It is a very powerful feature which facilitates users to create a new class with a
few or more modification to an existing class.
2. Write the syntax of inheritance. Refer Pg.no.: 106

III. Answer the following questions in detail.


1. Explain inheritance in Python with an example. Refer Pg.no.: 107
2. Explain Multi-Level inheritance in Python with an example. Refer Pg.no.: 110-111
LESSON 12

I. Fill in the blanks.


1. Python allows us to create and manage text and binary types of files.
2. The open( ) function takes two parameters namely, filename and mode.
3. read( ) function is used for reading the content of the file.
4. By default, the read( ) method returns the whole text.
5. To open a file, use the open( ) function.

II. Answer the following in one line.


1. How many methods/modes are there in opening a file? 4
2. Name the module needed to be imported to delete a file. os
3. Which function is used to delete a file? remove( )
4. Name the method used to close a file. close( )

III. Answer the following.


1. State the difference between using file.read(4), file.read( ) and file.readline( ) in a
table.
file.read(4) - returns the first 4 characters of the file
file.read( ) - returns the whole text
file.readline( ) - returns the first line of the file
2. Write a note on close( ) function.
close( ) function is used to close a file after appending the content to the file.
3. Justify the usage of ‘t’ in opening a file. (file.open(“sample.txt”,”rt”).
“t” for text
4. Write the general definition of a file.
It is a collection of data stored in one unit, identified by a filename.
5. Expand ‘a’ mode of creating a new file.
Append – opens a file for appending, creates the file if it does not exist

IV. Write the code for the following.


1. Code for creating a new file.
my_file=open("D:\myfile.txt","w")
my_file.write('How you are feeling today?')
my_file.close()
2. Write code to insert the content below to the file created above.
Content:
It’s a new day and a new dawn.
I’m feeling good.
my_file=open("D:\myfile.txt","a")
my_file.write('\n It’s a new day and a new dawn.')
my_file.write('\n I’m feeling good.')
my_file.close()

You might also like