DEV Community

Max
Max

Posted on

Python One Line While Loop

In this tutorial we will see how to find even or odd in python program using one line while loop.

Python Terniary Operator

Python doesn't have a inbuild terniary operator, we can simulate the operation using one line if statement

print("EVEN") if 4%2==0 else print("ODD")

Output:
EVEN
Enter fullscreen mode Exit fullscreen mode

Using the same techinque we can create a single line while loop

Normal Python While Loop

l = list(range(1, 6))
i = 0

while i<len(l): 
    print(l[i])
    if i%2==0:
        print("EVEN") 
    else:
        print("ODD")
    i+=1
Enter fullscreen mode Exit fullscreen mode

One line Python While Loop

l = list(range(1, 6))
i = 0

while i<len(l): print(l[i]); print("EVEN") if i%2==0 else print("ODD"); i+=1;
Enter fullscreen mode Exit fullscreen mode
# OUTPUT
1
EVEN
2
ODD
3
EVEN
4
ODD
5
EVEN
Enter fullscreen mode Exit fullscreen mode

Explore Other Dev.to Articles

Read and write csv file in Python
Python Install Jupyter Notebook
Python Create Virtual Environment
Read and Write JSON in Python Requests from API
Read and Write Python Json

Top comments (0)