To find and print the largest odd and even number using python, We need to separate the odd and even numbers and sort that list in descending order. For that we need to accept the numbers from the user using an for loop
and add the elements to the list using the append()
method.
Use a for loop
to traverse from the start to the end of the list and check whether each element is divisible by 2 using the mod(%) operator. If the condition is a success, then add that element into even numbers list else add that number to the odd.
Now we have 2 separate lists for odd and even numbers. Then apply the sort()
function in python language in which the default is ascending order, so use the keyword reverse=TRUE
inside the sort() to change the sorting of the list in descending order. Now, the first element of each list will hold the largest among the odd and even respectively. Output the first number to the user with print()
function in python.
STEP 1: Accept the number of elements in the list using the input()
function in python
STEP 2: Initialize a list called num_lst[] and open a for loop
to add the elements to the list using the append()
function.
STEP 3: initialize two separate lists for odd numbers and even numbers.
STEP 4: Using for loop
traverse the list elements and check each element is divisible by 2 ;
STEP 5: Use the sort()
method to both odd and even list with keyword reverse=TRUE
to sort the elements in Descending order
STEP 6: Print the first element of both odd and even lists to print the largest element.
To sort odd and even numbers and calculate the largest, we need to use the below concepts of python programming, we recommend to learn those for better understanding
n=int(input("Enter the number of list elements: "))
num_lst=[]
even_lst=[]
odd_lst=[]
print("\nEnter list elements:")
for i in range(0,n):
num_lst.append(int(input()))
for i in num_lst:
if(i%2==0):
even_lst.append(i)
else:
odd_lst.append(i)
even_lst.sort(reverse=True)
odd_lst.sort(reverse=True)
print("\nLargest even number:",even_lst[0])
print("\nLargest odd number",odd_lst[0])
Enter the number of list elements: 6 Enter list elements: 8 4 7 9 10 12 Largest even number: 12 Largest odd number 9