Thursday, October 17, 2024

40 Python Programs Collections – 03 - LOOPING STRUCTURE - FOR AND WHILE

 

 


1.     Print numbers from 1 to 10 using a for loop

 

for i in range(1, 11):

    print(i)

 

2.     Print numbers from 1 to 10 using a while loop

 

i = 1

while i <= 10:

    print(i)

    i += 1

 

3.     Print the first 10 natural numbers in reverse order

 

for i in range(10, 0, -1):

    print(i)

 

4.     Sum of numbers from 1 to 100

 

total = 0

for i in range(1, 101):

    total += i

print("Sum:", total)

 

5.     Print even numbers between 1 and 20

 

for i in range(2, 21, 2):

    print(i)

 

6.     Find the sum of even numbers between 1 and 50

 

total = 0

for i in range(2, 51, 2):

    total += i

print("Sum of even numbers between 1 and 50:", total)

 

7.     Calculate the sum of all odd numbers from 1 to 100

 

total = 0

for i in range(1, 101, 2):

    total += i

print("Sum of odd numbers between 1 and 100:", total)

 

 

8.     Sum of the first n natural numbers

 

n = int(input("Enter a number: "))

total = sum(range(1, n + 1))

print(f"Sum of the first {n} natural numbers is {total}")

 

9.     Find the sum of numbers divisible by 3 and 5 between 1 and 100

 

total = 0

for i in range(1, 101):

    if i % 3 == 0 and i % 5 == 0:

        total += i

print("Sum of numbers divisible by 3 and 5 between 1 and 100:", total)

 

10.  Print the first 10 multiples of a given number

 

num = int(input("Enter a number: "))

for i in range(1, 11):

    print(f"{num} x {i} = {num * i}")

 

11.  Print the sum of the first 20 even numbers

 

total = 0

for i in range(2, 41, 2):

    total += i

print("Sum of the first 20 even numbers:", total)

 

 

 

12.  Print the multiplication table of a number

 

num = int(input("Enter a number: "))

for i in range(1, 11):

    print(f"{num} x {i} = {num * i}")

 

13.  Factorial of a number using a for loop

 

num = int(input("Enter a number: "))

factorial = 1

for i in range(1, num + 1):

    factorial *= i

print(f"Factorial of {num} is {factorial}")

 

14.  Factorial of a number using a while loop

 

num = int(input("Enter a number: "))

factorial = 1

i = 1

while i <= num:

    factorial *= i

    i += 1

print(f"Factorial of {num} is {factorial}")

 

15.  Print the Fibonacci sequence up to a given number

 

n = int(input("Enter a number: "))

a, b = 0, 1

while a <= n:

    print(a, end=" ")

    a, b = b, a + b

 

16.  Print the Fibonacci sequence up to n terms using a while loop

 

n = int(input("Enter the number of terms: "))

a, b = 0, 1

count = 0

while count < n:

    print(a, end=" ")

    a, b = b, a + b

    count += 1

 

17.  Print the sum of the digits of a number

 

num = int(input("Enter a number: "))

sum = 0

while num > 0:

    digit = num % 10        

    sum += digit     #

    num = num // 10           

print("Sum of the digits:", sum)

 

18.  Check if a number is prime using a while loop

 

num = int(input("Enter a number: "))

i = 2

is_prime = True

while i <= num // 2:

    if num % i == 0:

        is_prime = False

        break

    i += 1

if is_prime:

    print(f"{num} is a prime number.")

else:

    print(f"{num} is not a prime number.")

 

19.  Print all prime numbers up to 50

 

for num in range(2, 51):

    for i in range(2, num):

        if num % i == 0:

            break

    else:

        print(num)

 

20.  Find the GCD of two numbers using a while loop

 

a = int(input("Enter the first number: "))

b = int(input("Enter the second number: "))

while b:

    a, b = b, a % b

print(f"GCD is {a}")

 

21.  Find the LCM of two numbers using a for loop

 

def gcd(a, b):

    while b:

        a, b = b, a % b

    return a

 

def lcm(a, b):

    return a * b // gcd(a, b)

 

a = int(input("Enter the first number: "))

b = int(input("Enter the second number: "))

print(f"LCM is {lcm(a, b)}")

 

22.  Count the number of digits in a number

 

num = int(input("Enter a number: "))

count = 0

while num > 0:

    num //= 10

    count += 1

print(f"Number of digits:", count)

 

23.  Calculate the power of a number using a for loop

 

base = int(input("Enter the base: "))

exponent = int(input("Enter the exponent: "))

result = 1

for _ in range(exponent):

    result *= base

print(f"{base} to the power of {exponent} is {result}")

 

24.  Reverse a number using a while loop

num = int(input("Enter a number: "))

reversed_num = 0

while num > 0:

    digit = num % 10              

    reversed_num = reversed_num * 10 + digit 

    num = num // 10               

print("Reversed number:", reversed_num)

 

25.  Print the sum of squares of numbers from 1 to 10

 

total = 0

for i in range(1, 11):

    total += i ** 2

print("Sum of squares:", total)

 

26.  Print the cube of numbers from 1 to 5

 

for i in range(1, 6):

    print(f"Cube of {i} is {i ** 3}")

 

27.  Check if a number is a palindrome using a while loop

 

num = int(input("Enter a number: "))

original_num = num

reversed_num = 0

while num > 0:

    digit = num % 10

    reversed_num = reversed_num * 10 + digit

    num //= 10

 

if original_num == reversed_num:

    print(f"{original_num} is a palindrome.")

else:

    print(f"{original_num} is not a palindrome.")

 

28.  Print all Armstrong numbers between 100 and 999

 

