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
-
please add input fileTalha Israr– Talha Israr2019年01月19日 12:56:35 +00:00Commented Jan 19, 2019 at 12:56
-
2@TalhaIsrar Unnecessary; problem is clearLightness Races in Orbit– Lightness Races in Orbit2019年01月19日 12:58:17 +00:00Commented Jan 19, 2019 at 12:58
3 Answers 3
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():
4 Comments
eachenv is not "DEV01" or "DEV01". I think it has an \n at the end. like this: "DEV01\n" @user1557960if eachenv.rstrip() in ["DEV01", "DEV02"] then update me here. if eachenv=="DEV01" or "DEV02":
Means, if either of the following:
eachenvis 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:
eachenvis equal to"DEV01"eachenvis equal to"DEV02"
Yay!
Comments
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.