# python coding interview questions and answers for testers ### Python coding Interview Questions and Answers for Testers

#### Below is the list of most frequently asked python coding interview questions and answers for testers, this will be helpful for your next interview.

In order to solve complex algorithms in your automation code, you have to be familiar with the basic python coding logic and syntax. While preparing for the interview, revising the basic coding question is always helpful, we have accumulated the most frequently asked python coding interview questions and answers for testers, and below is the list.

##### 1- How to swap two numbers?

Method 1- By using a temporary variable, temp

Logic- Take a temporary variable temp, assign the value of num1 in temp, then store the value of num2 in num1 now finally assign the value of temp in num2.

`num1= input("Enter num1 value:")num2= input("Enter num2 value:")print("Value of num1 before swapping: ",num1)print("Value of num2 before swapping: ",num2)temp=num1num1=num2num2=tempprint("Value of num1 after swapping: ",num1)print("Value of num2 after swapping: ",num2)`

Method 2- Without using a temporary variable, simply using the shortcut,

`num1.num2=num2,num1num1= input("Enter num1 value:")num2= input("Enter num2 value:")print("Value of num1 before swapping: ",num1)print("Value of num2 before swapping: ",num2)num1,num2=num2,num1print("Value of num1 after swapping: ",num1)print("Value of num2 after swapping: ",num2)`
##### 2- How to check number is prime or not?

Numbers that are divisible only by themselves and 1 are called the prime number and it is always greater than 1. Example , 2, 3, 5, 7, 11, 19.

`num= 5count=0if num>1:    for i in range(1,num+1):        if(num%i)==0:            count=count+1    if count==2:        print("Number is prime")    else:        print("Number is not prime")`
##### 3- How to find the factorial of a number?

Factorial of a number is the product of all the integers from 1 to that number. For example, the factorial of 7 is 1*2*3*4*5*6*7 = 5040

Logic- We can just use the looping statement, we will iterate the loop multiple times to get the values, and ten finally multiplying all the values to get the factorial.

`factorial=1num=5if num<0:    print("Factorial doesnot exist for negative number")elif num==0:    print("Factorial 0 is 1")else:    for i in range (1,num+1):        factorial=factorial * i    print("Factorial of ", num, "is ",factorial)`
##### 4- How to print the Fibonacci series?

Fibonacci Sequence is the series of numbers, where each number in the series is the sum of two preceding numbers.

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ..

`n1=0n2=1print(n1)print(n2)for i in range(2,10):    sum=n1+n2    print(sum)    n1=n2    n2=sum`
##### 5- How to find sum of element in an array?

input: arr[] = {1, 2, 3} = 1+2+3

Output: 6

`arr=[1,2,3,4,5]print (sum(arr))`
##### 6- How to find maximum and minimum element in array?

input: arr[] = {1,2,3,4,5}

Output: 5

Output: 1

`arr=[1,2,3,4,5]max=arrn= len(arr)for i in range(1,n):    if arr[i]>max:        max=arr[i]print("Maximum Element ",max)arr=[1,2,3,4,5]min=arrn= len(arr)for i in range(1,n):    if arr[i]<min:        min=arr[i]print("Minimum Element ",min)`
##### 7- How to find the length of a list?

Input: [10,20,30,40,50]

Output: 5

`mylist=[10,20,30,40,50]print(mylist)`

count=0
for i in mylist:
count=count+1
print(“Length of list is “, count)

##### 8- How to swap first & last elements of a list

Input: [1,2,3]

Output: [3,2,1]

`mylist=[11,2,3,4,15]size=len(mylist)temp= mylistmylist=mylist[size-1]mylist[size-1]=tempprint("List after swapping ",mylist)`
##### 9- How to remove the nth occurrence of the word from a list?

input: list= [“geeks”, “for”, “geeks”]

word = geeks, N=2

Output: list= [“geeks”, “for”]

My requirement is to remove the word “geeks” whenever it appears for the second time.

`mylist= ["geeks", "for", "geeks"]word="geeks"n=2count=0for i in range(0,len(mylist)):    if(mylist[i])==word:        count=count+1        if(count==n):           del mylist[i]print("Updated List", mylist)`
##### 10- How To Search an Element in a List

mylist: [1,6,3,5,3,4]

element= 4

Output: Element Found

element= 100

`mylist=[1,6,3,5,3,4]ele=4flag=0for i in mylist:    if(i==ele):        print("Element Found")        flag= 1        breakif(flag==0):    print("Element Not Found")`
##### 11- How to clear a List?

