Saturday 17 September 2022

Python Example Problems : Odd and Even Numbers

 Finding even and odd numbers using while loop in Python

Example 1

i=1
x=[]
y=[]
while (i <= 30):
    if i%2 == 0:
        x.append(i)
       
    else :
        y.append(i)
       
    i = i + 1  
print(f"even numbers are {x} ")    
print(f" odd number are {y} ")

Output

even numbers are [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30] odd number are [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29]

Example 2

Finding odd and even numbers in a specified list

n = int(input("Enter a number till which we need to list out odd and even numbers: "))
i=1
x=[]
y=[]

while (i <= n):
    if i%2 == 0:
        x.append(i)
       
    else :
        y.append(i)
       
    i = i + 1  
print(f"even numbers are {x} ")    
print(f" odd number are {y} ")

output Enter a number till which we need to list out odd and even numbers: 10
even numbers are [2, 4, 6, 8, 10] odd number are [1, 3, 5, 7, 9]

No comments:

Post a Comment