Loop practice questions in Python - Level 3

WAP stands for Write A Program

  1. WAP to print all prime numbers between two input numbers using while loops.
  2. WAP in Python to check whether two strings are anagrams of each other using only for loops.
    Input: “listen”, “silent”
    Output: True
    An anagram of a string is another string that contains the same characters, only the order of characters can be different.

  3. WAP to flatten a nested list (i.e., a list of lists) into a single list using for loops.
    Input: a = [[1,2], [3,4,5],[6]]
    Output: 1, 2, 3, 4, 5, 6,

  4. WAP to calculate the sum of the product of corresponding elements from two lists.

    Input: a = [1, 2, 3], b = [4, 5, 6,]
    Output: 32
    Logic: (1*4 + 2*5 + 3*6)
  5. WAP to print all possible pairs of elements from a list using nested for loops.
    Input: a = [1, 2, 3]
    Output: 1, 1 \n 1, 2 \n 1, 3 \n 2, 1 \n 2, 2 \n 2, 3 \n 3, 1 \n 3, 2 \n 3, 3
  6. WAP to create a list of the cumulative sum of elements of a given list using for loops.
    Input: a = [1, 2, 3, 4]
    Output: [1, 3, 6, 10]
  7. WAP to print all the factors of a given input number.
    Input: n = 27
    Output: Factors = 1, 3, 9, 27
  8. WAP in Python to print the average of marks of each student only if the average is more than 90.
    Input:
    d = {“Samarth”:[45, 60, 50, 90, 70], “Jatin”: [90, 95, 93, 91, 90], “Nishant”:[93, 99, 98, 97, 91]}
    Output: Jatin Average is 91.8
                       Nishant Average is 95.6
     
  9. WAP to count the number of distinct elements in a list without using sets.
    Input: a = [1, 2, 2, 3, 4, 4, 5]
    Output: 5
  10. WAP to implement a Caesar Cipher encryption using a for loop, where n represents the number of shifts for each letter in the alphabet.
    Input: string = ‘hello, n = 3
    Output: “Khoor”
    Logic: Each alphabet is shifted by 3 positions.