Python - Lists, For Loop Continuation
Python - Lists, For Loop Continuation
P20) Write a Python function that takes a list of numbers as input and returns the sum of all the
numbers in the list.
numbers = [1, 2, 3, 4, 5]
total_sum_loop = 0
for num in numbers:
total_sum_loop += num
print("Sum using loop:", total_sum_loop)
numbers = []
for i in range(no_of_numbers):
num = int(input("Enter number: "))
numbers.append(num)
P21) Given a list of numbers, write a Python function to find and print all the even numbers in the list.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = []
for num in numbers:
if num % 2 == 0:
even_numbers.append(num)
print("Even numbers:", even_numbers)
P22) Write a Python function that takes a list of numbers and returns a new list with only the positive
numbers.
numbers = [-2, -1, 0, 1, 2, 3, 4, 5]
positive_numbers = []
P23) Given a list of strings, write a Python function to find and print all the strings that have a length
of 4 characters.
strings = ["apple", "banana", "orange", "grape", "kiwi", "pear"]
for string in strings:
if len(string) == 4:
print(string)
P24) Write a Python function that takes a list of integers and returns a new list with the square of each
number.
numbers = [1, 2, 3, 4, 5]
squared_numbers = []
P25) Take input a string, and print the number of consonants and vowels.
user_input = input("Enter a string: ")
vowels = "aeiouAEIOU"
consonants_count = 0
vowels_count = 0
P26) Write a Python program to calculate the factorial of a given number using a for loop.
num = int(input("Enter a number: "))
if num < 0:
print("Factorial is not defined for negative numbers.")
else:
result = 1
for i in range(1, num + 1):
result *= i
print("Factorial of", num, "is", result)
P27) Write a Python program to print all the prime numbers between 1 and N using a for loop.
N = int(input("Enter the value of N: "))
if is_palindrome:
print("Palindrome")
else:
print("Not a Palindrome")
P29) Write a Python program to print all the factors of a given number using a for loop.
num = int(input("Enter a number: "))
if num < 1:
print("Factors are only defined for positive integers.")
else:
print("Factors of", num, ":")
for i in range(1, num + 1):
if num % i == 0:
print(i, end=", ")
P30) Write a Python program to find the smallest and largest number from a list of numbers.
numbers = [12, 45, 23, 67, 1, 90, 34, 78]
if not numbers:
print("The list is empty.")
else:
smallest = largest = numbers[0]
if sum_of_cubes == original_number:
print(f"{original_number} is an Armstrong number.")
else:
print(f"{original_number} is not an Armstrong number.")
if divisors_sum == number:
print(number," is a perfect number.")
else:
print(number," is not a perfect number.")