Input: mylist = [1,6,3,4,2,9]

Output: mylist = []

Method 1: Using clear() method

`mylist= [6,0,4,1]print ("My List before clear:",mylist)mylist.clear()print("My List before clear:",mylist)`

Method-2: initializes the list with no value

`mylist= [6,0,4,1]print ("My List before clear:",mylist)mylist=[]print("My List before clear:",mylist)`

Method 3: Using operator  *=0

`mylist= [6,0,4,1]print ("My List before clear:",mylist)mylist*=0print("My List before clear:",mylist)`

Method-4: Using del() method

`mylist= [6,0,4,1]print ("My List before clear:",mylist)del mylist[:]print("My List before clear:",mylist)`
##### 12- How to clone or copy a list?

Input: mylist = [4,8,2,10,15,18]

Output: mylistcopy = [4,8,2,10,15,18]

Method 1: Using slicing technique

`mylist= [4,8,2,10,15,18]mylist_copy=mylist[:]print(mylist_copy)`

Method-2: Using extend() method

`mylist= [4,8,2,10,15,18]mylist_copy=[]mylist_copy.extend(mylist)print(mylist_copy)`

Method 3: Using the list() method

`mylist= [4,8,2,10,15,18]mylist_copy=list(mylist)print(mylist_copy)`

Method-4: Using copy() method

`mylist= [4,8,2,10,15,18]mylist_copy= mylist.copy()print(mylist_copy)`

Method 5: Using list comprehension

`mylist= [4,8,2,10,15,18]mylist_copy= [i for i in mylist]print(mylist_copy)`
##### 13- Program to count the occurrence of an element in a list?

Input: mylist=[15,6,7,10,12,10,20,10]

x=10

Output: 3

10 appeared 3 times in the given list

Method 1: Using loop

`mylist= [15,6,7,10,12,10,20,10]x=10count=0for ele in mylist:    if(ele==x):        count=count+1print("{} has occured {} times".format(x,count))`

Method-2: Using count()

`mylist= [15,6,7,10,12,10,20,10]x=10print("{} has occured {} times".format(x,mylist.count(x)))`
##### 14- How to find sum of element in the list?

Input: [5,10,15,20]

Output: 50

`mylist= [5,10,15,20]total=0for i in range(0,len(mylist)):    total=total+mylist[i]print ("Sum of all elements in given list: ", total)`
##### 15- Program to multiply all the numbers in the list?

Input: list1= [3,2,4]

Output: 24

Explanation: 3*2*4=12

`mylist= [3,2,4]result=1for x in mylist:    result=result*xprint(result)`
##### 16- How to find the smallest and the largest number in a list?

Input: mylist=[20,100,20,1,10]

Output:

Smallest is 1

Largest is 100

Method 1: Sort the list in ascending order and print the first and the last elements in the list

`mylist= [20,100,20,1,10]mylist.sort()print(mylist)print("smallest element is:", mylist )print("Largest element is:", mylist[-1] )`

Method-2: Using min() and max() method

`mylist= [20,100,20,1,10]print("smallest element is:", min(mylist))print("Largest element is:", max(mylist))`
##### 17- Program to find the second largest number from the list?

Input: mylist= [90,11,20,40,100]

Output: 90

`mylist= [90,11,20,40,100]mylist.sort()print(mylist)print("largest number is:", mylist[-1])print("second largest number is:", mylist[-2])`
##### 18- How to find the string is palindrome or not?

Method:  Find the reverse of the string and check reversed string is equal to the original or not.

`s=input("Enter a string")revstr=(s[::-1])if revstr==s:    print("palindrome")else:    print("not palindrome")`
##### 19- Program to reverse words in a String?

Input: “Welcome to python programming”

Output: “programming python to Welcome”

`str="Welcome to python programming"words= str.split(" ")print(words)words= words[-1::-1]print (words)outputstr=' '.join(words)`
##### 20- How to find Substring presence in a string?
`Input: "Welcome to python programming"`

sub_str= “python”

str=”Welcome to python programming”
sub_str=”python”

print(str.find(sub_str))

if(str.find(sub_str) == -1):

else:
print(“Found”)

##### 21- Print HELLO for the given string “AHCECLWLXO”.
`str = "AHCECLWLXO" print(str[1::2])`
##### 22- Print HELLO in CAPITAL letters for the given string “ahceclwlxo”.

str1 = “ahceclwlxo”
print (str1[1::2]. upper ())

