What are the built-in types does python provide?
Python has following built-in data types:
Numbers: Python identifies three types of numbers:
- Integer: All positive and negative numbers without a fractional part
- Float: Any real number with floating-point representation
- Complex numbers: A number with a real and imaginary component represented as x+yj. x and y are floats and j is -1(square root of -1 called an imaginary number)
Boolean: The Boolean data type is a data type that has one of two possible values i.e. True or False. Note that ‘T’ and ‘F’ are capital letters.
String: A string value is a collection of one or more characters put in single, double or triple quotes.
List: A list object is an ordered collection of one or more data items which can be of different types, put in square brackets. A list is mutable and thus can be modified, we can add, edit or delete individual elements in a list.
Set: An unordered collection of unique objects enclosed in curly brackets
Frozen set: They are like a set but immutable, which means we cannot modify their values once they are created.
Dictionary: A dictionary object is unordered in which there is a key associated with each value and we can access each value through its key. A collection of such pairs is enclosed in curly brackets. For example {‘First Name’ : ’Tom’ , ’last name’ : ’Hardy’} Note that Number values, strings, and tuple are immutable while as List or Dictionary object are mutable.
What is docstring in Python?
Python docstrings are the string literals enclosed in triple quotes that appear right after the definition of a function, method, class, or module. These are generally used to describe the functionality of a particular function, method, class, or module. We can access these docstrings using the __doc__ attribute. Here is an example:
def square(n):
'''Takes in a number n, returns the square of n'''
return n**2
print(square.__doc__)
Output: Takes in a number n, returns the square of n.
How to Reverse a String in Python?
In Python, there are no in-built functions that help us reverse a string. We need to make use of an array slicing operation for the same.
str_reverse = string[::-1]
Python Interview Question
How to check Python Version in CMD?
To check the Python Version in CMD, press CMD + Space. This opens Spotlight. Here, type “terminal” and press enter. To execute the command, type python –version or python -V and press enter. This will return the python version in the next line below the command.
Is Python case sensitive when dealing with identifiers?
Yes. Python is case sensitive when dealing with identifiers. It is a case sensitive language. Thus, variable and Variable would not be the same.
How to create a new column in pandas by using values from other columns?
We can perform column based mathematical operations on a pandas dataframe. Pandas columns containing numeric values can be operated upon by operators.
Code
import pandas as pd
a=[1,2,3]
b=[2,3,5]
d={"col1":a,"col2":b}
df=pd.DataFrame(d)
df["Sum"]=df["col1"]+df["col2"]
df["Difference"]=df["col1"]-df["col2"]
df
Output

Advance Python Interview Question
What are the different functions that can be used by grouby in pandas ?
grouby() in pandas can be used with multiple aggregate functions. Some of which are sum(),mean(), count(),std().
Data is divided into groups based on categories and then the data in these individual groups can be aggregated by the aforementioned functions.
How to select columns in pandas and add them to a new data frame? What if there are two columns with the same name?
If df is dataframe in pandas df.columns gives the list of all columns. We can then form new columns by selecting columns.
If there are two columns with the same name then both columns get copied to the new dataframe.
Code
print(d_new.columns)
d=d_new[["col1"]]
d
Output
How to delete a column or group of columns in pandas? Given the below data frame drop column “col1”.
drop() function can be used to delete the columns from a data frame.
Output

Python Interview Question
Given the following data frame drop rows having column values as A.
Code
d={"col1":[1,2,3],"col2":["A","B","C"]}
df=pd.DataFrame(d)
df.dropna(inplace=True)
df=df[df.col1!=1]
df
Output

What is reindexing in pandas?
Reindexing is the process of re-assigning the index of a pandas data frame.
Code
import pandas as pd
bikes=["bajaj","tvs","herohonda","kawasaki","bmw"]
cars=["lamborghini","masserati","ferrari","hyundai","ford"]
d={"cars":cars,"bikes":bikes}
df=pd.DataFrame(d)
a=[10,20,30,40,50]
df.index=a
df
Output

