Python Interview Questions and Answers for Freshers
1. What are the key features of 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
2. Differentiate between lists and tuples.
The major difference is that a list is mutable, but a tuple is immutable. Examples:>>> mylist=[1,3,3]
>>> mylist[1]=2
>>> mytuple=(1,3,3)
>>> mytuple[1]=2
Traceback (most recent call last):
File “<pyshell#97>”, line 1, in <module>
mytuple[1]=2
TypeError: ‘tuple’ object does not support item assignment
3. Explain the ternary operator in Python.
Unlike C++, we don’t have ?: in Python, but we have this:[on true] if [expression] else [on false]
If the expression is True, the statement under [on true] is executed. Else, that under [on false] is executed.
Below is how you would use it:
>>> a,b=2,3
>>> min=a if a<b else b
>>> min
Ex: 2
>>> print("Hi") if a<b else print("Bye")
4. What are negative indices?
Let’s take a list for this.>>> mylist=[0,1,2,3,4,5,6,7,8]
A negative index, unlike a positive one, begins searching from the right.
>>> mylist[-3]
This also helps with slicing from the back:
>>> mylist[-6:-1]
[3, 4, 5, 6, 7]
5. Is Python case-sensitive?
A language is case-sensitive if it distinguishes between identifiers like myname and Myname. In other words, it cares about case- lowercase or uppercase. Let’s try this with Python.>>> myname='Ayushi'
>>> Myname
Traceback (most recent call last):
File “<pyshell#3>”, line 1, in <module>
Myname
NameError: name ‘Myname’ is not defined
As you can see, this raised a NameError. This means that Python is indeed case-sensitive.
6. How long can an identifier be in Python?
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:
- It can only begin with an underscore or a character from A-Z or a-z.
- The rest of it can contain anything from the following: A-Z/a-z/_/0-9.
- Python is case-sensitive, as we discussed in the previous question.
- Keywords cannot be used as identifiers. Python has the following keywords:
7. How would you convert a string into lowercase?
We use the lower() method for this.>>> 'AyuShi'.lower()
‘ayushi’
To convert it into uppercase, then, we use upper().
>>> 'AyuShi'.upper()
‘AYUSHI’
Also, to check if a string is in all uppercase or all lowercase, we use the methods isupper() and islower().
>>> 'AyuShi'.isupper()
False
>>> 'AYUSHI'.isupper()
True
>>> 'ayushi'.islower()
True
>>> '@yu$hi'.islower()
True
>>> '@YU$HI'.isupper()
True
So, characters like @ and $ will suffice for both cases
Also, istitle() will tell us if a string is in title case.
>>> 'The Corpse Bride'.istitle()
True
8. What is the pass statement in Python?
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.>>> def func(*args):
pass
>>>
Similarly, the break statement breaks out of a loop.
>>> for i in range(7):
if i==3: break
print(i)
1
2
Finally, the continue statement skips to the next iteration.
>>> for i in range(7):
if i==3: continue
print(i)
1
2
4
5
6
9. Explain help() and dir() functions in Python.
The help() function displays the documentation string and help for its argument.>>> import copy
>>> help(copy.copy)
Help on function copy in module copy:
copy(x)
Shallow copy operation on arbitrary Python objects.
See the module’s __doc__ string for more info.
The dir() function displays all the members of an object(any kind).
>>> dir(copy.copy)
[‘__annotations__’, ‘__call__’, ‘__class__’, ‘__closure__’, ‘__code__’, ‘__defaults__’,
‘__delattr__’, ‘__dict__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__get__’,
‘__getattribute__’, ‘__globals__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__init_subclass__’, ‘__kwdefaults__’,
‘__le__’, ‘__lt__’, ‘__module__’, ‘__name__’, ‘__ne__’, ‘__new__’, ‘__qualname__’, ‘__reduce__’,
‘__reduce_ex__’, ‘__repr__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’]
10. How do you get a list of all the keys in a dictionary?
Be specific in these type of Python Interview Questions and Answers.For this, we use the function keys().
>>> mydict={'a':1,'b':2,'c':3,'e':5}
>>> mydict.keys()
dict_keys([‘a’, ‘b’, ‘c’, ‘e’])
11. What is slicing?
Slicing is a technique that allows us to retrieve only a part of a list, tuple, or string. For this, we use the slicing operator [].>>> (1,2,3,4,5)[2:4]
(3, 4)
>>> [7,6,8,5,9][2:]
[8, 5, 9]
>>> 'Hello'[:-1]
‘Hell’
12. How would you declare a comment in Python?
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.>>> #line 1 of comment
>>> #line 2 of comment
In fact, you can place a comment anywhere in your code. You can use it to explain your code.
13. How will you check if all characters in a string are alphanumeric?
For this, we use the method isalnum().14. How will you capitalize the first letter of a string?
Simply using the method capitalize().>>> 'ayushi'.capitalize() - Output: ‘Ayushi’
>>> type(str.capitalize) - Output: <class ‘method_descriptor’>
However, it will let other characters be.
>>> '@yushi'.capitalize() - Output: ‘@yushi’
>>> 'Ayushi123'.isalnum() - Output: True
>>> 'Ayushi123!'.isalnum() - Output: False
Other methods that we have include:
>>> '123.3'.isdigit() - Output: False
>>> '123'.isnumeric() - Output: True
>>> 'ayushi'.islower() - Output: True
>>> 'Ayushi'.isupper() - Output: False
>>> 'Ayushi'.istitle() - Output: True
>>> ' '.isspace() - Output: True
>>> '123F'.isdecimal() - Output: False
15. 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.>>> import os
>>> os.getcwd()
‘C:\\Users\\lifei\\AppData\\Local\\Programs\\Python\\Python36-32’
>>> type(os.getcwd)
<class ‘builtin_function_or_method’>
We can also change the current working directory with chdir().
>>> os.chdir('C:\\Users\\lifei\\Desktop')
>>> os.getcwd()
‘C:\\Users\\lifei\\Desktop’
16. How do you insert an object at a given index in Python?
Let’s build a list first.>>> 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.
>>> a.insert(2,3)
>>> a
[1, 2, 3, 4]
17. And how do you reverse a list?
Using the reverse() method.>>> a.reverse()
>>> a
[4, 3, 2, 1]
You can also do it via slicing from right to left:
>>> a[::-1]
>>> 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.
18. What is the Python interpreter prompt?
This is the following sign for Python Interpreter:>>>
If you have worked with the IDLE, you will see this prompt.
19. How does a function return values?
A function uses the ‘return’ keyword to return a value. Take a look:>>> def add(a,b):
return a+b
20. How would you define a block in Python?
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.>>> if 3>1:
print("Hello")
print("Goodbye")
Hello
Goodbye
21. Why do we need break and continue in Python?
Both break and continue are statements that control flow in Python loops. break stops the current loop from executing further and transfers the control to the next block. continue jumps to the next iteration of the loop without exhausting it.22. What is Python good for?
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:
- Web and Internet Development
- Desktop GUI
- Scientific and Numeric Applications
- Software Development Applications
- Applications in Education
- Applications in Business
- Database Access
- Network Programming
- Games, 3D Graphics
- Other Python Applications
23. Can you name ten built-in functions in Python and explain each in brief?
Ten Built-in Functions, you say? Okay, here you go.complex()- Creates a complex number.
>>> complex(3.5,4) - Output: (3.5+4j)
eval()- Parses a string as an expression.
>>> eval('print(max(22,22.0)-min(2,3))') - Output: 20
filter()- Filters in items for which the condition is true.
>>> list(filter(lambda x:x%2==0,[1,2,0,False])) - Output: [2, 0, False]
format()- Lets us format a string.
>>> print("a={0} but b={1}".format(a,b)) - Output: a=2 but b=3
hash()- Returns the hash value of an object.
>>> hash(3.7) - Output: 644245917
hex()- Converts an integer to a hexadecimal.
>>> hex(14) - Output: ‘0xe’
input()- Reads and returns a line of string.
>>> input('Enter a number') - Output: Enter a number 7
‘7’
len()- Returns the length of an object.
>>> len('Ayushi') - Output: 6
locals()- Returns a dictionary of the current local symbol table.
>>> locals() - Output: {‘__name__’: ‘__main__’, ‘__doc__’: None, ‘__package__’: None, ‘__loader__’: <class ‘_frozen_importlib.BuiltinImporter’>,
‘__spec__’: None, ‘__annotations__’: {}, ‘__builtins__’: <module ‘builtins’ (built-in)>, ‘a’: 2, ‘b’: 3}
open()- Opens a file.
>>> file=open('tabs.txt')
24. What will the following code output?
>>> word=’abcdefghij’>>> word[:3]+word[3:]
The output is ‘abcdefghij’. The first slice gives us ‘abc’, the next gives us ‘defghij’.
25. How will you convert a list into a string?
We will use the join() method for this.>>> nums=['one','two','three','four','five','six','seven']
>>> s=' '.join(nums)
>>> s
‘one two three four five six seven’
26. How will you remove a duplicate element from a list?
We can turn it into a set to do that.>>> list=[1,2,1,3,4,2]
>>> set(list)
{1, 2, 3, 4}
27. Can you explain the life cycle of a thread?
- 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.
Comments
Post a Comment