##### 23- Ask the user to enter a number and then print the multiplication table of that number.
`n = int(input( "Enter the value of n: "))for i in range (1,11):print (n, 'X', i, '=', n * i)`
##### 24- Ask the user to enter two number (int) a and b, return true if

a) either one is 6

b) or if their sum is 6

c) or the difference is 6

`def findSix():a = int(input("Please first number : "))b = int(input("Please second number : "))`

if a ==6 or b == 6 or a+b == 6 or abs(a-b) == 6:
return True
else:
return False

##### 25- Ask the user to input a string of odd length, return the string length 3 from its middle. The string length will be at least 3.

Ex. (“Candy”) → “and”

`def middle(s):#s=str(input('enter string of odd no'))if len(s)%2==0:return 'Enter correct string of odd num and try again'else:i=int((len(s)-1)/2)return s[i-1:i+2]print(middle('Candy'))`
##### 26- Given 2 strings, a and b, return a new string made of the first char of a and the last char of b. If either string is length 0, use ‘@’ for its missing char.

Ex. (“last”, “chars”) → “ls”
Ex. (“yo”, “java”) → “ya”

`def fristlast(s1,s2):if len(s1)>0 and len(s2)>0:return s1+s2[-1]#elif len(s1<0) or len(s2)<0:elif len(s1)>0 and len(s2)<=0:return str(s1)+'@'elif len(s1)<=0 and len(s2)>0:return '@'+str(s2[-1])elif len(s1)<=0 and len(s2)<=0:return '@@'print(fristlast('last','chars'))`
##### 27- Ask the user to input a string and an integer n, return a string made of the first and last n chars from the string. The string length will be at least n.

Ex1:(“Hello”, 2) → “Helo”
Ex2:(“Chocolate”, 3) → “Choate”
Ex3:(“Chocolate”, 1) → “Ce”
Ex4:(“Hello”, 1) → “Ho”

`def practice1(s,n):return s[:n]+s[-n:]print(practice1("Hello", 2))print(practice1("Chocolate", 3))print(practice1("Chocolate", 1))`
##### 28- Given a string, return true if “bad” appears starting at index 0 or 1 in the string, The string may be any length, including 0.

`def practive2(s):if s.index('bad')==0 or s.index('bad')==1:return Trueelse:return Falseprint(practive2("badxx"))print(practive2("xbadxx"))print(practive2("xxbadxx"))`
##### 29- Ask user to input a string, return a new string where for every char in the original, there are two chars.

Ex1: (“The”) → “TThhee”
Ex2: (“AAbb”) → “AAAAbbbb”
Ex3: (“Hi-There”) → “HHii–TThheerree”

`def practice1(s):j=""for i in range(len(s)):j=j+(s[i]*2)return jprint(practice1("The"))print(practice1("AAbb"))print(practice1("AAbb"))`
##### 30- Return the number of times that the string “code” appears anywhere in the given string

Ex1: (“aaacodebbb”) → 1
Ex2: (“codexxcode”) → 2
Ex3: (“codexxcodexxcode”) → 3

`def practice2(s):return s.count("code")print(practice2("aaacodebbb"))print(practice2("codexxcode"))print(practice2("codexxcodexxcode"))`
##### 31- For the given below strings, Return true if the string “cat” and “dog” appear the same number of times.

Ex1: (“catdog”) → true
Ex2:(“catcat”) → false
Ex4:(“catnotdog”) → true

`def status(a):if a.count("cat") == a.count("dog"):return Trueelse:return Falsea = "catdog"value = status(a)print value`
##### 32- Return the sum of the numbers in the array,a: Return 0 for an empty array. b: Number 13 is very unlucky, so it does not count and numbers that come immediately after a 13 also do not count.

Ex1: [1, 2, 2, 1] → 6
Ex2: [1, 1] → 2
Ex3: [1, 2, 2, 1, 13] → 6

`def sum13(n):Total=0for i in range (len(n)):if(n[i]==13 or n[i-1]==13 and i!=0):Total=Total else:Total=Total+n[i]return Total`

print(sum13([13, 2, 5, 8, 13, 4]))

##### 33- Given a number n, create and return a new int array of length n, containing the numbers 0, 1, 2, … n-1. The given n may be 0, in which case just return a length 0 array.

