<jupyter_start><jupyter_text>All the IPython Notebooks in **Data Science Interview Questions** series by Dr. <NAME> are available @ **[GitHub](https://github.com/milaan9/DataScience_Interview_Questions)**  Python Basics ➞ 120 Questions  1. What is Python?Solution- 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. Name some of the features of Python.SolutionFollowing are some of the salient features of python −* It supports functional and structured programming methods as well as OOP.* It can be used as a scripting language or can be compiled to byte-code for building large applications.* It provides very high-level dynamic data types and supports dynamic type checking.* It supports automatic garbage collection.* It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.  3. What is the purpose of PYTHONPATH environment variable?Solution- 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.  4. What is the purpose of PYTHONSTARTUP environment variable?Solution- 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.  5. What is the purpose of PYTHONCASEOK environment variable?Solution- 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.  6.  What is the purpose of PYTHONHOME environment variable?Solution- PYTHONHOME − It is an alternative module search path. It is usually embedded in the PYTHONSTARTUP or PYTHONPATH directories to make switching module libraries easy.  7. Is python a case sensitive language?Solution- Yes! Python is a case sensitive programming language.  8. What are the supported data types in Python?Solution- Python has five standard data types:    1. Numbers    2. String    3. List    4. Tuple    5. Dictionary  9. What is the output of print `str` if `str = 'Hello World!'`?Solution- It will print complete string. - Output would be `Hello World!`  10. What is the output of print `str[0]` if `str = 'Hello World!'`?Solution- It will print first character of the string. Output would be H.  11. What is the output of print `str[2:5]` if `str = 'Hello World!'`?Solution- It will print characters starting from 3rd to 5th. - Output would be `llo`  12. What is the output of print `str[2:]` if `str = 'Hello World!'`?Solution- It will print characters starting from 3rd character. - Output would be `llo World!`  13. What is the output of print `str * 2` if `str = 'Hello World!'`?Solution- It will print string two times. - Output would be `Hello World!Hello World!`  14. What is the output of print `str + "TEST"` if `str = 'Hello World!'`?Solution- It will print concatenated string. - Output would be `Hello World!TEST`  15. What is the output of print `list` if `list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]`?Solution- It will print complete list. - Output would be `['abcd', 786, 2.23, 'john', 70.200000000000003]`  16. What is the output of print `list[0]` if `list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]`?Solution- It will print first element of the list. - Output would be `abcd`  17.  What is the output of print `list[1:3]` if `list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]`?Solution- It will print elements starting from 2nd till 3rd. - Output would be `[786, 2.23]`  18. What is the output of print `list[2:]` if `list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]`?Solution- It will print elements starting from 3rd element. - Output would be `[2.23, 'john', 70.200000000000003]`  19. What is the output of print `tinylist * 2` if `tinylist = [123, 'john']`?Solution- It will print list two times. - Output would be `[123, 'john', 123, 'john']`  20. What is the output of print `list1 + list2`, if `list1 = [ 'abcd', 786 , 2.23, 'john', 70.2 ] and ist2 = [123, 'john']`?Solution- It will print concatenated lists. - Output would be `['abcd', 786, 2.23, 'john', 70.2, 123, 'john']`  21. What are tuples in Python?Solution- 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.  22. What is the difference between tuples and lists in Python?Solution- 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.  23. What is the output of print `tuple` if `tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )`?Solution- It will print complete tuple. - Output would be `('abcd', 786, 2.23, 'john', 70.200000000000003)`  24. What is the output of print `tuple[0]` if `tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )`?Solution- It will print first element of the tuple. - Output would be `abcd`  25. What is the output of print `tuple[1:3]` if `tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )`?Solution- It will print elements starting from 2nd till 3rd. - Output would be `(786, 2.23)`  26. What is the output of print `tuple[2:]` if `tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )`?Solution- It will print elements starting from 3rd element. - Output would be `(2.23, 'john', 70.200000000000003)`  27. What is the output of print `tinytuple * 2` if `tinytuple = (123, 'john')`?Solution- It will print tuple two times. - Output would be `(123, 'john', 123, 'john')`  28. What is the output of print `tuple + tinytuple` if `tuple = ( 'abcd', 786, 2.23, 'john', 70.2 )` and `tinytuple = (123, 'john')`?Solution- It will print concatenated tuples. - Output would be `('abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john')`  29. What are Python's dictionaries?Solution- 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.  30. How will you create a dictionary in python?Solution- Dictionaries are enclosed by curly braces `{ }` and values can be assigned and accessed using square braces `[]`.```pythondict = {}dict['one'] = "This is one"dict[2]     = "This is two"tinydict = {'name': 'john','code':6734, 'dept': 'sales'}```  31. How will you get all the keys from the dictionary?Solution- Using `dictionary.keys()` function, we can get all the keys from the dictionary object.```pythonprint dict.keys()    Prints all the keys```  32. How will you get all the values from the dictionary?Solution- Using `dictionary.values()` function, we can get all the values from the dictionary object.```pythonprint dict.values()    Prints all the values```  33. How will you convert a string to an int in python?Solution- `int(x [,base])` - Converts `x` to an integer. `base` specifies the base if `x` is a string.  34. How will you convert a string to a long in python?Solution- `long(x [,base] )` - Converts `x` to a long integer. `base` specifies the base if `x` is a string.  35. How will you convert a string to a float in python?Solution- `float(x)` − Converts `x` to a floating-point number.  36. How will you convert a object to a string in python?Solution- `str(x)` − Converts object `x` to a string representation.  37. How will you convert a object to a regular expression in python?Solution- `repr(x)` − Converts object `x` to an expression string.  38. How will you convert a String to an object in python?Solution- `eval(str)` − Evaluates a string and returns an object.  39. How will you convert a string to a tuple in python?Solution- `tuple(s)` − Converts `s` to a tuple.  40. How will you convert a string to a list in python?Solution- `list(s)` − Converts `s` to a list.  41. How will you convert a string to a set in python?Solution- `set(s)` − Converts `s` to a set.  42. How will you create a dictionary using tuples in python?Solution- `dict(d)` − Creates a dictionary. `d` must be a sequence of (key,value) tuples.  43. How will you convert a string to a frozen set in python?Solution- `frozenset(s)` − Converts `s` to a frozen set.  44. How will you convert an integer to a character in python?Solution- `chr(x)` − Converts an integer to a character.  45. How will you convert an integer to an unicode character in python?Solution- `unichr(x)` − Converts an integer to a Unicode character.  46. How will you convert a single character to its integer value in python?Solution- `ord(x)` − Converts a single character to its integer value.  47. How will you convert an integer to hexadecimal string in python?Solution- `hex(x)` − Converts an integer to a hexadecimal string.  48. How will you convert an integer to octal string in python?Solution- `oct(x)` − Converts an integer to an octal string.  49. What is the purpose of `**` operator?Solution- `**` Exponent − Performs exponential (power) calculation on operators. - `a**b` = 10 to the power 20 if `a = 10` and `b = 20`  50. What is the purpose of `//` operator?Solution- `//` Floor Division − The division of operands where the result is the quotient in which the digits after the decimal point are removed.  51. What is the purpose of `is` operator?Solution- `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)`.  52. What is the purpose of `not in` operator?Solution- `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`.  53. What is the purpose `break` statement in python?Solution- `break` statement − Terminates the loop statement and transfers execution to the statement immediately following the loop.  54. What is the purpose `continue` statement in python?Solution- `continue` statement − Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.  55. What is the purpose `pass` statement in python?Solution- `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.  56. How can you pick a random item from a list or tuple?Solution- `choice(seq)` − Returns a random item from a list, tuple, or string.  57. How can you pick a random item from a range?Solution-  `randrange ([start,] stop [,step])` − returns a randomly selected element from range(start, stop, step).  58. How can you get a random number in python?Solution- `random()` − returns a random float `r`, such that 0 is less than or equal to `r` and `r` is less than 1.  59. How will you set the starting value in generating random numbers?Solution- `seed([x])` − Sets the integer starting value used in generating random numbers. Call this function before calling any other random module function. Returns `None`.  60. How will you randomizes the items of a list in place?Solution- `shuffle(lst)` − Randomizes the items of a list in place. Returns `None`.  61. How will you capitalizes first letter of string?Solution- `capitalize()` − Capitalizes first letter of string.  62. How will you check in a string that all characters are alphanumeric?Solution- `isalnum()` − Returns `True` if string has at least 1 character and all characters are alphanumeric and `False` otherwise.  63. How will you check in a string that all characters are digits?Solution- `isdigit()` − Returns `True` if string contains only digits and `False` otherwise.  64. How will you check in a string that all characters are in lowercase?Solution- `islower()` − Returns `True` if string has at least 1 cased character and all cased characters are in lowercase and `False` otherwise.  65. How will you check in a string that all characters are numerics?Solution- `isnumeric()` − Returns `True` if a unicode string contains only numeric characters and `False` otherwise.  66. How will you check in a string that all characters are whitespaces?Solution- `isspace()` − Returns `True` if string contains only whitespace characters and `False` otherwise.  67. How will you check in a string that it is properly titlecased?Solution- `istitle()` − Returns `True` if string is properly "titlecased" and `False` otherwise.  68. How will you check in a string that all characters are in uppercase?Solution- `isupper()` − Returns `True` if string has at least one cased character and all cased characters are in uppercase and `False` otherwise.  69. How will you merge elements in a sequence?Solution- `join(seq)` − Merges (concatenates) the string representations of elements in sequence `seq` into a string, with separator string.  70. How will you get the length of the string?Solution- `len(string)` − Returns the length of the string.  71. How will you get a space-padded string with the original string left-justified to a total of width columns?Solution- `ljust(width[, fillchar])` − Returns a space-padded string with the original string left-justified to a total of width columns.  72. How will you convert a string to all lowercase?Solution- `lower()` − Converts all uppercase letters in string to lowercase.  73. How will you remove all leading whitespace in string?Solution- `lstrip()` − Removes all leading whitespace in string.  74. How will you get the max alphabetical character from the string?Solution- `max(str)` − Returns the `max` alphabetical character from the string `str`.  75. How will you get the min alphabetical character from the string?Solution- ``min(str)` − Returns the `min` alphabetical character from the string `str`.  76. How will you replaces all occurrences of old substring in string with new string?Solution- `replace(old, new [, max])` − Replaces all occurrences of old in string with new or at most max occurrences if `max` given.  77. How will you remove all leading and trailing whitespace in string?Solution- `strip([chars])` − Performs both `lstrip()` and `rstrip()` on string.  78. How will you change case for all letters in string?Solution- `swapcase()` − Inverts case for all letters in string.  79. How will you get titlecased version of string?Solution- `title()` − Returns "titlecased" version of string, that is, all words begin with uppercase and the rest are lowercase.  80. How will you convert a string to all uppercase?Solution- `upper()` − Converts all lowercase letters in string to uppercase.  81. How will you check in a string that all characters are decimal?Solution- `isdecimal()` − Returns `True` if a unicode string contains only decimal characters and `False` otherwise.  82. What is the difference between `del()` and `remove()` methods of list?Solution- 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.  83. What is the output of `len([1, 2, 3])`?Solution- `3`  84. What is the output of `[1, 2, 3] + [4, 5, 6]`?Solution- `[1, 2, 3, 4, 5, 6]`  85. What is the output of `['Hi!'] * 4`?Solution- `['Hi!', 'Hi!', 'Hi!', 'Hi!']`  86. What is the output of 3 in `[1, 2, 3]`?Solution- `True`  87. What is the output of for `x in [1, 2, 3]: print x`?Solution```python123```  88. What is the output of `L[2]` if `L = [1,2,3]`?Solution- `3`, Offsets start at zero.  89. What is the output of `L[-2]` if `L = [1,2,3]`?Solution- `1`, Negative: count from the right.  90. What is the output of `L[1:]` if `L = [1,2,3]`?Solution- `2, 3`, Slicing fetches sections.  91. How will you compare two lists?Solution- `cmp(list1, list2)` − Compares elements of both lists.  92. How will you get the length of a list?Solution- `len(list)` − Gives the total length of the list.  93. How will you get the max valued item of a list?Solution- `max(list)` − Returns item from the list with max value.  94. How will you get the min valued item of a list?Solution- `min(list)` − Returns item from the list with min value.  95. How will you get the index of an object in a list?Solution- `list.index(obj)` − Returns the lowest index in list that `obj` appears.  96. How will you insert an object at given index in a list?Solution- `list.insert(index, obj)` − Inserts object `obj` into list at offset index.  97. How will you remove last object from a list?Solution`list.pop(obj=list[-1])` − Removes and returns last object or obj from list.  98. How will you remove an object from a list?Solution- `list.remove(obj)` − Removes object `obj` from list.  99. How will you reverse a list?Solution- `list.reverse()` − Reverses objects of list in place.  100. How will you sort a list?Solution- `list.sort([func])` − Sorts objects of list, use compare `func` if given.  101. What is lambda function in python?Solution- `‘lambda’` is a keyword in python which creates an anonymous function. Lambda does not contain block of statements. It does not contain return statements.  102. What we call a function which is incomplete version of a function?Solution- `Stub`.  103. When a function is defined then the system stores parameters and local variables in an area of memory. What this memory is known as?Solution- `Stack`.  104. A canvas can have a foreground color? (Yes/No)Solution- `Yes`.  105. Is Python platform independent?Solution- No. There are some modules and functions in python that can only run on certain platforms.  106. Do you think Python has a complier?Solution- Yes. Python complier which works automatically so we don’t notice the compiler of python.  107. What are the applications of Python?Solution1. Django (Web framework of Python).2. Micro Frame work such as Flask and Bottle.3. Plone and Django CMS for advanced content Management.  108. What is the basic difference between Python ver 2 and Python ver 3?Solution- Table below explains the difference between Python version 2 and Python version 3.| S.No | Section | Python Version 2 | Python Version 3 | |:-------|:---------------| :------ |:--------|| 1. | Print Function | Print command can be used without parentheses. | Python 3 needs parentheses to print any string. It will raise error without parentheses. | | 2. | Unicode | ASCII str() types and separate Unicode() but there is no byte type code in Python 2. | Unicode (utf-8) and it has two byte classes − Byte, Bytearray S. || 3. | Exceptions | Python 2 accepts both new and old notations of syntax. | Python 3 raises a SyntaxError in turn when we don’t enclose the exception argument in parentheses. || 4. | Comparing Unorderable | It does not raise any error. | It raises ‘TypeError’ as warning if we try to compare unorderable types. |  109. Which programming Language is an implementation of Python programming language designed to run on Java Platform?Solution- `Jython`. (Jython is successor of Jpython.)  110. Is there any double data type in Python?Solution- `No`.  111. Is String in Python are immutable? (Yes/No)Solution- `Yes`.  112. Can `True = False` be possible in Python?Solution- `No`.  113. Which module of python is used to apply the methods related to OS.?Solution- `OS`.  114. When does a new block begin in python?Solution- A block begins when the line is intended by 4 spaces.  115. Write a function in python which detects whether the given two strings are anagrams or not.Solution<jupyter_code>def check(a,b):
    if(len(a)!=len(b)):
        return False
    else:
        if(sorted(list(a)) == sorted(list(b))):
            return True
        else:
            return False<jupyter_output><empty_output><jupyter_text>116. Name the python Library used for Machine learning.Solution- Scikit-learn python Library used for Machine learning  117. What does `pass` operation do?Solution- `pass` indicates that nothing is to be done i.e., it signifies a no operation.  118. Name the tools which python uses to find bugs (if any).Solution- `Pylint` and `pychecker`.  119. Write a function to give the sum of all the numbers in list?SolutionSample list − (100, 200, 300, 400, 0, 500)Expected output − 1500<jupyter_code># Program for sum of all the numbers in list is −

def sum(numbers):
    total = 0
    for num in numbers:
        total+=num
    print("Sum of the numbers: ", total)
sum((100, 200, 300, 400, 0, 500))

# We define a function ‘sum’ with numbers as parameter. 
#The in for loop we store the sum of all the values of list.<jupyter_output>Sum of the numbers:  1500<jupyter_text>120. Write a program in Python to reverse a string without using inbuilt function reverse string?Solution<jupyter_code># Reverse a string without using reverse() function

def string_reverse(string):
    i = len(string) - 1
    print ("The length of string is: ", len(string))
    sNew = ''
    while  i >= 0:
        sNew = sNew + str(string[i])
        i = i -1
    return sNew
print(string_reverse("1tniop"))

# First we declare a variable to store the reverse string. 
# Then using while loop and indexing of string (index is calculated by string length) 
# we reverse the string. While loop starts when index is greater than zero. 
# Index is reduced to value 1 each time. When index reaches zero we obtain the reverse of string.<jupyter_output>The length of string is:  6
point1<jupyter_text>121. Write a program to test whether the number is in the defined range or not?Solution<jupyter_code># Program is −

def test_range(num):
    if num in range(0, 101):
        print("%s is in range"%str(num))
    else:
        print("%s is not in range"%str(num))
#        print("The number is outside the given range.")
        
test_range(99)

# To test any number in a particular range we make use of the method ‘if..in’ and else condition.<jupyter_output>99 is in range<jupyter_text>122. Write a program to calculate number of upper case letters and number of lower case letters?SolutionTest on String: 'The quick Brown Fox'<jupyter_code># Program is −

def string_test(s):
    d={"UPPER_CASE":0, "LOWER_CASE":0}
    for c in s:
        if c.isupper():
            d["UPPER_CASE"]+=1
        elif c.islower():
            d["LOWER_CASE"]+=1
        else:
            pass
    print ("String in testing is: ", s)
    print ("Number of Lower Case characters in String: ", d["UPPER_CASE"])
    print ("Number of Upper Case characters in String: ", d["LOWER_CASE"])

string_test('The quick Brown Fox')

# We make use of the methods .isupper() and .islower(). We initialise the count for lower and upper. 
# Using if and else condition we calculate total number of lower and upper case characters.<jupyter_output>String in testing is:  The quick Brown Fox
Number of Lower Case characters in String:  3
Number of Upper Case characters in String:  13
StarcoderdataJupyterStructuredCleanDedup