DEV Community

Max
Max

Posted on

3

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

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series