for num in range(100, 1000):

    sum_of_cubes = sum(int(digit) ** 3 for digit in str(num))

    if sum_of_cubes == num:

        print(num)

 

29.  Check if a number is an Armstrong number using a while loop

 

num = int(input("Enter a number: "))

sum_of_cubes = 0

temp = num

 

while temp > 0:

    digit = temp % 10

    sum_of_cubes += digit ** 3

    temp //= 10

 

if num == sum_of_cubes:

    print(f"{num} is an Armstrong number.")

else:

    print(f"{num} is not an Armstrong number.")

 

30.  Print the factorial of a number using recursion

 

def factorial(n):

    if n == 1:

        return 1

    else:

        return n * factorial(n - 1)

 

num = int(input("Enter a number: "))

print(f"Factorial of {num} is {factorial(num)}")

 

31.  Print a pyramid pattern of stars

 

rows = int(input("Enter the number of rows: "))

for i in range(1, rows + 1):

    print(' ' * (rows - i) + '*' * (2 * i - 1))

 

32.  Print an inverted pyramid pattern of stars

 

rows = int(input("Enter the number of rows: "))

for i in range(rows, 0, -1):

    print(' ' * (rows - i) + '*' * (2 * i - 1))

 

33.  Find the sum of the digits of an integer using a for loop

 

num = input("Enter a number: ")

total = 0

for digit in num:

    total += int(digit)

print("Sum of digits:", total)

 

34.  Calculate the average of numbers entered by the user

 

total = 0

count = 0

while True:

    num = input("Enter a number (or 'done' to finish): ")

    if num.lower() == 'done':

        break

    total += float(num)

    count += 1

print("Average:", total / count)

 

35.  Generate a list of squares of numbers from 1 to n

 

n = int(input("Enter a number: "))

squares = [i ** 2 for i in range(1, n + 1)]

print("List of squares:", squares)

 

36.  Print all multiples of 4 between 1 and 100

 

for i in range(4, 101, 4):

    print(i)

 

37.  Check if a number is a perfect square using a while loop

 

import math

 

num = int(input("Enter a number: "))

sqrt = math.isqrt(num)

if sqrt * sqrt == num:

    print(f"{num} is a perfect square.")

else:

    print(f"{num} is not a perfect square.")

 

38.  Check if a number is a perfect number

 

num = int(input("Enter a number: "))

divisors = [i for i in range(1, num) if num % i == 0]

if sum(divisors) == num:

    print(f"{num} is a perfect number.")

else:

    print(f"{num} is not a perfect number.")

 

39.  Print the factorial of numbers from 1 to n

 

n = int(input("Enter a number: "))

factorial = 1

for i in range(1, n + 1):

    factorial *= i

    print(f"Factorial of {i} is {factorial}")

 

40.  Find the largest number in a list using a loop

 

lst = [int(x) for x in input("Enter numbers separated by spaces: ").split()]

largest = lst[0]

for num in lst:

    if num > largest:

        largest = num

print("Largest number:", largest)

 

41.  Print all prime factors of a given number

 

num = int(input("Enter a number: "))

i = 2

while num > 1:

    if num % i == 0:

        print(i)

        num //= i

    else:

        i += 1

 

42.  Find the smallest number in a list using a loop

 

lst = [int(x) for x in input("Enter numbers separated by spaces: ").split()]

smallest = lst[0]

for num in lst:

    if num < smallest:

        smallest = num

print("Smallest number:", smallest)

 

43.  Print the first n odd numbers

 

n = int(input("Enter the number of odd numbers: "))

count = 0

i = 1

while count < n:

    print(i)

    i += 2

    count += 1

 

44.  Print the first n even numbers

 

n = int(input("Enter the number of even numbers: "))

count = 0

i = 2

while count < n:

    print(i)

    i += 2

    count += 1

 

45.  Count the number of vowels and consonants in a string

 

string = input("Enter a string: ").lower()

vowels = 'aeiou'

vowel_count = consonant_count = 0

for char in string:

    if char.isalpha():

        if char in vowels:

            vowel_count += 1

        else:

            consonant_count += 1

print("Vowels:", vowel_count)

print("Consonants:", consonant_count)

 

46.  Print the reverse of a string using a loop

 

string = input("Enter a string: ")

reversed_string = ""

for char in string:

    reversed_string = char + reversed_string

print("Reversed string:", reversed_string)

 

 

47.  Count the frequency of each character in a string

 

string = input("Enter a string: ").lower()

frequency = {}

for char in string:

    if char in frequency:

        frequency[char] += 1

    else:

        frequency[char] = 1

print("Character frequency:", frequency)

 

Print all the factors of a number

 

num = int(input("Enter a number: "))

for i in range(1, num + 1):

    if num % i == 0:

        print(i)

 

48.  Calculate the sum of series 1 + 1/2 + 1/3 + ... + 1/n

 

n = int(input("Enter a number: "))

total = 0

for i in range(1, n + 1):

    total += 1 / i

print("Sum of the series:", total)

 

49.  Print the elements of a list in reverse order using a for loop

 

lst = [int(x) for x in input("Enter numbers separated by spaces: ").split()]

for i in range(len(lst) - 1, -1, -1):

    print(lst[i])

 

50.  Count the frequency of elements in a list using a dictionary

 

lst = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]

frequency = {}

for item in lst:

    if item in frequency:

        frequency[item] += 1

    else:

        frequency[item] = 1

print("Frequency of elements:", frequency)

1 comment:

  1. Looping structures like FOR and WHILE are essential in mastering Python programming. Just like ViVe Tool helps optimize builds efficiently, these loops enable programmers to iterate through data and execute code blocks smoothly

    ReplyDelete