Write a Python Program to Print Odd Numbers in a List using For Loop, While Loop, and Functions with a practical example.
Python Program to Print Odd Numbers in a List using For Loop
In this Python program, we are using For Loop to iterate each element in this list. We are using the If statement inside the for loop to check and print odd numbers.
NumList = [] Number = int(input("Please enter the Total Number of List Elements: ")) for i in range(1, Number + 1): value = int(input("Please enter the Value of %d Element : " %i)) NumList.append(value) print("\nOdd Numbers in this List are : ") for j in range(Number): if(NumList[j] % 2 != 0): print(NumList[j], end = ' ')
User entered list elements = [3, 4, 5, 9]. Within this Python program, the For Loop iteration is
For Loop – First Iteration: for 0 in range(0, 4)
The condition is True. So, it enters into the If Statement
if(NumList[0] % 2 != 0) => if(3 % 2 != 0) – Condition is True
This Number is printed.
Second Iteration: for 1 in range(0, 4) – Condition is True
if(NumList[1] % 2 != 0) => if(4 % 2 != 0) – Condition is False
This Number was Skipped.
Third Iteration: for 2 in range(0, 4) – Condition is True
if(NumList[2] % 2 != 0) => if(5 % 2 != 0) – Condition is True
This Number will print.
Fourth Iteration: for 3 in range(0, 4) – Condition is True
if(9 % 2 != 0) – Condition is True
This number is also printed.
Fifth Iteration: for 4 in range(0, 4) – Condition is False
So, it exits from Python For Loop
Python Program to Print Odd Numbers in a List using While loop
This program for odd numbers in a list is the same as the above. We just replaced the For Loop with a While loop.
NumList = [] j = 0 Number = int(input("Please enter the Total Number of List Elements: ")) for i in range(1, Number + 1): value = int(input("Please enter the Value of %d Element : " %i)) NumList.append(value) print("\nOdd Numbers in this List are : ") while(j < Number): if(NumList[j] % 2 != 0): print(NumList[j], end = ' ') j = j + 1
Python Program to Print Odd Numbers in a List using Functions
These odd numbers in a list program are the same as the first example. However, we separated the logic using Functions.
def odd_numbers(NumList): for j in range(Number): if(NumList[j] % 2 != 0): print(NumList[j], end = ' ') NumList = [] Number = int(input("Please enter the Total Number of List Elements: ")) for i in range(1, Number + 1): value = int(input("Please enter the Value of %d Element : " %i)) NumList.append(value) print("\nOdd Numbers in this List are : ") odd_numbers(NumList)