loops

Python problems on loops 2

June 12, 20242 min read

Problem 1: Sum of Natural Numbers

Question: Write a program to find the sum of the first n natural numbers.

  • Example Input:n = 5

  • Example Output:15

  • Solution:

Problem 2: Factorial of a Number

Question: Write a program to find the factorial of a number n.

  • Example Input:n = 4

  • Example Output:24

Problem 3: Print Multiplication Table

Question: Write a program to print the multiplication table of a number n.

  • Example Input:n = 3

  • Example Output:

    3 x 1 = 3
    3 x 2 = 6
    3 x 3 = 9
    ...
    3 x 10 = 30

Problem 4: Reverse a String

Question: Write a program to reverse a given string.

  • Example Input:s = "hello"

  • Example Output:olleh

Problem 5: Count Digits in a Number

Question: Write a program to count the number of digits in a number n.

  • Example Input:n = 12345

  • Example Output:5

Problem 6: Fibonacci Sequence

Question: Write a program to print the first n terms of the Fibonacci sequence.

  • Example Input:n = 5

  • Example Output:0 1 1 2 3

Problem 7: Sum of Digits

Question: Write a program to find the sum of digits of a number n.

  • Example Input:n = 123

  • Example Output:6

Problem 8: Palindrome Check

Question: Write a program to check if a given string is a palindrome.

  • Example Input:s = "racecar"

  • Example Output:True

Problem 9: Find the Largest Number

Question: Write a program to find the largest number in a list.

  • Example Input:lst = [3, 1, 4, 1, 5, 9]

  • Example Output:9

Problem 10: Find the Second Largest Number

Question: Write a program to find the second largest number in a list.

  • Example Input:lst = [3, 1, 4, 1, 5, 9]

  • Example Output:5

Problem 11: Count Vowels in a String

Question: Write a program to count the number of vowels in a given string.

  • Example Input:s = "hello"

  • Example Output:2

Problem 12: Sum of Even Numbers

Question: Write a program to find the sum of even numbers from 1 to n.

  • Example Input:n = 10

  • Example Output:30

Problem 13: Count Words in a String

Question: Write a program to count the number of words in a given string.

  • Example Input:s = "hello world"

  • Example Output:2

blog author image

sunil s

Quant Developer & Mentor

Back to Blog