2

python beginner here. My file contains lines that consists of conditions that are formatted just like a python if statement (without the if in the beginning and colon in the end). Example:

temperature < 40 and weekday == "Thursday" and (country != "Norway" or country != "USA")
(temperature != 30 or temperature != 35) and weekday == "Friday" and country == "Canada"

I want to write code that reads the lines as if they were if statements and prints True or False depending on if the conditions were met. I am thinking something along the lines of:

temperature = 35
country = "Canada"
weekday = "Friday"
file = open('output.txt', r)
lines = file.readlines()
for line in lines:
    if line:
        # if conditions in string are met, print true
        print(True)
    else:
        # else print False
        print(False)

which should when run with above file lines should output

False
True

EDIT:

Would it be possible to reliably and consistently parse the file lines and process it, like how I'm assuming a python compiler would read an actual if statement?

2 Answers2

2

Alright so you've got a few basic issues, mostly forgetting to use "" for strings such as in country = Canada and weekday = Friday. Other than that, you can use the eval() method, however, it is considered bad practice and you should try to avoid it.

temperature = 35
country = "Canada"
weekday = "Friday"
file = open('output.txt', "r")
lines = file.readlines()
for line in lines:
    if eval(line):
        # if conditions in string are met, print true
        print(True)
    else:
        # else print False
        print(False)

Note: Forgot to mention, you need "" for the read specifier in open().

Marco Kurepa
  • 325
  • 1
  • 9
-4

There are two concepts, selection (if statements), and conditions / boolean logic <, or, and, etc. You are trying to use the 2nd. You are correct you don't need the 1st.

When we program we don't write big programs that don't work, the fix them. We start with small programs that work, and then make them bigger. So let me start with a simple example.

temperature < 40

How do we print True if this is true, and False if it is false? The answer may surprise you.

print(temperature < 40)

ctrl-alt-delor
  • 7,506
  • 5
  • 40
  • 52