What do you understand by lambda function? Create a lambda function which will print the sum of all the elements in this list -> [5, 8, 10, 20, 50, 100]
from functools import reduce
sequences = [5, 8, 10, 20, 50, 100]
sum = reduce (lambda x, y: x+y, sequences)
print(sum)
Advance Python Interview Question
What is vstack() in numpy? Give an example
vstack() is a function to align rows vertically. All rows must have same number of elements.
Code
import numpy as np
n1=np.array([10,20,30,40,50])
n2=np.array([50,60,70,80,90])
print(np.vstack((n1,n2)))
Output

How do we interpret Python?
When a python program is written, it converts the source code written by the developer into intermediate language, which is then cover into machine language that needs to be executed.
How to remove spaces from a string in Python?
Spaces can be removed from a string in python by using strip() or replace() functions. Strip() function is used to remove the leading and trailing white spaces while the replace() function is used to remove all the white spaces in the string:
string.replace(” “,””) ex1: str1= “great learning”
print (str.strip())
o/p: great learning
ex2: str2=”great learning”
print (str.replace(” “,””))
o/p: greatlearning
Python Interview Question
Explain the file processing modes that Python supports.
There are three file processing modes in Python: read-only(r), write-only(w), read-write(rw) and append (a). So, if you are opening a text file in say, read mode. The preceding modes become “rt” for read-only, “wt” for write and so on. Similarly, a binary file can be opened by specifying “b” along with the file accessing flags (“r”, “w”, “rw” and “a”) preceding it.
What is pickling and unpickling?
Pickling is the process of converting a Python object hierarchy into a byte stream for storing it into a database. It is also known as serialization. Unpickling is the reverse of pickling. The byte stream is converted back into an object hierarchy.
How is memory managed in Python?
Memory management in python comprises of a private heap containing all objects and data stucture. The heap is managed by the interpreter and the programmer does not have acess to it at all. The Python memory manger does all the memory allocation. Moreover, there is an inbuilt garbage collector that recycles and frees memory for the heap space.
Advance Python Interview Question
What is unittest in Python?
Unittest is a unit testinf framework in Python. It supports sharing of setup and shutdown code for tests, aggregation of tests into collections,test automation, and independence of the tests from the reporting framework.
How do you delete a file in Python?
Files can be deleted in Python by using the command os.remove (filename) or os.unlink(filename)
How do you create an empty class in Python?
To create an empty class we can use the pass command after the definition of the class object. A pass is a statement in Python that does nothing.
Python Interview Question
What are Python decorators?
Decorators are functions that take another functions as argument to modify its behavior without changing the function itself. These are useful when we want to dynamically increase the functionality of a function without changing it. Here is an example :
def smart_divide(func):
def inner(a, b):
print("Dividing", a, "by", b)
if b == 0:
print("Make sure Denominator is not zero")
return
return func(a, b)
return inner
@smart_divide
def divide(a, b):
print(a/b)
divide(1,0)
Write code to perform sentiment analysis on amazon reviews:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.python.keras import models, layers, optimizers
import tensorflow
from tensorflow.keras.preprocessing.text import Tokenizer, text_to_word_sequence
from tensorflow.keras.preprocessing.sequence import pad_sequences
import bz2
from sklearn.metrics import f1_score, roc_auc_score, accuracy_score
import re
%matplotlib inline
def get_labels_and_texts(file):
labels = []
texts = []
for line in bz2.BZ2File(file):
x = line.decode(“utf-8”)
labels.append(int(x[9]) – 1)
texts.append(x[10:].strip())
return np.array(labels), texts
train_labels, train_texts = get_labels_and_texts(‘train.ft.txt.bz2’)
test_labels, test_texts = get_labels_and_texts(‘test.ft.txt.bz2’)
Train_labels[0]
Train_texts[0]
train_labels=train_labels[0:500]
train_texts=train_texts[0:500]
import re
NON_ALPHANUM = re.compile(r'[\W]’)
NON_ASCII = re.compile(r'[^a-z0-1\s]’)
def normalize_texts(texts):
normalized_texts = []
for text in texts:
lower = text.lower()
no_punctuation = NON_ALPHANUM.sub(r’ ‘, lower)
no_non_ascii = NON_ASCII.sub(r”, no_punctuation)
normalized_texts.append(no_non_ascii)
return normalized_texts
train_texts = normalize_texts(train_texts)
test_texts = normalize_texts(test_texts)
from sklearn.feature_extraction.text import CountVectorizer
cv = CountVectorizer(binary=True)
cv.fit(train_texts)
X = cv.transform(train_texts)
X_test = cv.transform(test_texts)
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
X_train, X_val, y_train, y_val = train_test_split(
X, train_labels, train_size = 0.75)
for c in [0.01, 0.05, 0.25, 0.5, 1]:
lr = LogisticRegression(C=c)
lr.fit(X_train, y_train)
print (“Accuracy for C=%s: %s”
% (c, accuracy_score(y_val, lr.predict(X_val))))
lr.predict(X_test[29])
Implement a probability plot using numpy and matplotlib:
import numpy as np
import pylab
import scipy.stats as stats
from matplotlib import pyplot as plt
n1=np.random.normal(loc=0,scale=1,size=1000)
np.percentile(n1,100)
n1=np.random.normal(loc=20,scale=3,size=100)
stats.probplot(n1,dist=”norm”,plot=pylab)
plt.show()
Advance Python Interview Question
The independent variables should be “Sepal.Width”, “Petal.Length”, “Petal.Width”, while the dependent variable should be “Sepal.Length”.
import pandas as pd
iris = pd.read_csv(“iris.csv”)
iris.head()
x = iris[[‘Sepal.Width’,’Petal.Length’,’Petal.Width’]]
y = iris[[‘Sepal.Length’]]
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.35)
from sklearn.linear_model import LinearRegression
lr = LinearRegression()
lr.fit(x_train, y_train)
y_pred = lr.predict(x_test)
from sklearn.metrics import mean_squared_error
mean_squared_error(y_test, y_pred)
Code solution:
We start off by importing the required libraries:
import pandas as pd
iris = pd.read_csv(“iris.csv”)
iris.head()
Then, we will go ahead and extract the independent variables and dependent variable:
x = iris[[‘Sepal.Width’,’Petal.Length’,’Petal.Width’]]
y = iris[[‘Sepal.Length’]]
Following which, we divide the data into train and test sets:
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.35)
Then, we go ahead and build the model:
from sklearn.linear_model import LinearRegression
lr = LinearRegression()
lr.fit(x_train, y_train)
y_pred = lr.predict(x_test)
Finally, we will find out the mean squared error:
from sklearn.metrics import mean_squared_error
mean_squared_error(y_test, y_pred)
Find the percentage of transactions which are fraudulent and not fraudulent. Also build a logistic regression model, to find out if the transaction is fraudulent or not.
nfcount=0
notFraud=data_df[‘Class’]
for i in range(len(notFraud)):
if notFraud[i]==0:
nfcount=nfcount+1
nfcount
per_nf=(nfcount/len(notFraud))*100
print(‘percentage of total not fraud transaction in the dataset: ‘,per_nf)
fcount=0
Fraud=data_df[‘Class’]
for i in range(len(Fraud)):
if Fraud[i]==1:
fcount=fcount+1
fcount
per_f=(fcount/len(Fraud))*100
print(‘percentage of total fraud transaction in the dataset: ‘,per_f)
x=data_df.drop([‘Class’], axis = 1)#drop the target variable
y=data_df[‘Class’]
xtrain, xtest, ytrain, ytest = train_test_split(x, y, test_size = 0.2, random_state = 42)
logisticreg = LogisticRegression()
logisticreg.fit(xtrain, ytrain)
y_pred = logisticreg.predict(xtest)
accuracy= logisticreg.score(xtest,ytest)
cm = metrics.confusion_matrix(ytest, y_pred)
print(cm)
Implement a simple CNN on the MNIST dataset using Keras. Following which, also add in drop out layers.
from __future__ import absolute_import, division, print_function
import numpy as np
# import keras
from tensorflow.keras.datasets import cifar10, mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation, Dropout, Flatten, Reshape
from tensorflow.keras.layers import Convolution2D, MaxPooling2D
from tensorflow.keras import utils
import pickle
from matplotlib import pyplot as plt
import seaborn as sns
plt.rcParams[‘figure.figsize’] = (15, 8)
%matplotlib inline
# Load/Prep the Data
(x_train, y_train_num), (x_test, y_test_num) = mnist.load_data()
x_train = x_train.reshape(x_train.shape[0], 28, 28, 1).astype(‘float32’)
x_test = x_test.reshape(x_test.shape[0], 28, 28, 1).astype(‘float32’)
x_train /= 255
x_test /= 255
y_train = utils.to_categorical(y_train_num, 10)
y_test = utils.to_categorical(y_test_num, 10)
print(‘— THE DATA —‘)
print(‘x_train shape:’, x_train.shape)
print(x_train.shape[0], ‘train samples’)
print(x_test.shape[0], ‘test samples’)
TRAIN = False
BATCH_SIZE = 32
EPOCHS = 1
# Define the Type of Model
model1 = tf.keras.Sequential()
# Flatten Imgaes to Vector
model1.add(Reshape((784,), input_shape=(28, 28, 1)))
# Layer 1
model1.add(Dense(128, kernel_initializer=’he_normal’, use_bias=True))
model1.add(Activation(“relu”))
# Layer 2
model1.add(Dense(10, kernel_initializer=’he_normal’, use_bias=True))
model1.add(Activation(“softmax”))
# Loss and Optimizer
model1.compile(loss=’categorical_crossentropy’, optimizer=’adam’, metrics=[‘accuracy’])
# Store Training Results
early_stopping = keras.callbacks.EarlyStopping(monitor=’val_acc’, patience=10, verbose=1, mode=’auto’)
callback_list = [early_stopping]# [stats, early_stopping]
# Train the model
model1.fit(x_train, y_train, nb_epoch=EPOCHS, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=callback_list, verbose=True)
#drop-out layers:
# Define Model
model3 = tf.keras.Sequential()
# 1st Conv Layer
model3.add(Convolution2D(32, (3, 3), input_shape=(28, 28, 1)))
model3.add(Activation(‘relu’))
# 2nd Conv Layer
model3.add(Convolution2D(32, (3, 3)))
model3.add(Activation(‘relu’))
# Max Pooling
model3.add(MaxPooling2D(pool_size=(2,2)))
# Dropout
model3.add(Dropout(0.25))
# Fully Connected Layer
model3.add(Flatten())
model3.add(Dense(128))
model3.add(Activation(‘relu’))
# More Dropout
model3.add(Dropout(0.5))
# Prediction Layer
model3.add(Dense(10))
model3.add(Activation(‘softmax’))
# Loss and Optimizer
model3.compile(loss=’categorical_crossentropy’, optimizer=’adam’, metrics=[‘accuracy’])
# Store Training Results
early_stopping = tf.keras.callbacks.EarlyStopping(monitor=’val_acc’, patience=7, verbose=1, mode=’auto’)
callback_list = [early_stopping]
# Train the model
model3.fit(x_train, y_train, batch_size=BATCH_SIZE, nb_epoch=EPOCHS,
Python Interview Question
Implement the naive bayes algorithm on top of the diabetes dataset:
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import matplotlib.pyplot as plt # matplotlib.pyplot plots data
%matplotlib inline
import seaborn as sns
pdata = pd.read_csv(“pima-indians-diabetes.csv”)
columns = list(pdata)[0:-1] # Excluding Outcome column which has only
pdata[columns].hist(stacked=False, bins=100, figsize=(12,30), layout=(14,2));
# Histogram of first 8 columns
# However we want to see correlation in graphical representation so below is function for that
def plot_corr(df, size=11):
corr = df.corr()
fig, ax = plt.subplots(figsize=(size, size))
ax.matshow(corr)
plt.xticks(range(len(corr.columns)), corr.columns)
plt.yticks(range(len(corr.columns)), corr.columns)
plot_corr(pdata)
from sklearn.model_selection import train_test_split
X = pdata.drop(‘class’,axis=1) # Predictor feature columns (8 X m)
Y = pdata[‘class’] # Predicted class (1=True, 0=False) (1 X m)
x_train, x_test, y_train, y_test = train_test_split(X, Y, test_size=0.3, random_state=1)
# 1 is just any random seed number
x_train.head()
from sklearn.naive_bayes import GaussianNB # using Gaussian algorithm from Naive Bayes
# creatw the model
diab_model = GaussianNB()
diab_model.fit(x_train, y_train.ravel())
diab_train_predict = diab_model.predict(x_train)
from sklearn import metrics
print(“Model Accuracy: {0:.4f}”.format(metrics.accuracy_score(y_train, diab_train_predict)))
print()
diab_test_predict = diab_model.predict(x_test)
from sklearn import metrics
print(“Model Accuracy: {0:.4f}”.format(metrics.accuracy_score(y_test, diab_test_predict)))
print()
print(“Confusion Matrix”)
cm=metrics.confusion_matrix(y_test, diab_test_predict, labels=[1, 0])
df_cm = pd.DataFrame(cm, index = [i for i in [“1″,”0”]],
columns = [i for i in [“Predict 1″,”Predict 0”]])
plt.figure(figsize = (7,5))
sns.heatmap(df_cm, annot=True)
What do you understand by object oriented programming in Python?
Object oriented programming refers to the process of solving a problem by creating objects. This approach takes into account two key factors of an object- attributes and behavior.
How are classes created in Python? Give an example
class Node(object):
def __init__(self):
self.x=0
self.y=0
Here Node is a class
Advance Python Interview Question
What is inheritance in Object oriented programming? Give an example of multiple inheritance.
Inheritance is one of the core concepts of object-oriented programming. It is a process of deriving a class from a different class and form a hierarchy of classes that share the same attributes and methods. It is generally used for deriving different kinds of exceptions, create custom logic for existing frameworks and even map domain models for database.
Example
class Node(object):
def __init__(self):
self.x=0
self.y=0
Here class Node inherits from the object class.
What is multi-level inheritance? Give an example for multi-level inheritance?
If class A inherits from B and C inherits from A it’s called multilevel inheritance.
class B(object):
def __init__(self):
self.b=0
class A(B):
def __init__(self):
self.a=0
class C(A):
def __init__(self):
self.c=0
How can you find the minimum and maximum values present in a tuple?
Solution ->
We can use the min() function on top of the tuple to find out the minimum value present in the tuple:
tup1=(1,2,3,4,5)
min(tup1)
Output
1
We see that the minimum value present in the tuple is 1.
Analogous to the min() function is the max() function, which will help us to find out the maximum value present in the tuple:
tup1=(1,2,3,4,5)
max(tup1)
Output
5
We see that the maximum value present in the tuple is 5
Python Interview Question
If you have a list like this -> [1,”a”,2,”b”,3,”c”]. How can you access the 2nd, 4th and 5th elements from this list?
Solution ->
We will start off by creating a tuple which will comprise of the indices of elements which we want to access:
Then, we will use a for loop to go through the index values and print them out:
Below is the entire code for the process:
indices = (1,3,4)
for i in indices:
print(a[i])
If you have a list like this -> [“sparta”,True,3+4j,False]. How would you reverse the elements of this list?
Solution ->
We can use the reverse() function on the list:
a.reverse()
a
If you have dictionary like this – > fruit={“Apple”:10,”Orange”:20,”Banana”:30,”Guava”:40}. How would you update the value of ‘Apple’ from 10 to 100?
Solution ->
This is how you can do it:
fruit["Apple"]=100
fruit
Give in the name of the key inside the parenthesis and assign it a new value.
Advance Python Interview Question
If you have two sets like this -> s1 = {1,2,3,4,5,6}, s2 = {5,6,7,8,9}. How would you find the common elements in these sets.
Solution ->
You can use the intersection() function to find the common elements between the two sets:
s1 = {1,2,3,4,5,6}
s2 = {5,6,7,8,9}
s1.intersection(s2)
We see that the common elements between the two sets are 5 & 6.
Write a program to print out the 2-table using while loop.
Solution ->
Below is the code to print out the 2-table:
Code
i=1
n=2
while i<=10:
print(n,"*", i, "=", n*i)
i=i+1
Output
We start off by initializing two variables ‘i’ and ‘n’. ‘i’ is initialized to 1 and ‘n’ is initialized to ‘2’.
Inside the while loop, since the ‘i’ value goes from 1 to 10, the loop iterates 10 times.
Initially n*i is equal to 2*1, and we print out the value.
Then, ‘i’ value is incremented and n*i becomes 2*2. We go ahead and print it out.
This process goes on until i value becomes 10.
Write a function, which will take in a value and print out if it is even or odd.
Solution ->
The below code will do the job:
def even_odd(x):
if x%2==0:
print(x," is even")
else:
print(x, " is odd")
Here, we start off by creating a method, with the name ‘even_odd()’. This function takes a single parameter and prints out if the number taken is even or odd.
Now, let’s invoke the function:
even_odd(5)
We see that, when 5 is passed as a parameter into the function, we get the output -> ‘5 is odd’.
Python Interview Question
Write a python program to print the factorial of a number.
Solution ->
Below is the code to print the factorial of a number:
factorial = 1
#check if the number is negative, positive or zero
if num<0:
print("Sorry, factorial does not exist for negative numbers")
elif num==0:
print("The factorial of 0 is 1")
else
for i in range(1,num+1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
We start off by taking an input which is stored in ‘num’. Then, we check if ‘num’ is less than zero and if it is actually less than 0, we print out ‘Sorry, factorial does not exist for negative numbers’.
After that, we check,if ‘num’ is equal to zero, and it that’s the case, we print out ‘The factorial of 0 is 1’.
On the other hand, if ‘num’ is greater than 1, we enter the for loop and calculate the factorial of the number.
Write a python program to check if the number given is a palindrome or not
Solution ->
Below is the code to Check whether the given number is palindrome or not:
n=int(input("Enter number:"))
temp=n
rev=0
while(n>0)
dig=n%10
rev=rev*10+dig
n=n//10
if(temp==rev):
print("The number is a palindrome!")
else:
print("The number isn't a palindrome!")
We will start off by taking an input and store it in ‘n’ and make a duplicate of it in ‘temp’. We will also initialize another variable ‘rev’ to 0.
Then, we will enter a while loop which will go on until ‘n’ becomes 0.
Inside the loop, we will start off by dividing ‘n’ with 10 and then store the remainder in ‘dig’.
Then, we will multiply ‘rev’ with 10 and then add ‘dig’ to it. This result will be stored back in ‘rev’.
Going ahead, we will divide ‘n’ by 10 and store the result back in ‘n’
Once the for loop ends, we will compare the values of ‘rev’ and ‘temp’. If they are equal, we will print ‘The number is a palindrome’, else we will print ‘The number isn’t a palindrome’.
Write a python program to print the following pattern ->
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
Solution ->
Below is the code to print this pattern:
#10 is the total number to print
for num in range(6):
for i in range(num):
print(num,end=" ")#print number
#new line after each row to display pattern correctly
print("\n")
We are solving the problem with the help of nested for loop. We will have an outer for loop, which goes from 1 to 5. Then, we have an inner for loop, which would print the respective numbers.
Advance Python Interview Question
Pattern questions. Print the following pattern
#
# #
# # #
# # # #
# # # # #
def pattern_1(num):
# outer loop handles the number of rows
# inner loop handles the number of columns
# n is the number of rows.
for i in range(0, n):
# value of j depends on i
for j in range(0, i+1):
# printing hashes
print("#",end="")
# ending line after each row
print("\r")
num = int(input("Enter the number of rows in pattern: "))
pattern_1(num)
Print the following pattern
#
# #
# # #
# # # #
# # # # #
Code:
def pattern_2(num):
# define the number of spaces
k = 2*num - 2
# outer loop always handles the number of rows
# let us use the inner loop to control the number of spaces
# we need the number of spaces as maximum initially and then decrement it after every iteration
for i in range(0, num):
for j in range(0, k):
print(end=" ")
# decrementing k after each loop
k = k - 2
# reinitializing the inner loop to keep a track of the number of columns
# similar to pattern_1 function
for j in range(0, i+1):
print("# ", end="")
# ending line after each row
print("\r")
num = int(input("Enter the number of rows in pattern: "))
pattern_2(num)
Print the following pattern:
0
0 1
0 1 2
0 1 2 3
0 1 2 3 4
Code:
def pattern_3(num):
# initialising starting number
number = 1
# outer loop always handles the number of rows
# let us use the inner loop to control the number
for i in range(0, num):
# re assigning number after every iteration
# ensure the column starts from 0
number = 0
# inner loop to handle number of columns
for j in range(0, i+1):
# printing number
print(number, end=" ")
# increment number column wise
number = number + 1
# ending line after each row
print("\r")
num = int(input("Enter the number of rows in pattern: "))
pattern_3(num)
Python Interview Question
Print the following pattern:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Code:
def pattern_4(num):
# initialising starting number
number = 1
# outer loop always handles the number of rows
# let us use the inner loop to control the number
for i in range(0, num):
# commenting the reinitialization part ensure that numbers are printed continuously
# ensure the column starts from 0
number = 0
# inner loop to handle number of columns
for j in range(0, i+1):
# printing number
print(number, end=" ")
# increment number column wise
number = number + 1
# ending line after each row
print("\r")
num = int(input("Enter the number of rows in pattern: "))
pattern_4(num)
Print the following pattern:
A
B B
C C C
D D D D
def pattern_5(num):
# initializing value of A as 65
# ASCII value equivalent
number = 65
# outer loop always handles the number of rows
for i in range(0, num):
# inner loop handles the number of columns
for j in range(0, i+1):
# finding the ascii equivalent of the number
char = chr(number)
# printing char value
print(char, end=" ")
# incrementing number
number = number + 1
# ending line after each row
print("\r")
num = int(input("Enter the number of rows in pattern: "))
pattern_5(num)
Print the following pattern:
A
B C
D E F
G H I J
K L M N O
P Q R S T U
def pattern_6(num):
# initializing value equivalent to 'A' in ASCII
# ASCII value
number = 65
# outer loop always handles the number of rows
for i in range(0, num):
# inner loop to handle number of columns
# values changing acc. to outer loop
for j in range(0, i+1):
# explicit conversion of int to char
# returns character equivalent to ASCII.
char = chr(number)
# printing char value
print(char, end=" ")
# printing the next character by incrementing
number = number +1
# ending line after each row
print("\r")
num = int(input("enter the number of rows in the pattern: "))
pattern_6(num)
Advance Python Interview Question
Given the below data frames form a single data frame by vertical stacking.
We use the pd.concat and axis as 0 to stack them horizontally
Code
import pandas as pd
d={"col1":[1,2,3],"col2":['A','B','C']}
df1=pd.DataFrame(d)
d={"col1":[4,5,6],"col2":['D','E','F']}
df2=pd.DataFrame(d)
d_new=pd.comcat([df1,df2],axis=0)
d_new
Given the below data frames stack them horizontally to form a single data frame.
We use the pd.concat and axis as 0 to stack them horizontally.
Code
import pandas as pd
d={"col1":[1,2,3],"col2":['A','B','C']}
df1=pd.DataFrame(d)
d={"col1":[4,5,6],"col2":['D','E','F']}
df2=pd.DataFrame(d)
d_new=pd.comcat([df1,df2],axis=1)
d_new