Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if-else inside for loop not working in python

I am writing a simple Python script with if-else condition in a for a loop by reading inputs line by line from a text file. Below is my script. I should get the expected output. Please help! My env.txt contains:

DEV01
DEV02
UAT01
UAT02

Here is the code:

with open("env.txt") as envnames:
    for eachenv in envnames:
        if eachenv=="DEV01" or "DEV02":
            eachenv="dev"
            print (eachenv)
        elif eachenv=="UAT01" or "UAT02":
            eachenv="uat"
            print(eachenv)
        else :
            print('')

Expected:

dev
dev
uat
uat

actual:

dev
dev
dev
dev
like image 231
Sivakumar Kayaroganam Avatar asked Jan 28 '26 15:01

Sivakumar Kayaroganam


1 Answers

The problem is if eachenv=="DEV01" or "DEV02".

you can not check like this. the result will be True if eachenv=="DEV01" otherwise the rusult will be "DEV02", not False. you should go like this:

if eachenv in ["DEV01", "DEV02"]:

also change for eachenv in envnames: to:

for eachenv in envnames.readlines():
like image 118
Mehrdad Pedramfar Avatar answered Jan 30 '26 04:01

Mehrdad Pedramfar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!