Viva QA Python
Viva QA Python
If it makes for an introductory language to programming, Python must mean something. These are
its qualities:
Interpreted
Dynamically-typed
Object-oriented
Concise and simple
Free
Has a large community
If the expression is True, the statement under [on true] is executed. Else, that under [on false] is
executed.
1. >>> mylist=[0,1,2,3,4,5,6,7,8]
A negative index, unlike a positive one, begins searching from the right.
1. >>> mylist[-3]
1. >>> mylist[-6:-1]
[3, 4, 5, 6, 7]
Q.5. Is Python case-sensitive?
1. >>> myname='Ayushi'
2. >>> Myname
Myname
As we can see, this raised a NameError. This means that Python is indeed case-sensitive.
According to the official Python documentation, an identifier can be of any length. However, PEP 8
suggests that you should limit all lines to a maximum of 79 characters. Also, PEP 20 says ‘readability
counts’. So, a very long identifier will violate PEP-8 and PEP-20.
Apart from that, there are certain rules we must follow to name one:
1. >>> 'AyuShi'.lower()
‘ayushi’
1. >>> 'AyuShi'.upper()
‘AYUSHI’
Also, to check if a string is in all uppercase or all lowercase, we use the methods isupper() and
islower().
1. >>> 'AyuShi'.isupper()
False
1. >>> 'AYUSHI'.isupper()
True
1. >>> 'ayushi'.islower()
True
1. >>> '@yu$hi'.islower()
True
1. >>> '@YU$HI'.isupper()
True
True
There may be times in our code when we haven’t decided what to do yet, but we must type
something for it to be syntactically correct. In such a case, we use the pass statement.
1
2
Practical No. 2
The help() function displays the documentation string and help for its argument.
copy(x)
1. >>> dir(copy.copy)
1. >>> mydict={'a':1,'b':2,'c':3,'e':5}
2. >>> mydict.keys()
1. >>> (1,2,3,4,5)[2:4]
(3, 4)
1. >>> [7,6,8,5,9][2:]
[8, 5, 9]
1. >>> 'Hello'[:-1]
‘Hell’
Unlike languages like C++, Python does not have multiline comments. All it has is octothorpe (#).
Anything following a hash is considered a comment, and the interpreter ignores it.
In fact, you can place a comment anywhere in your code. You can use it to explain your code.
Q.5. How will you check if all characters in a string are alphanumeric?
1. >>> 'ayushi'.capitalize()
‘Ayushi’
1. >>> type(str.capitalize)
<class ‘method_descriptor’>
1. >>> '@yushi'.capitalize()
‘@yushi’
1. >>> 'Ayushi123'.isalnum()
True
1. >>> 'Ayushi123!'.isalnum()
False
1. >>> '123.3'.isdigit()
False
1. >>> '123'.isnumeric()
True
1. >>> 'ayushi'.islower()
True
1. >>> 'Ayushi'.isupper()
False
1. >>> 'Ayushi'.istitle()
True
True
1. >>> '123F'.isdecimal()
False
Q.7. We know Python is all the rage these days. But to be truly accepting of a great
technology, you must know its pitfalls as well. Would you like to talk about this?
Of course. To be truly yourself, you must be accepting of your flaws. Only then can you
move forward to work on them. Python has its flaws too:
Q.8. With Python, how do you find out which directory you are currently in?
To find this, we use the function/method getcwd(). We import it from the module os.
1. >>> import os
2. >>> os.getcwd()
Practical No. 3
1. >>> a=[1,2,4]
Now, we use the method insert. The first argument is the index at which to insert, the second is the
value to insert.
1. >>> a.insert(2,3)
2. >>> a
[1, 2, 3, 4]
1. >>> a.reverse()
2. >>> a
[4, 3, 2, 1]
1. >>> a[::-1]
2. >>> a
[1, 2, 3, 4]
This gives us the original list because we already reversed it once. However, this does not modify the
original list to reverse it.
1. >>> a.reverse()
2. >>> a
[4, 3, 2, 1]
1. >>> a[::-1]
2. >>> a
[1, 2, 3, 4]
This gives us the original list because we already reversed it once. However, this does not modify the
original list to reverse it.
1. >>>
If you have worked with the IDLE, you will see this prompt.
For any kind of statements, we possibly need to define a block of code under them. However,
Python does not support curly braces. This means we must end such statements with colons and
then indent the blocks under those with the same amount.
1. >>> if 3>1:
2. print("Hello")
3. print("Goodbye")
Hello
Goodbye
Q.8. Will the do-while loop work if you don’t end it with a semicolon?
Python does not support an intrinsic do-while loop. Secondly, to terminate do-while loops is a
necessity for languages like C++.
Q.9. In one line, show us how you’ll get the max alphabetical character from a string.
1. >>> max('flyiNg')
‘y’
The following are the ASCII values for all the letters of this string-
f- 102
l- 108
y- 121
i- 105
N- 78
g- 103
1. >>> max('fly{}iNg')
‘}’
(Bonus: } – 125)
Practical No 4.
Python is a jack of many trades, check out Applications of Python to find out more.
Meanwhile, we’ll say we can use it for:
Q.2. Can you name ten built-in functions in Python and explain each in brief?
1. >>> complex(3.5,4)
(3.5+4j)
1. >>> eval('print(max(22,22.0)-min(2,3))')
20
[2, 0, False]
1. >>> hash(3.7)
644245917
hex()- Converts an integer to a hexadecimal.
1. >>> hex(14)
‘0xe’
Enter a number7
1. ‘7’
1. >>> len('Ayushi')
1. >>> locals()
1. >>> file=open('tabs.txt')
1. >>> word=’abcdefghij’
2. >>> word[:3]+word[3:]
The output is ‘abcdefghij’. The first slice gives us ‘abc’, the next gives us ‘defghij’.
1. >>> nums=['one','two','three','four','five','six','seven']
2. >>> s=' '.join(nums)
3. >>> s
1. >>> list=[1,2,1,3,4,2]
2. >>> set(list)
{1, 2, 3, 4}
To create a thread, we create a class that we make override the run method of the thread
class. Then, we instantiate it.
A thread that we just created is in the new state. When we make a call to start() on it, it
forwards the threads for scheduling. These are in the ready state.
When execution begins, the thread is in the running state.
Calls to methods like sleep() and join() make a thread wait. Such a thread is in the
waiting/blocked state.
When a thread is done waiting or executing, other waiting threads are sent for scheduling.
A running thread that is done executing terminates and is in the dead state.
1. >>> roots={25:5,16:4,9:3,4:2,1:1}
2. >>> type(roots)
<class ‘dict’>
1. >>> roots[9]
{25: 5, 16: 4, 9: 3, 4: 2, 1: 1}
The // operator performs floor division. It will return the integer part of the result on division.
1. >>> 7//2
3
Normal division would return 3.5 here.
Similarly, ** performs exponentiation. a**b returns the value of a raised to the power b.
1. >>> 2**10
1024
Finally, % is for modulus. This gives us the value left after the highest achievable division.
1. >>> 13%7
1. >>> 3.5%1.5
0.5
Practical No. 5
False
1. >>> 7<7 or True
True
False
Q.4. What are membership operators?
With the operators ‘in’ and ‘not in’, we can confirm if a value is a member in another.
True
True
Q.5. Explain identity operators in Python.
The operators ‘is’ and ‘is not’ tell us if two values have the same identity.
1. >>> 10 is '10'
False
True
1. >>> a=7.0
2. >>>
Lists – A list is an ordered collection of values, and we declare it using square brackets.
1. >>> colors=['red','green','blue']
2. >>> type(colors)
<class ‘list’>
Tuples – A tuple, like a list, is an ordered collection of values. The difference. However, is
that a tuple is immutable. This means that we cannot change a value in it.
1. >>> name=('Ayushi','Sharma')
2. >>> name[0]='Avery'
1. >>> squares={1:1,2:4,3:9,4:16,5:25}
2. >>> type(squares)
<class ‘dict’>
1. >>> type({})
<class ‘dict’>
We can also use a dictionary comprehension:
Hi
To get a function’s docstring, we use its __doc__ attribute.
1. >>> sayhi.__doc__
Practical No. 6
If a string contains only numerical characters, you can convert it into an integer using the int()
function.
1. >>> int('227')
227
1. >>> type('227')
<class ‘str’>
1. >>> type(int('227'))
<class ‘int’>
For taking input from the user, we have the function input(). In Python 2, we had another function
raw_input().
The input() function takes, as an argument, the text to be displayed for the task:
Enter a number7
But if you have paid attention, you know that it takes input in the form of a string.
1. >>> type(a)
<class ‘str’>
Multiplying this by 2 gives us this:
1. >>> a*=2
2. >>> a
’77’
Enter a number7
1. >>> a*=2
2. >>> a
14
When we want to execute a sequence of statements, we can give it a name. Let’s define a function
to take two numbers and return the greater number.
3.5
24
One of the less common functions with beginners, zip() returns an iterator of tuples.
1. >>> list(zip(['a','b','c'],[1,2,3])
Here, it pairs items from the two lists and creates tuples with those. But it doesn’t have to be lists.
1. >>> list(zip(('a','b','c'),(1,2,3)))
This is simple. We call the function len() on the string we want to calculate the length of.
13
[1, 3, 5, 7, 9]
We saw previously, to get all keys from a dictionary, we make a call to the keys() method. Similarly,
for values, we use the method values().
False
1. >>> 4 in {'a':1,'b':2,'c':3,'d':4}.values()
True
Practical No. 7
We have the swapcase() method from the str class to do just that.
1. >>> 'AyuShi'.swapcase()
‘aYUsHI’
Questions 50 through 52 assume the string ‘I love Python’. You need to do the needful.
1. >>> i=0
2. >>> while s[i]!='t':
3. print(s[i],end=’’)
4. i+=1
I love Py
Q.3. Write code to print everything in the string except the spaces.
1. >>> for i in s:
2. if i==' ': continue
3. print(i,end='')
IlovePython
I love Python
I love Python
I love Python
I love Python
I love Python
I love Python
1. >>> bytes([2,4,8])
b’\x02\x04\x08′
1. >>> bytes(5)
b’\x00\x00\x00\x00\x00′
1. >>> bytes('world','utf-8')
b’world’
Q.7. Create a new list to convert the following list of number strings to a list of numbers.
nums=[‘22’,’68’,’110’,’89’,’31’,’12’]
We will use the int() function with a list comprehension to convert these strings into integers
and put them in a list.
Q.8. Given the first and last names of all employees in your firm, what data type will
you use to store it?
I can use a dictionary to store that. It would be something like this-
{‘first_name’:’Ayushi’,’second_name’:’Sharma’
Practical No. 8
Q.1. How would you work with numbers other than those in the decimal number
system?
With Python, it is possible to type numbers in binary, octal, and hexadecimal.
Binary numbers are made of 0 and 1. To type in binary, we use the prefix 0b or 0B.
1. >>> int(0b1010)
10
To convert a number into its binary form, we use bin().
1. >>> bin(0xf)
‘0b1111’
Octal numbers may have digits from 0 to 7. We use the prefix 0o or 0O.
1. >>> oct(8)
‘0o10’
Hexadecimal numbers may have digits from 0 to 15. We use the prefix 0x or 0X.
1. >>> hex(16)
‘0x10’
1. >>> hex(15)
‘0xf’
Q.2. What does the following code output?
The range() function in Python can take up to 3 arguments. Let’s see this one by one.
a. One argument
When we pass only one argument, it takes it as the stop value. Here, the start value is 0, and the
step value is +1.
1. >>> list(range(5))
[0, 1, 2, 3, 4]
1. >>> list(range(-5))
[]
1. >>> list(range(0))
[]
b. Two arguments
When we pass two arguments, the first one is the start value, and the second is the stop value.
1. >>> list(range(2,7))
[2, 3, 4, 5, 6]
1. >>> list(range(7,2))
[]
1. >>> list(range(-3,4))
c. Three arguments
Here, the first argument is the start value, the second is the stop value, and the third is the step
value.
1. >>> list(range(2,9,2))
[2, 4, 6, 8]
1. >>> list(range(9,2,-1))
[9, 8, 7, 6, 5, 4, 3]
PEP 8 is a coding convention that lets us write more readable code. In other words, it is a set of
recommendations.
1. >>> a,b=b,a
1. >>> a,b=2,3
2. >>> a,b=b,a
3. >>> a,b
(3, 2)
First –
Second –
Q.8. If you are ever stuck in an infinite loop, how will you break out of it?
For this, we press Ctrl+C. This interrupts the execution. Let’s create an infinite loop to demonstrate
this.
1. >>> def counterfunc(n):
2. while(n==7):print(n)
3. >>> counterfunc(7)
counterfunc(7)
KeyboardInterrupt
Practical No. 9
Python files first compile to bytecode. Then, the host executes them.
To pass its parameters to a function, Python uses pass-by-reference. If you change a parameter
within a function, the change reflects in the calling function. This is its default behavior. However,
when we pass literal arguments like strings, numbers, or tuples, they pass by value. This is because
they are immutable.
The with statement in Python ensures that cleanup code is executed when working with unmanaged
resources by encapsulating common preparation and cleanup tasks. It may be used to open a file, do
something, and then automatically close the file at the end. It may be used to open a database
connection, do some processing, then automatically close the connection to ensure resources are
closed and available for others. with will cleanup the resources even if an exception is thrown. This
statement is like the using statement in C#.
Consider you put some code in a try block, then in the finally block, you close any resources used.
The with statement is like syntactic sugar for that.
While both files hold bytecode, .pyc is the compiled version of a Python file. It has platform-
independent bytecode. Hence, we can execute it on any platform that supports the .pyc format.
Python automatically generates it to improve performance(in terms of load time, not speed).
Encapsulation
Abstraction
Inheritance
Polymorphism
Data hiding
Immutable objects- Those which do not let us modify their contents. Examples of these will be
tuples, booleans, strings, integers, floats, and complexes. Iterations on such objects are faster.
1. >>> tuple=(1,2,4)
2. >>> tuple
(1, 2, 4)
1. >>> 2+4j
(2+4j)
Mutable objects – Those that let you modify their contents. Examples of these are lists, sets, and
dicts. Iterations on such objects are slower.
1. >>> [2,4,9]
[2, 4, 9]
1. >>> dict1={1:1,2:2}
2. >>> dict1
{1: 1, 2: 2}
While two equal immutable objects’ reference variables share the same address, it is possible to
create two mutable objects with the same content.
Practical No. 10
Q.8.If given the first and last names of bunch of employees how would you store it and what
datatype?