Ccc Lab Manual
Ccc Lab Manual
OBJECTIVE:
SOURCECODE:
a=5
print(a, "is of type", type(a))
a = 2.0
print(a, "is of type", type(a))
a = 1+2j
print(a, "is complex number?", isinstance(1+2j,complex))
INPUT ANDOUTPUT:
17
5 is of type <class 'int'>
2.0 is of type <class 'float'>
(1+2j) is complex number? True
VIVA Questions
2) What is PEP 8?
PEP 8 is a coding convention, a set of recommendation, about how to write your Python code more readable.
3) What is pickling and unpickling?
Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by
using dump function, this process is called pickling. While the process of retrieving original Python objects
from the stored string representation is called unpickling.
4) How Python is interpreted?
Python language is an interpreted language. Python program runs directly from the source code. It converts the
source code that is written by the programmer into an intermediate language, which is again translated into
machine language that has to be executed.
5) How memory is managed in Python?
Python memory is managed by Python private heap space. All Python objects and data structures are
located in a private heap. The programmer does not have an access to this private heap and interpreter
takes care of this Python private heap.
The allocation of Python heap space for Python objects is done by Python memory manager. The core
API gives access to some tools for the programmer to code.
Python also have an inbuilt garbage collector, which recycle all the unused memory and frees the
memory and makes it available to the heap space.
6) What are the tools that help to find bugs or perform static analysis?
PyChecker is a static analysis tool that detects the bugs in Python source code and warns about the style and
complexity of the bug. Pylint is another tool that verifies whether the module meets the coding standard.
7) What are Python decorators?
A Python decorator is a specific change that we make in Python syntax to alter functions easily.
8) What is the difference between list and tuple?
The difference between list and tuple is that list is mutable while tuple is not. Tuple can be hashed for e.g as a
key for dictionaries.
9) How are arguments passed by value or by reference?
Everything in Python is an object and all variables hold references to the objects. The references values are
according to the functions; as a result you cannot change the value of the references. However, you can change
the objects if it is mutable.
10) What is Dict and List comprehensions are?
They are syntax constructions to ease the creation of a Dictionary or List based on existing iterable.
11) What are the built-in type does python provides?
There are mutable and Immutable types of Pythons built in types Mutable built-in types
List
Sets
Dictionaries
Immutable built-in types
Strings
Tuples
18
Numbers
12) What is namespace in Python?
In Python, every name introduced has a place where it lives and can be hooked for. This is known as
namespace. It is like a box where a variable name is mapped to the object placed. Whenever the variable is
searched out, this box will be searched, to get corresponding object.
13) What is lambda in Python?
It is a single expression anonymous function often used as inline function.
14) Why lambda forms in python does not have statements?
A lambda form in python does not have statements as it is used to make new function object and then return
them at runtime.
15) What is pass in Python?
Pass means, no-operation Python statement, or in other words it is a place holder in compound statement,
where there should be a blank left and nothing has to be written there.
16) In Python what are iterators?
In Python, iterators are used to iterate a group of elements, containers like list.
17) What is unittest in Python?
A unit testing framework in Python is known as unittest. It supports sharing of setups, automation testing,
shutdown code for tests, aggregation of tests into collections etc.
18) In Python what is slicing?
A mechanism to select a range of items from sequence types like list, tuple, strings etc. is known as slicing.
19) What are generators in Python?
The way of implementing iterators are known as generators. It is a normal function except that it yields
expression in the function.
20) What is docstring in Python?
A Python documentation string is known as docstring, it is a way of documenting Python functions, modules
and classes.
21) How can you copy an object in Python?
To copy an object in Python, you can try copy.copy () or copy.deepcopy() for the general case. You cannot
copy all objects but most of them.
22) What is negative index in Python?
Python sequences can be index in positive and negative numbers. For positive index, 0 is the first index, 1 is
the second index and so forth. For negative index, (-1) is the last index and (-2) is the second last index and so
forth.
23) How you can convert a number to a string?
In order to convert a number into a string, use the inbuilt function str(). If you want a octal or hexadecimal
representation, use the inbuilt function oct() or hex().
24) What is the difference between Xrange and range?
Xrange returns the xrange object while range returns the list, and uses the same memory and no matter what
the range size is.
25) What is module and package in Python?
In Python, module is the way to structure program. Each Python program file is a module, which imports other
modules like objects and attributes.
The folder of Python program is a package of modules. A package can have modules or subfolders.
26) Mention what are the rules for local and global variables in Python?
Local variables: If a variable is assigned a new value anywhere within the function's body, it's assumed to be
local.
Global variables: Those variables that are only referenced inside a function are implicitly global.
27) How can you share global variables across modules?
To share global variables across modules within a single program, create a special module. Import the config
module in all modules of your application. The module will be available as a global variable across modules.
28) Explain how can you make a Python Script executable on Unix?
To make a Python Script executable on Unix, you need to do two things,
Script file's mode must be executable and
the first line must begin with # ( #!/usr/local/bin/python)
29) Explain how to delete a file in Python?
19
By using a command os.remove (filename) or os.unlink(filename)
30) Explain how can you generate random numbers in Python?
To generate random numbers in Python, you need to import command as
import random
random.random()
This returns a random floating point number in the range [0,1)
EXPERIMENT - 2
OBJECTIVE:
SOURCECODE:
x = 15
y=4
# Output: x + y = 19
print('x + y =',x+y)
# Output: x - y = 11
print('x - y =',x-y)
# Output: x * y = 60
print('x * y =',x*y)
# Output: x / y = 3.75
print('x / y =',x/y)
# Output: x // y = 3
print('x // y =',x//y)
# Output: x ** y = 50625
print('x ** y =',x**y)
INPUT ANDOUTPUT:
x + y = 19
x - y = 11
x * y = 60
20
x / y = 3.75
x // y = 3
x ** y = 50625
VIVA Questions
1. Which of these in not a core data type?
a) Lists
b) Dictionary
c) Tuples
d)Class
Answer: d
Explanation: Class is a user defined data type.
2. Given a function that does not return any value, What value is thrown by default when executed in shell.
a) int
b) bool
c) void
d)None
Answer: d
Explanation: Python shell throws a NoneType object back.
3. Following set of commands are executed in shell, what will be the output?
1. >>>str="hello"
2. >>>str[:2]
3. >>>
a) he
b) lo
c) olleh
d)hello
Answer: a
Explanation: We are printing only the 1st two bytes of string and hence the answer is “he”.
4. Which of the following will run without errors ?
a) round(45.8)
b) round(6352.898,2,5)
c) round()
d) round(7463.123,2,1)
Answer: a
Explanation: Execute help(round) in the shell to get details of the parameters that are passed into the round function.
5. What is the return type of function id?
a) int
b) float
c) bool
d)dict
Answer: a
Explanation: Execute help(id) to find out details in python shell.id returns a integer value that is unique.
6. In python we do not specify types,it is directly interpreted by the compiler, so consider the following operation to be
performed.
1. >>>x =13?2
21
objective is to make sure x has a integer value, select all that apply (python 3.xx)
a) x = 13 // 2
b) x = int(13 / 2)
c) x = 13 % 2
d) All of the mentioned
Answer: d
Explanation: // is integer operation in python 3.0 and int(..) is a type cast operator.
7. What error occurs when you execute?
apple = mango
a) SyntaxError
b) NameError
c) ValueError
d)TypeError
Answer: b
Explanation: Mango is not defined hence name error.
8. Carefully observe the code and give the answer.
1. def example(a):
2. a = a +'2'
3. a = a*2
4. return a
5. >>>example("hello")
a) indentation Error
b) cannot perform mathematical operation on strings
c) hello2
d)hello2hello2
Answer: a
Explanation: Python codes have to be indented properly.
9. What data type is the object below ?
L = [1, 23, ‘hello’, 1].
a) list
b) dictionary
c) array
d)tuple
Answer: a
Explanation: List data type can store any values within it.
10. In order to store values in terms of key and value we use what core data type.
a) list
b) tuple
c) class
d)dictionary
Answer: d
Explanation: Dictionary stores values in terms of keys and values.
11. Which of the following results in a SyntaxError ?
a) ‘”Once upon a time…”, she said.’
b) “He said, ‘Yes!'”
c) ‘3\’
d) ”’That’s okay”’
Answer: c
Explanation: Carefully look at the colons.
advertisement
12. The following is displayed by a print function call:
1. tom
22
2. dick
3. harry
Select all of the function calls that result in this output
a) print(”’tom
\ndick
\nharry”’)
b) print(”’tomdickharry”’)
c) print(‘tom\ndick\nharry’)
d)print(‘tom
dick
harry’)
Answer: c
Explanation: The \n adds a new line.
13. What is the average value of the code that is executed below ?
1. >>>grade1 =80
2. >>>grade2 =90
3. >>>average =(grade1 + grade2)/2
a) 85.0
b) 85.1
c) 95.0
d) 95.1
Answer: a
Explanation: Cause a decimal value of 0 to appear as output.
14. Select all options that print
hello-how-are-you
a) print(‘hello’, ‘how’, ‘are’, ‘you’)
b) print(‘hello’, ‘how’, ‘are’, ‘you’ + ‘-‘ * 4)
c) print(‘hello-‘ + ‘how-are-you’)
d)print(‘hello’ + ‘-‘ + ‘how’ + ‘-‘ + ‘are’ + ‘you’)
Answer: c
Explanation: Execute in the shell.
15. What is the return value of trunc() ?
a) int
b) bool
c) float
d)None
Answer: a
Explanation: Execute help(math.trunc) to get details.
23
Answer: c
18. What is the type of inf?
a) Boolean
b) Integer
c) Float
d)Complex
Answer: c
Explanation: Infinity is a special case of floating point numbers. It can be obtained by float(‘inf’).
19. What does ~4 evaluate to?
a) -5
b) -4
c) -3
d) +3
Answer: a
Explanation: ~x is equivalent to -(x+1).
20. What does ~~~~~~5 evaluate to?
a) +5
b) -11
c) +11
d) -5
Answer: a
Explanation: ~x is equivalent to -(x+1).
21. Which of the following is incorrect?
a) x = 0b101
b) x = 0x4f5
c) x = 19023
d) x = 03964
Answer: d
Explanation: Numbers starting with a 0 are octal numbers but 9 isn’t allowed in octal numbers.
22. What is the result of cmp(3, 1)?
a) 1
b) 0
c) True
d)False
Answer: a
Explanation: cmp(x, y) returns 1 if x > y, 0 if x == y and -1 if x < y.
23. Which of the following is incorrect?
a) float(‘inf’)
b) float(‘nan’)
c) float(’56’+’78’)
d) float(’12+34′)
Answer: d
Explanation: ‘+’ cannot be converted to a float.
24. What is the result of round(0.5) – round(-0.5)?
a) 1.0
b) 2.0
c) 0.0
d) None of the mentioned
Answer: b
Explanation: Python rounds off numbers away from 0 when the number to be rounded off is exactly halfway through.
round(0.5) is 1 and round(-0.5) is -1.
24
25. What does 3 ^ 4 evaluate to?
a) 81
b) 12
c) 0.75
d) 7
Answer: d
Explanation: ^ is the Binary XOR operator.
26)Explain how can you access a module written in Python from C?
You can access a module written in Python from C by following method,
Module = =PyImport_ImportModule("<modulename>");
27) Mention the use of // operator in Python?
It is a Floor Divisionoperator , which is used for dividing two operands with the result as quotient showing only digits
before the decimal point. For instance, 10//5 = 2 and 10.0//5.0 = 2.0.
28) Mention five benefits of using Python?
Python comprises of a huge standard library for most Internet platforms like Email, HTML, etc.
Python does not require explicit memory management as the interpreter itself allocates the memory to new
variables and free them automatically
Provide easy readability due to use of square brackets
Easy-to-learn for beginners
Having the built-in data types saves programming time and effort from declaring variables
29) Mention the use of the split functionin Python?
The use of the split function in Python is that it breaks a string into shorter strings using the defined separator. It gives a
list of all words present in the string.
30) Explain what is Flask & its benefits?
Flask is a web micro framework for Python based on "Werkzeug, Jinja 2 and good intentions" BSD licensed. Werkzeug
and jingja are two of its dependencies.
Flask is part of the micro-framework. Which means it will have little to no dependencies on external libraries. It makes
the framework light while there is little dependency to update and less security bugs.
25
EXPERIMENT -3
OBJECTIVE:
Write a program to create, concatenate and print a string and accessing sub-string from a given
string.
SOURCECODE:
# all of the following are equivalent
my_string = 'Hello'
print(my_string)
my_string = "Hello"
print(my_string)
my_string = '''Hello'''
print(my_string)
# triple quotes string can extend multiple lines
my_string = """Hello, welcome to
the world of Python"""
print(my_string)
c=" mlritm"
print(my_string+c)
# substring function
print(my_string[5:11])
INPUT ANDOUTPUT:
Hello
Hello
Hello
Hello, welcome to
the world of Python
Hello, welcome to
the world of Python mlritm
, welc
VIVA Questions
Answer: d
Explanation: All the statements will execute successfully but at the cost of reduced readability.
3. Which of the following is an invalid variable?
a) my_string_1
b) 1st_string
c) foo
d) _
Answer: b
Explanation: Variable names should not start with a number.
5. Why are local variable names beginning with an underscore discouraged?
a) they are used to indicate a private variables of a class
b) they confuse the interpreter
c) they are used to indicate global variables
d) they slow down execution
Answer: a
Explanation: As Python has no concept of private variables, leading underscores are used to indicate variables
that must not be accessed from outside the class.
6. Which of the following is not a keyword?
a) eval
b) assert
c) nonlocal
d) pass
Answer: a
Explanation: eval can be used as a variable.
7. All keywords in Python are in
a) lower case
b) UPPER CASE
c) Capitalized
d)None of the mentioned
Answer: d
Explanation: True, False and None are capitalized while the others are in lower case.
8. Which of the following is true for variable names in Python?
a) unlimited length
b) all private members must have leading and trailing underscores
c) underscore and ampersand are the only two special characters allowed
d)none of the mentioned
Answer: a
Explanation: Variable names can be of any length.
9. Which of the following is an invalid statement?
a) abc = 1,000,000
b) a b c = 1000 2000 3000
27
c) a,b,c = 1000, 2000, 3000
d) a_b_c = 1,000,000
Answer: b
Explanation: Spaces are not allowed in variable names.
9. Which of the following cannot be a variable?
a) init
b) in
c) it
d) on
Answer: b
Explanation: in is a keyword.
10. Is Python case sensitive when dealing with identifiers?
a) yes
b) no
c) machine dependent
d)none of the mentioned
Answer: a
Explanation: Case is always significant.
11. The value of the expressions 4/(3*(2-1)) and 4/3*(2-1) is the same. State whether true or false.
a) True
b) False
Answer: a
Explanation: Although the presence of parenthesis does affect the order of precedence, in the case shown above,
it is not making a difference. The result of both of these expressions is 1.333333333. Hence the statement is true.
12. The
4 + 3value
% 5 of the expression:
Explanation: The order of precedence is: %, +. Hence the expression above, on simplification results in 4 + 3 =
7. Hence the result is 7.
13. Evaluate the expression given below if A= 16 and B = 15.
A % B // A
Answer: b
Explanation: The above expression is evaluated as: 16%15//16, which is equal to 1//16, which results in 0.
14. Which of the following operators has its associativity from right to left?
a) +
b) //
c) %
d) **
Answer: d
Explanation: All of the operators shown above have associativity from left to right, except exponentiation
operator (**) which has its associativity from right to left.
16. What is the value of x if:
x = int(43.55+2/2)
Explanation: The expression shown above is an example of explicit conversion. It is evaluated as int(43.55+1) =
int(44.55) = 44. Hence the result of this expression is 44.
16. What is the value of the following expression?
2+4.00, 2**4.0
Explanation: The result of the expression shown above is (6.0, 16.0). This is because the result is automatically
rounded off to one decimal place.
17. Which of the following is the truncation division operator?
a) /
b) %
28
c) //
d)|
Answer: c
Explanation: // is the operator for truncation division. It it called so because it returns only the integer part of the
quotient, truncating the decimal part. For example: 20//3 = 6.
18. What are the values of the following expressions:
2**(3**2)
(2**3)**2
2**3**2
Answer: d
Explanation: Expression 1 is evaluated as: 2**9, which is equal to 512.Expression 2 is evaluated as 8**2, which
is equal to 64. The last expression is evaluated as 2**(3**2). This is because the associativity of ** operator is
from right to left. Hence the result of the third expression is 512.
advertisement
19. What is the value of the following expression:
8/4/2, 8/(4/2)
Answer: a
Explanation: The above expressions are evaluated as: 2/2, 8/2, which is equal to (1.0, 4.0).
20. What is the value of the following expression:
float(22//3+3/3)
Answer: b
Explanation: The expression shown above is evaluated as: float( 7+1) = float(8) = 8.0. Hence the result of this
expression is 8.0.
21. What is the result of the snippet of code shown below if x=1?
x<<2
Explanation: The binary form of 1 is 0001. The expression x<<2 implies we are performing bitwise left shift on
x. This shift yields the value: 0100, which is the binary form of the number 4.
22. The output of the expression is:
bin(29)
‘0b10111’
b) ‘0b11101’
c) ‘0b11111’
d) ‘0b11011’
Answer: b
Explanation: The binary form of the number 29 is 11101. Hence the output of this expression is ‘0b11101’.
23. What is the value of x if:
x>>2=2
Explanation: When the value of x is equal to 8 (1000), then x>>2 (bitwise right shift) yields the value 0010,
which is equal to 2. Hence the value of x is 8.
24. What is the result of the expression:
int(1011)?
Explanation: The result of the expression shown will be 1011. This is because we have not specified the base in
this expression. Hence it automatical
25. To find the decimal value of 1111, that is 15, we can use the function:
Explanation: The expression int(‘1111’,2) gives the result 15. The expression int(‘1111’, 10) will give the result
1111.
26. What is the result of the expression if x=15 and y=12:
x&y
Explanation: The symbol ‘&’ represents bitwise AND. This gives 1 if both the bits are equal to 1, else it gives 0.
The binary form of 15 is 1111 and that of 12 is 1100. Hence on performing the bitwise AND operation, we get
1100, which is equal to 12.
27. Which of the following expressions results in an error?
a) int(1011)
29
b) int(‘1011’,23)
c) int(1011,2)
d) int(‘1011’)
Answer: c
Explanation: The expression int(1011,2) results in an error. Had we written this expression as int(‘1011’,2), then
there would not be an error.
advertisement
28. Which of the following represents the bitwise XOR operator?
a) &
b) ^
c) |
d) !
Answer: b
Explanation: The ^ operator represent bitwise XOR operation. &: bitwise AND, | : bitwise OR and ! represents
bitwise NOT.
30. What is the value of this expression?
bin(0x8)
Explanation: The prefix 0x specifies that the value is hexadecimal in nature. When we convert this hexadecimal
value to binary form, we get the result as: ‘0b1000’.
30. What is the result of the expression:
0x35 | 0x75
Explanation: The binary value of 0x35 is 110101 and that of 0x75 is 1110101. On OR-ing these two values we
get the output as: 1110101, which is equal to 117. Hence the result of the above expression is 117.
30
EXPERIMENT -4
OBJECTIVE:
Write a python script to print the current date in the following format “Sun May 29
SOURCECODE:
today =date.today()
# dd/mm/YY
d1 =today.strftime("%d/%m/%Y")
print("d1 =", d1)
# mm/dd/y
d3 =today.strftime("%m/%d/%y")
print("d3 =", d3)
d1 = 25/12/2018
d2 = December 25, 2018
d3 = 12/25/18
d4 = 12/25/18
VIVA Questions
1. What is Python?
Python is a high-level, interpreted, interactive and object-oriented scripting language. Python
is designed to be highly readable. It uses English keywords frequently where as other
languages use punctuation, and it has fewer syntactical constructions than other languages.
2. What is the purpose of PYTHONPATH environment variable?
31
PYTHONPATH - It has a role similar to PATH. This variable tells the Python interpreter
where to locate the module files imported into a program. It should include the Python source
library directory and the directories containing Python source code. PYTHONPATH is
sometimes preset by the Python installer.
3. What is the purpose of PYTHONSTARTUP environment variable?
PYTHONSTARTUP - It contains the path of an initialization file containing Python source
code. It is executed every time you start the interpreter. It is named as .pythonrc.py in Unix
and it contains commands that load utilities or modify PYTHONPATH.
4. What is the purpose of PYTHONCASEOK environment variable?
PYTHONCASEOK − It is used in Windows to instruct Python to find the first case-
insensitive match in an import statement. Set this variable to any value to activate it.
5. What is the purpose of PYTHONHOME environment variable?
PYTHONHOME − It is an alternative module search path. It is usually embedded in the
PYTHONSTARTUP or PYTHONPATH directories to make switching module libraries easy.
6. Is python a case sensitive language?
Yes! Python is a case sensitive programming language.
7. What are the supported data types in Python?
Python has five standard data types −
Numbers
String
List
Tuple
Dictionary
8. What is the output of print str if str = 'Hello World!'?
It will print complete string. Output would be Hello World!.
9. What is the output of print str[0] if str = 'Hello World!'?
It will print first character of the string. Output would be H.
10. What is the output of print str[2:5] if str = 'Hello World!'?
It will print characters starting from 3rd to 5th. Output would be llo.
11. What is the output of print str[2:] if str = 'Hello World!'?
It will print characters starting from 3rd character. Output would be lloWorld!.
12. What is the output of print str * 2 if str = 'Hello World!'?
It will print string two times. Output would be Hello World!Hello World!.
13. What is the output of print str + "TEST" if str = 'Hello World!'?
It will print concatenated string. Output would be Hello World!TEST.
14. What is the output of print list if list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]?
It will print complete list. Output would be ['abcd', 786, 2.23, 'john', 70.200000000000003].
15. What is the output of print list[0] if list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]?
It will print first element of the list. Output would be abcd.
16. What is the output of print list[1:3] if list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]?
It will print elements starting from 2nd till 3rd. Output would be [786, 2.23].
17. What is the output of print list[2:] if list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]?
32
It will print elements starting from 3rd element. Output would be [2.23, 'john',
70.200000000000003].
18. What is the output of print tinylist * 2 if tinylist = [123, 'john']?
It will print list two times. Output would be [123, 'john', 123, 'john'].
19. What is the output of print list1 + list2, if list1 = [ 'abcd', 786 , 2.23, 'john', 70.2 ] and ist2 =
[123, 'john']?
It will print concatenated lists. Output would be ['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
20. What are tuples in Python?
A tuple is another sequence data type that is similar to the list. A tuple consists of a number of
values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.
21. What is the difference between tuples and lists in Python?
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.
22. What is the output of print tuple if tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )?
It will print complete tuple. Output would be ('abcd', 786, 2.23, 'john', 70.200000000000003).
23. What is the output of print tuple[0] if tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )?
It will print first element of the tuple. Output would be abcd.
24. What is the output of print tuple[1:3] if tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )?
It will print elements starting from 2nd till 3rd. Output would be (786, 2.23).
25. What is the output of print tuple[2:] if tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )?
It will print elements starting from 3rd element. Output would be (2.23, 'john',
70.200000000000003).
26. What is the output of print tinytuple * 2 if tinytuple = (123, 'john')?
It will print tuple two times. Output would be (123, 'john', 123, 'john').
27. 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 would be ('abcd', 786, 2.23, 'john',
70.200000000000003, 123, 'john').
28. What are Python's dictionaries?
Python's dictionaries are kind of hash table type. They work like associative arrays or hashes
found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type,
but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python
object.
29. How will you get all the keys from the dictionary?
Using dictionary.keys() function, we can get all the keys from the dictionary object.
printdict.keys()# Prints all the keys
30. How will you get all the values from the dictionary?
Using dictionary.values() function, we can get all the values from the dictionary object.
EXPERIMENT -5
OBJECTIVE:
33
Write a program to create, append, and remove lists in python.
SOURCECODE:
my_list = ['p','r','o','b','l','e','m']
my_list.remove('p')
# Output: 'o'
print(my_list.pop(1))
# Output: 'm'
print(my_list.pop())
my_list.clear()
# Output: []
print(my_list)
INPUT ANDOUTPUT:
my_list=['p','r','o','b','l','e','m']
>>>my_list[2:3]=[]
>>>my_list
['p','r','b','l','e','m']
>>>my_list[2:5]=[]
>>>my_list
['p','r','m']
VIVA Questions
1. How will you convert a string to an int in python?
int(x [,base]) - Converts x to an integer. base specifies the base if x is a string.
2. How will you convert a string to a long in python?
34
long(x [,base] ) - Converts x to a long integer. base specifies the base if x is a string.
3. How will you convert a string to a float in python?
float(x) − Converts x to a floating-point number.
4. How will you convert a object to a string in python?
str(x) − Converts object x to a string representation.
5. How will you convert a object to a regular expression in python?
repr(x) − Converts object x to an expression string.
6. How will you convert a String to an object in python?
eval(str) − Evaluates a string and returns an object.
7. How will you convert a string to a tuple in python?
tuple(s) − Converts s to a tuple.
8. How will you convert a string to a list in python?
list(s) − Converts s to a list.
9. How will you convert a string to a set in python?
set(s) − Converts s to a set.
10. How will you create a dictionary using tuples in python?
dict(d) − Creates a dictionary. d must be a sequence of (key,value) tuples.
11. How will you convert a string to a frozen set in python?
frozenset(s) − Converts s to a frozen set.
12. How will you convert an integer to a character in python?
chr(x) − Converts an integer to a character.
13. How will you convert an integer to an unicode character in python?
unichr(x) − Converts an integer to a Unicode character.
14. How will you convert a single character to its integer value in python?
ord(x) − Converts a single character to its integer value.
15. How will you convert an integer to hexadecimal string in python?
hex(x) − Converts an integer to a hexadecimal string.
16. How will you convert an integer to octal string in python?
oct(x) − Converts an integer to an octal string.
17. What is the purpose of ** operator?
** Exponent − Performs exponential (power) calculation on operators. a**b = 10 to the
power 20 if a = 10 and b = 20.
18. What is the purpose of // operator?
// Floor Division − The division of operands where the result is the quotient in which the
digits after the decimal point are removed.
19. What is the purpose of is operator?
is − Evaluates to true if the variables on either side of the operator point to the same object
and false otherwise. x is y, here is results in 1 if id(x) equals id(y).
20. What is the purpose of not in operator?
not in − Evaluates to true if it does not finds a variable in the specified sequence and false
otherwise. x not in y, here not in results in a 1 if x is not a member of sequence y.
21. What is the purpose break statement in python?
break statement − Terminates the loop statement and transfers execution to the statement
immediately following the loop.
22. What is the purpose continue statement in python?
continue statement − Causes the loop to skip the remainder of its body and immediately retest
its condition prior to reiterating.
35
23. What is the purpose pass statement in python?
pass statement − The pass statement in Python is used when a statement is required
syntactically but you do not want any command or code to execute.
24. How can you pick a random item from a list or tuple?
choice(seq) − Returns a random item from a list, tuple, or string.
25. How can you pick a random item from a range?
randrange ([start,] stop [,step]) − returns a randomly selected element from range(start, stop,
step).
26. How can you get a random number in python?
random() − returns a random float r, such that 0 is less than or equal to r and r is less than 1.
27. How will you set the starting value in generating random numbers?
seed([x]) − Sets the integer starting value used in generating random numbers. Call this
function before calling any other random module function. Returns None.
28. How will you randomizes the items of a list in place?
shuffle(lst) − Randomizes the items of a list in place. Returns None.
29. How will you capitalizes first letter of string?
capitalize() − Capitalizes first letter of string.
30. How will you check in a string that all characters are alphanumeric?
isalnum() − Returns true if string has at least 1 character and all characters are alphanumeric
and false otherwise.
36
EXPERIMENT -6
OBJECTIVE:
Write a program to demonstrate working with tuples in python.
SOURCECODE:
# empty tuple
# Output: ()
my_tuple = ()
print(my_tuple)
# nested tuple
# Output: ("mouse", [8, 4, 6], (1, 2, 3))
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)
INPUT ANDOUTPUT:
37
()
(1, 2, 3)
(1, 'Hello', 3.4)
('mouse', [8, 4, 6], (1, 2, 3))
(3, 4.6, 'dog')
3
4.6
dog
VIVA Questions
1. How will you check in a string that all characters are digits?
isdigit() − Returns true if string contains only digits and false otherwise.
2. How will you check in a string that all characters are in lowercase?
38
islower() − Returns true if string has at least 1 cased character and all cased characters are in
lowercase and false otherwise.
3. How will you check in a string that all characters are numerics?
isnumeric() − Returns true if a unicode string contains only numeric characters and false
otherwise.
4. How will you check in a string that all characters are whitespaces?
isspace() − Returns true if string contains only whitespace characters and false otherwise.
5. How will you check in a string that it is properly titlecased?
istitle() − Returns true if string is properly "titlecased" and false otherwise.
6. How will you check in a string that all characters are in uppercase?
isupper() − Returns true if string has at least one cased character and all cased characters are
in uppercase and false otherwise.
7. How will you merge elements in a sequence?
join(seq) − Merges (concatenates) the string representations of elements in sequence seq into
a string, with separator string.
8. How will you get the length of the string?
len(string) − Returns the length of the string.
9. How will you get a space-padded string with the original string left-justified to a total of width
columns?
ljust(width[, fillchar]) − Returns a space-padded string with the original string left-justified to
a total of width columns.
10. How will you convert a string to all lowercase?
lower() − Converts all uppercase letters in string to lowercase.
11. How will you remove all leading whitespace in string?
lstrip() − Removes all leading whitespace in string.
12. How will you get the max alphabetical character from the string?
max(str) − Returns the max alphabetical character from the string str.
13. How will you get the min alphabetical character from the string?
min(str) − Returns the min alphabetical character from the string str.
14. How will you replaces all occurrences of old substring in string with new string?
replace(old, new [, max]) − Replaces all occurrences of old in string with new or at most max
occurrences if max given.
15. How will you remove all leading and trailing whitespace in string?
strip([chars]) − Performs both lstrip() and rstrip() on string.
16. How will you change case for all letters in string?
swapcase() − Inverts case for all letters in string.
17. How will you get titlecased version of string?
title() − Returns "titlecased" version of string, that is, all words begin with uppercase and the
rest are lowercase.
18. How will you convert a string to all uppercase?
upper() − Converts all lowercase letters in string to uppercase.
19. How will you check in a string that all characters are decimal?
isdecimal() − Returns true if a unicode string contains only decimal characters and false
otherwise.
20. What is the difference between del() and remove() methods of list?
To remove a list element, you can use either the del statement if you know exactly which
element(s) you are deleting or the remove() method if you do not know.
39
EXPERIMENT -7
OBJECTIVE:
SOURCECODE:
# Output: Jack
print(my_dict['name'])
# Output: 26
print(my_dict.get('age'))
INPUT ANDOUTPUT:
Jack
26
40
EXPERIMENT -8
OBJECTIVE:
SOURCECODE:
# Python program to find the largest number among the three input numbers
43
EXPERIMENT -9
OBJECTIVE:
SOURCECODE:
# Python Program to convert temperature in celsius to fahrenheit
# calculate fahrenheit
fahrenheit = (celsius * 1.8) + 32
print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %(celsius,fahrenheit))
INPUT ANDOUTPUT:
47
: EXPERIMENT -10
OBJECTIVE:
Write a Python program to construct the following pattern, using a nested for loop
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
SOURCECODE:
n=5;
for i in range(n):
for j in range(i):
print ('* ', end="")
print('')
for i in range(n,0,-1):
for j in range(i):
print('* ', end="")
print('')
INPUT ANDOUTPUT:
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
51
EXPERIMENT -11
OBJECTIVE:
Write a Python script that prints prime numbers less than 20.
SOURCECODE:
INPUT ANDOUTPUT:
55
EXPERIMENT -12
OBJECTIVE:
SOURCECODE:
# Python program to find the factorial of a number provided by the user.
factorial = 1
59
EXPERIMENT -13
OBJECTIVE:
Write a program that accepts the lengths of three sides of a triangle as inputs. The
program output should indicate whether or not the triangle is a right triangle (Recall
from the Pythagorean Theorem that in a right triangle, the square of one side equals
SOURCECODE:
# Python Program to find the area of triangle
a=5
b=6
c=7
62
EXPERIMENT -14
OBJECTIVE:
Write a python program to define a module to find Fibonacci Numbers and import the
module to another program.
SOURCECODE:
# Program to display the Fibonacci sequence up to n-th term where n is provided by the user
# change this value for a different result
nterms = 10
# uncomment to take input from the user
#nterms = int(input("How many terms? "))
# first two terms
n1 = 0
n2 = 1
count = 0
# check if the number of terms is valid
if nterms<= 0:
print("Please enter a positive integer")
elifnterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence upto",nterms,":")
while count <nterms:
print(n1,end=' , ')
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
INPUT ANDOUTPUT:
66
EXPERIMENT -15
OBJECTIVE:
Write a python program to define a module and import a specific function in that
module to another program.
SOURCECODE:
# Python Program to find numbers divisible by thirteen from a list using anonymous function
INPUT ANDOUTPUT:
70
EXPERIMENT -16
OBJECTIVE:
Write a script named copyfile.py. This script should prompt the user for the names of
two text files. The contents of the first file should be input and written to the second
file.
SOURCECODE:
withopen("test.txt")as f:
withopen("out.txt","w")as f1:
for line in f:
f1.write(line)
INPUT ANDOUTPUT:
Case 1:
Contents of file(test.txt):
Hello world
Output(out.text):
Hello world
Case 2:
Contents of file(test.txt):
Sanfoundry
Output(out.text):
Sanfoundry
74
EXPERIMENT -17
OBJECTIVE:
Write a program that inputs a text file. The program should print all of the unique
words in the file in alphabetical order.
SOURCECODE:
INPUT ANDOUTPUT:
80
EXPERIMENT -18
OBJECTIVE:
SOURCECODE:
class py_solution:
def int_to_Roman(self, num):
val = [
1000, 900, 500, 400,
100, 90, 50, 40,
10, 9, 5, 4,
1
]
syb = [
"M", "CM", "D", "CD",
"C", "XC", "L", "XL",
"X", "IX", "V", "IV",
"I"
]
roman_num = ''
i=0
while num> 0:
for _ in range(num // val[i]):
roman_num += syb[i]
num -= val[i]
i += 1
return roman_num
print(py_solution().int_to_Roman(1))
print(py_solution().int_to_Roman(4000))
INPUT ANDOUTPUT:
I
MMMM
85
EXPERIMENT -19
OBJECTIVE:
SOURCECODE:
class py_solution:
def pow(self, x, n):
if x==0 or x==1 or n==1:
return x
if x==-1:
if n%2 ==0:
return 1
else:
return -1
if n==0:
return 1
if n<0:
return 1/self.pow(x,-n)
val = self.pow(x,n//2)
if n%2 ==0:
return val*val
return val*val*x
print(py_solution().pow(2, -3));
print(py_solution().pow(3, 5));
print(py_solution().pow(100, 0));
INPUT ANDOUTPUT:
0.125
243
1
94
EXPERIMENT -20
OBJECTIVE:
SOURCECODE:
def reverseWords(input):
return output
INPUT ANDOUTPUT: