3

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
2
  • please add input file Commented Jan 19, 2019 at 12:56
  • 2
    @TalhaIsrar Unnecessary; problem is clear Commented Jan 19, 2019 at 12:58

3 Answers 3

6

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():
Sign up to request clarification or add additional context in comments.

4 Comments

This gives me empty output
I think all of the solutions here may give you an empty output, because eachenv is not "DEV01" or "DEV01". I think it has an \n at the end. like this: "DEV01\n" @user1557960
change it to if eachenv.rstrip() in ["DEV01", "DEV02"] then update me here.
Your welcome @user1557960. please consider this: stackoverflow.com/help/someone-answers
3
 if eachenv=="DEV01" or "DEV02":

Means, if either of the following:

  • eachenv is equal to "DEV01"
  • "DEV02"

Well, what about "DEV02"? It exists, so that option of the condition is going to be "truthy", so your if will always pass.

This is not how chained conditions work.

You meant:

if eachenv=="DEV01" or eachenv=="DEV02":

Now it's, if either of the following:

  • eachenv is equal to "DEV01"
  • eachenv is equal to "DEV02"

Yay!

Comments

2

In the line if eachenv=="DEV01" or "DEV02": the second condition is always true:

>>> if "DEV02":
...     print('hello')
... 
hello

This happens because the string "DEV02" is an object, therefore will be evaluated True.

@Lightness Races in Orbit gave the right way to write this if statement.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.