NOTES ON PYTHON PROGRAMMING
NOTES ON PYTHON PROGRAMMING
UNIT I
PART-A
1. Define Algorithm
Algorithm: It is a sequence of instructions designed in such a way that if the
instructions are executed in the specified sequence, the desired results will be obtained.
The instructions in an algorithm should not be repeated infinitely. The algorithm should
be written in sequence.
PART B
1. Define python
Python is an object-oriented, high-level language, interpreted, dynamic and
multipurpose programming language.
• In immediate mode, you type Python expressions into the Python Interpreter
window, and the interpreter immediately shows the result.
• Alternatively, you can write a program in a file and use the interpreter to
execute the contents of the file. Such a file is called a script. Scripts have
the advantage that they can be saved to disk, printed, and so on.
a
b
c
d
9. What is tuple ? What is the difference between list and tuple?
• A tuple is another sequence data type that is similar to the list. A tuple
consists of a number of values separated by commas.
• The main differences between lists and tuples are: Lists are enclosed in
brackets ( [ ] ) and their elements and size can be changed, while tuples are
enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought
of as read-only lists. Eg:
• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operator
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operator
PART B
UNIT II
PART A
CONTROL FLOW AND FUNCTIONS
statements
elif
statement:
statements
else:
statements
5. Write the syntax and usage of for loop
For Loop is used to iterate a variable over a sequence(i.e., list or string) in
the order that they appear. Syntax:
while
<expression>:
Body
10. What is len function and explain how it is used on strings with an example.
The len function, when applied to a string, returns the number or character in a string.
Example:
>>>book=‘Problem Solving and Python Programming‘
>>>l
en(book)
38
>>>
12. What are the two operators that are used in string functions?
The in operator tests for membership.
>>>‘V‘ in ‗VRB‘
True
>>>‘S‘ in ‗VRB‘
>>>False
The not in operator returns the logical opposite results of in operator.
>>>‘x‘ not
in ‗VRB‘
True
15. How to split strings and what function is used to perform that operation?
The str.split() method is used to split strings up.
>>>book=‘Problem Solving and Python Programming‘
>>>print(book.split())
[‗Problem‘, ‗Solving‘, ‗and‘, ‗Python‘, ‗Programing‘]
PYTHON PROGRAMMING – Question Bank
PART A
print words*2
Assuming num=125,
determine the value of each of the following Python expressions.
(i) num/125
(ii)num%100
(iii)(num==2 1)&(2<3)
(iv)not((num<45.9)&(6*2<=13))
PYTHON PROGRAMMING – Question Bank
PART B
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
5. Explain what is range() function and how it is used in lists?
The range function returns an immutable sequence object of integers
between the given start integer to the stop intege
range(start,stop,[step])
>>>f
or I
in
range(1,10,2):
print(i,end=‖―) 1 35 7 9
6. How lists are updated in Python?
The append() method is used to add elements to a list.
Syntax:
list.append(obj)
List=[123,‘VR
B‘]
List.append(2017)
Print(―
Updat
ed
List:‖,
List)
Output: Updated List: [123,‘VRB‘,2017]
10. What is the output of print tuple[1:3] if tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )? In the
given command, tuple[1:3] is accessing the items in tuple using indexing.
It will print elements starting from 2nd
till 3rd. Output will be (786, 2.23).
11. What are the methods that are used in Python Tuple?
Methods that add items or remove items are not available with tuple. Only the
following two methods are available:
a) count(x)- returns the number of items that is equal to x
b) index(x)- returns index of first item that is equal to x
>>>a<
b True
13. What are the built-in functions that are used in Tuple?
• all()- returns true if all elements of the tuple are true or if tuple is empty
• any()- returns true if any element of tuple is true
• len()- returns the length in the tuple
• max()- returns the largest item in tuple
• min()- returns the smallest item in tuple
• sum()- returns the sum of all elements in tuple
14. What is the output of print tuple + tinytuple if tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
and tinytuple = (123, 'john')?
It will print concatenated tuples. Output will be ('abcd', 786, 2.23, 'john',
70.200000000000003, 123, 'john').
If someone buys all of the pears, we can remove the entry from the dictionary:
>>> del inventory[‘pears‘]
>>> print inventory
{‘oranges‘: 525, ‘apples‘: 430, ‘bananas‘: 312}
19. Explain values and items method used in dictionary with example.
The values method is similar; it returns a list of the values in the dictionary:
>>>
eng2sp.v
alues()
[‘uno‘,‘tres‘,‘dos‘]
The items method returns both, in the form of a list of tuples—one for each key-value pair:
>>> eng2sp.items()
[(‘one‘,‘uno‘), (‘three‘, ‘tres‘), (‘two‘, ‘dos‘)]
The syntax provides useful type information. The square brackets indicate that
this is a list. The parentheses indicate that the elements of the list are tuples.
20. What is the difference between modify and copy operations performed in
dictionary? If you want to modify a dictionary and keep a copy of the original, use
the copy method. For example, opposites is a dictionary that contains pairs
of opposites:
>>> opposites = {‘up‘: ‘down‘, ‘right‘: ‘wrong‘, ‘true‘: ‘false‘}
>>> alias = opposites
>>> copy = opposites.copy()
alias and opposites refer to the same object; copy refers to a fresh copy
of the same dictionary. If we modify alias, opposites is also changed:
>>> alias[‘right‘] = ‘left‘
>>> opposites[‘
right‘]
‘left‘
If we modify copy, opposites is unchanged:
>>> copy[‘right‘] = ‘privilege’
PART_B
PART C
6. Which method is used to read the contents of a file which is already created?
The read method reads data from the file. With no arguments, it reads
the entire contents of the file:
>>> text = f.read()
>>> print text
Now is the timeto close the file
7. What is a text file? Give an example for a text file.
A text file is a file that contains printable characters and whitespace,
organized into lines separated by newline characters.
To demonstrate, we‘ll create a text file with three lines of text separated by newlines:
>>> f = open("test.dat","w")
>>> f.write("line one\nline two\nline three\n")
>>> f.close()
13. Explain how can you access a module written in Python from C?
We can access a module written in Python from C by following
method,Module =
=PyImport_ImportModule(―<modulename>‖);
17. Which method is used to read the contents of a file which is already created?
The read method reads data from the file. With no arguments, it reads
the entire contents of the file:
>>> text = f.read()
>>> print text
Now is the timeto close the file
23. List some few common Exception types and explain when they occur.
• ArithmeticError- Base class for all errors that occur for numeric calculations.
• OverflowError- Raised when a calculation exceeds maximum limit for a
numeric type.
• ZeroDivisionError- Raised when division or modulo by zero takes
o place.
• ImportError- Raised when an import statement fails.
• IndexError- Raised when an index is not found in a sequence.
• RuntimeError- Raised when a generated error does not fall into any category.
x=int(input(―Please
enter a number:‖))
break
except ValueError:
print(―Oops! That was no valid number. Try again…‖)
5) Explain in detail about Python Files, its types, functions and operations
that can be performed on files with examples. (16 marks)