Ex1:(4) → [0, 1, 2, 3]
Ex2:(1) → 
Ex3:(10) → [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

`def array(n): if n==0: return range(0,1) else: return range(0,n,1) print(array(4))`
##### 34- Given an array length 1 or more of ints, return the difference between the largest and smallest values in the array.

Ex1: [10, 3, 5, 6] → 7
Ex2: [7, 2, 10, 9] → 8

`lst = [10, 3, 5, 6]print(max(lst) - min(lst))`
##### 35- Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and extending to the next 7.(every 6 will be followed by at least one 7). Return 0 for no numbers.

Ex1: [1, 2, 2] → 5
Ex2: [1, 2, 2, 6, 7] → 5

`def sumofnos(nums):total = 0i=0 while i < len(nums):if nums[i] == 6:while nums[i] != 7:i+=1i+=1elif nums[i]!=6: total+=nums[i]i+=1return totalprint(sumofnos([1,2,2,6,7,1]))`
##### 36- Given an array of ints, return true if every element is a 1 or a 4.

Ex1: only14([1, 4, 1, 4]) → true
Ex2: only14([1, 4, 2, 4]) → false

`def oneorfour(l):for i in l:if i==1 or i==4:continueelse:return False return True print(oneorfour([1, 4, 1, 4]))print(oneorfour([1, 4, 2, 4]))print(oneorfour([1, 1]))print(oneorfour())`
##### 37- Given an array of ints, return true if the array contains two 7’s next to each other, or there are two 7’s separated by one element.

Ex1: [1, 7, 7] → true
Ex2: [1, 7, 1, 7] → true
Ex3: [1, 7, 1, 1, 7] → false

`def check7(l): for i in range(len(l)-1): if i<=len(l)-1 and l[i]==7 and l[i+1]==7: return True elif i<=len(l)-2 and l[i]==7 and l[i+2]==7: return True return False print(check7([1, 7, 7])) print(check7([1, 7, 1, 7])) print(check7([1, 7, 1, 1, 7])) print(check7([7, 7, 1, 1, 7])) print(check7([9, 0, 5, 1, 7])) print(check7([7, 7, 7, 7, 7]))`
##### 38- Return true if the array contains three increasing adjacent numbers like.

Ex1: [1, 2, 3] → true
Ex2: [6, 7, 8] → true
Ex3: [15, 16, 17] → true

`def checkincr(l):for i in range(len(l)):if i<=len(l)-2 and l[i] == (l[i+1]-1) == (l[i+2]-2):return Truereturn Falseprint(checkincr([1, 2, 3]))print(checkincr([6, 7, 8]))print(checkincr([15, 16, 17]))print(checkincr([1, 4, 5, 6, 2]))print(checkincr([1, 2, 4]))print(checkincr([1, 5, 6, 8]))print(checkincr([18, 15, 4]))`
##### 39- Return an array where each zero value in the array is replaced by the largest odd value to the right of the zero in the array. If there is no odd value to the right of the zero, leave the zero as a zero.

Ex1: [0, 5, 0, 3] → [5, 5, 3, 3]
Ex2: [0, 4, 0, 3] → [3, 4, 3, 3]
Ex3: [0, 1, 0] → [1, 1, 0]

`def fillzero(l):maxodd=0 for i in range(1,len(l)+1): if l[-i]%2==1 and l[-i]>maxodd: maxodd=l[-i] elif l[-i]==0: l[-i]=maxodd return l print(fillzero([0, 5, 0, 3])) print(fillzero([0, 4, 0, 3])) print(fillzero([0, 1, 0])) print(fillzero([0, 4, 0, 3,5]))`
##### 40- Given an array of ints, return true if the number of 1’s is greater than the number of 4’s

Ex1: [1, 4, 1] → true
Ex2: [1, 4, 1, 4] → false
Ex3: [1, 1] → true
Ex4: [1, 4, 4, 4] → false
Ex5: [1, 1, 1, 4] → true

`def onefours(lst): if 1 in lst or 4 in lst: ones=lst.count(1) fours=lst.count(4) return (ones>fours) return 'Array doesnt contains 1s and 4s' print(onefours([1, 4, 1])) print(onefours([1, 4, 1, 4])) print(onefours([1, 1])) print(onefours([1, 4, 4, 4])) print(onefours([1, 1, 1, 4])) print(onefours([5,4,0,2])) print(onefours([2,3,5,6]))`

For More Software Testing Interview Questions visit ALLSTQ

Wikipedia Python

### 4 thoughts on “python coding interview questions and answers for testers”

1. Thankyou

😊😊😊😊

1. 2. useful programs.update more programs

3. 