Python One Line While Loop

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

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

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;
# OUTPUT
1
EVEN
2
ODD
3
EVEN
4
ODD
5
EVEN

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

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
the-roi-of-digital-accessibility

The ROI of Digital Accessibility

Next Post
[ml-story]-dreamboothing-your-way-into-greatness

[ML Story] DreamBoothing Your Way into Greatness

Related Posts
flip-stack-weekly-28-jan-2023

FLiP Stack Weekly 28-Jan-2023

28-Jan-2023 FLiP Stack Weekly Welcome to the fourth newsletter of 2023. Tim Spann @PaaSDev Get some training https://www.eventbrite.com/e/practical-apache-pulsar-application-development-by-streamnative-tickets-522950859097…
Read More