data-flair/Python/ Interview questions level 1 Flashcards
Q.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
Q.2. Differentiate between lists and tuples
A list is mutable, but a tuple is immutable
> > > mylist=[1,3,3]
mylist[1]=2
mytuple=(1,3,3)
mytuple[1]=2
Traceback (most recent call last):
File “”, line 1, in
mytuple[1]=2
TypeError: ‘tuple’ object does not support item assignment
Q.4. What are negative indices?
mylist=[0,1,2,3,4,5,6,7,8]
mylist[-3]
6
Q.5. Is Python case-sensitive?
> > > myname=’Ayushi’
Myname
Traceback (most recent call last):
File “”, line 1, in
Myname
NameError: name ‘Myname’ is not defined
Q.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’
It can only begin with an underscore or a character from A-Z or a-z.
Keywords cannot be used as identifiers
Q.7. How would you convert a string into lowercase?
> > > ‘AyuShi’.lower()
‘ayushi’
Q.8. What is the pass and break statements 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
the break statement breaks out of a loop.
> > > for i in range(7):
if i==3: break
the continue statement skips to the next iteration.
for i in range(7):
if i==3:
continue
Outcome of:
for i in range(7): if i==3: continue print(i)
0 1 2 4 5 6
Q.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)
The dir() function displays all the members of an object(any kind) [‘\_\_annotations\_\_’, ‘\_\_call\_\_’, ‘\_\_class\_\_’, ‘\_\_closure\_\_’, ‘\_\_code\_\_’, ‘\_\_defaults\_\_’, ‘\_\_delattr\_\_’, ‘\_\_dict\_\_’,...
Q.10. How do you get a list of all the keys in a dictionary?
mydict={‘a’:1,’b’:2,’c’:3,’e’:5}
mydict.keys()
Outcome:
dict_keys([‘a’, ‘b’, ‘c’, ‘e’])
Q.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]
Outcome:
(3, 4)
Q.12. How would you declare a comment in Python?
All it has is octothorpe (#). Anything following a hash is considered a comment, and the interpreter ignores it.
#line 1 of comment
Q.13. How will you check if all characters in a string are alphanumeric?
‘fsdfsdf42’.isalnum()
Outcome:
True
Q.14. How will you capitalize the first letter of a string?
‘ayushi’.capitalize()
‘Ayushi’
Q.15. 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?
Python’s interpreted nature imposes a speed penalty on it.
While Python is great for a lot of things, it is weak in mobile computing, and in browsers.
Being dynamically-typed, Python uses duck-typing (If it looks like a duck, it must be a duck). This can raise runtime errors.
Python has underdeveloped database access layers. This renders it a less-than-perfect choice for huge database applications.
And then, well, of course. Being easy makes it addictive. Once a Python-coder, always a Python coder.
Q.16. With Python, how do you find out which directory you are currently in?
import os
os.getcwd()
Outcome:
‘/content’
Q.17. How do you insert an object at a given index in Python?
a=[1,2,4]
a.insert(2,3)
a
Outcome:
[1, 2, 3, 4]
Q.18. And how do you reverse a list?
a=[1,2,4]
a.reverse()
a
Outcome:
[4, 2, 1]
Q.19. What is the Python interpreter prompt?
> > >
Q.20. How does a function return values?
A function uses the ‘return’ keyword to return a value.
def add(a,b): return a+b
add(3,4)
Outcome:
7
Q.21. How would you define a block in Python?
we must end such statements with colons and then indent the blocks under those with the same amount.
if 3>1:
print(“Hello”)
Q.22. 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
Q.24. In one line, show us how you’ll get the max alphabetical character from a string
max(‘flyiNg’)
Outcome:
y
Q.25. 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
Outcome of complex(3.5,4) :
(3.5+4j)
Outcome of:
eval(‘print(max(22,22.0)-min(2,3))’)
eval()- Parses a string as an expression.
20
Q.27. What will the following code output?
word= ‘abcdefghij’
word[:3]+word[3:]
‘abcdefghij’
Q.28. How will you convert a list into a string?
nums=[‘one’,’two’,’three’,’four’,’five’,’six’,’seven’]
s=’ ‘.join(nums)
s
Outcome:
‘one two three four five six seven’
Q.29. How will you remove a duplicate element from a list?
list=[1,2,1,3,4,2]
set(list)
Outcome:
{1, 2, 3, 4}
Q.31. What is a dictionary in Python?
an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key:value pair.
roots={25:5,16:4,9:3,4:2,1:1}
type(roots)
#Outcome: dict
Q.32. Explain the //, %, and ** operators in Python.
The // operator performs floor division. It will return the integer part of the result on division.
** performs exponentiation
% is for modulus. This gives us the remainder after the highest achievable division.
Q.33. What do you know about relational operators in Python.
Relational operators compare values.
== != < > >= <=
Q.34. What are assignment operators in Python?
are used to store data into a variable.
x = 5 x = 5, x += 3 results in x = 8 x = 5, x -= 3 results in x = 2 x = 5, x *= 3 results in x = 15 x = 5, x /=3 results in x = 1.667 x = 5, x %=3 results in x = 2 x = 5, x **=3 results in x = 125 x = 5, x //= 3 results in x = 1
Q.35. Explain logical operators in Python
Used for conditional statements are true or false
False and True #False
7<7 or True #True
not 2==2 #False
Q.36. What are membership operators?
used to check whether a value/variable exists in the sequence like string, list, tuples, sets, dictionary or not. These operator returns either True or False
‘me’ in ‘disappointment’ #True
‘us’ not in ‘disappointment’
Q.37. Explain identity operators in Python
Used to determine whether a value is of a certain class or type.
10 is ‘10’ #False
True is not False #True
l =[10,3]; 10 in l #True
8 not in l #True
Q.38. Finally, tell us about bitwise operators in Python
used to perform bitwise calculations on integers. The integers are first converted into binary and then operations are performed on bit by bit,
& Bitwise AND x & y | Bitwise OR x | y ~ Bitwise NOT ~x ^ Bitwise XOR x ^ y >> Bitwise right shift x>> << Bitwise left shift x<
Q.39. What data types does Python support?
Numbers Strings Lists Tuples Dictionaries
Q.40. What is a docstring?
is a documentation string that we use to explain what a construct does.
def sayhi(): """The function prints Hi""" print("Hi")
Q.41. How would you convert a string into an int in Python?
int(‘227’)
Q.42. How do you take input in Python?
a=input(‘Enter a number’)
it takes input in the form of a string.
a=int(input(‘Enter a number’))
Q.43. What is a function?
is a block of organized, reusable code that is used to perform a single, related action
def greater(a,b): if a>b: return a else: return b
greater(3,3.5)
Outcome:
3.5
Q.44. What is recursion?
is a method of programming or coding a problem, in which a function calls itself one or more times in its body.
def facto(n): if n==1: return 1 return n*facto(n-1) facto(4)
Outcome:
24
Q.45. What does the function zip() do?
returns an iterator of tuples.
list(zip((‘a’,’b’,’c’),(1,2,3))) #[(‘a’, 1), (‘b’, 2), (‘c’, 3)]
Q.46. How do you calculate the length of a string?
len(‘Ayushi Sharma’)
Outcome: 13
Q.47. Explain Python List Comprehension
is a way to declare a list in one line of code
[i for i in range(1,11,2)]
Outcome:
[1, 3, 5, 7, 9]
Q.48. How do you get all values from a Python dictionary?
4 in {‘a’:1,’b’:2,’c’:3,’d’:4}.values() #True
{‘a’:1,’b’:2,’c’:3,’d’:4}.values()
Outcome:
dict_values([1, 2, 3, 4])
Q.49. What if you want to toggle case for a Python string?
‘AyuShi’.swapcase() #’aYUsHI’
Q.50. Write code to print only upto the letter t in ‘I love Python’ horizontally
s='I love Python' i=0 while s[i]!='t': print(s[i], end=' ') i+=1
Outcome:
I love Py
Q.51. Write code to print everything in the string I love Python except the spaces.
s='I love Python' for i in s: if i==' ': continue print(i,end='')
Outcome:
IlovePython
Q.52. Now, print I love Python five times in one column
s=’I love Python’
for i in range(2):
print(s)
Q.53. What is the purpose of bytes() in Python?
s a built-in function in Python that returns an immutable bytes object
bytes([2,4,8]) #b’\x02\x04\x08’
bytes(‘world’,’utf-8’) #b’world’
Q.54. What is a control flow statement?
is the order in which the program’s code executes. The control flow of a Python program is regulated by conditional statements, loops, and function calls.
Q.55. Create a new list (using a list comprehension) to convert the following list of number strings to a list of numbers.
nums=[‘22’,’68’,’110’,’89’,’31’,’12’]
nums=[‘22’,’68’]
[int(i) for i in nums] #[22, 68]
Q.56. 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’
Q.58. What does the following code output?
def extendList(val, list=[]): list.append(val) return list list1 = extendList(10) list2 = extendList(123,[]) list3 = extendList('a') list1,list2,list3
([10, ‘a’], [123], [10, ‘a’])
You’d expect the output to be something like this:
Once we define the function, it creates a new list. Then, whenever we call it again without a list argument, it uses the same list.
Q.59. How many arguments can the range() function take?
#Output of: list(range(2,9,2))
The range() function in Python can take up to 3 arguments. Let’s see this one by one.
Output:
[2, 4, 6, 8]
Q.61. How is Python different from Java?
Java is faster than Python
Python mandates indentation. Java needs braces.
Python is dynamically-typed; Java is statically typed.
Python is simple and concise; Java is verbose
Python is interpreted
Java is platform-independent
Java has stronger database-access with JDBC
Q.62. What is the best code you can write to swap two numbers?
a,b=b,a
Q.63. How can you declare multiple assignments in one statement?
a,b,c=3,4,5
a=b=c=3
Q.64. If you are ever stuck in an infinite loop, how will you break out of it?
we press Ctrl+C
Q.65. How do we execute Python?
Python files first compile to bytecode. Then, the host executes them
Q.67. What is the with statement in Python?
ensures that cleanup code is executed when working with unmanaged resources by encapsulating common preparation and cleanup tasks
with open('data.txt') as data: #processing statements
Q.68. How is a .pyc file different from a .py file?
While both files hold bytecode, .pyc is the compiled version of a Python file.
Q.69. What makes Python object-oriented?
With this kind of programming, we have the following features:
Encapsulation Abstraction Inheritance Polymorphism Data hiding
What is polymorphism?
In Python, Polymorphism allows us to define methods in the child class with the same name as defined in their parent class.
What is Abstraction?
is the process of hiding the real implementation of an application from the user and emphasizing only on usage of it
What is Inheritance?
s the capability of one class to derive or inherit the properties from some another class. The benefits of inheritance are: … It is transitive in nature, which means that if class B inherits from another class A, then all the subclasses of B would automatically inherit from class A
what is encapsulation in python?
one of the fundamental concepts in object-oriented programming (OOP). It describes the idea of wrapping data and the methods that work on data within one unit. … A class is an example of encapsulation as it encapsulates all the data that is member functions, variables, etc
Q.70. How many types of objects does Python support?
Mutable and immutable