0

I am trying to create a directory with based on set of logical conditions, but it only correctly executes through second logical statement.

# Sample code:

test_dict = {}

file_0 = "C:/Year/yea_84.txt"
file_1 = "C:/Year/yea_92.txt"
file_2 = "C:/Year/yea_01.txt"
file_3 = "C:/Year/yea_06.txt"

for x in range(1985, 2008):
    if (x <= 1991):
        test_dict[x] = file_0
    elif (x > 1991 & x <= 2000):
        test_dict[x] = file_1
    elif (x > 2000 & x <= 2005):
        test_dict[x] = file_2
    elif (x > 2005):
        test_dict[x] = file_3

print test_dict

# Print result
1985 C:/Year/yea_84.txt
1986 C:/Year/yea_84.txt
1987 C:/Year/yea_84.txt
1988 C:/Year/yea_84.txt
1989 C:/Year/yea_84.txt
1990 C:/Year/yea_84.txt
1991 C:/Year/yea_84.txt
1992 C:/Year/yea_92.txt
1993 C:/Year/yea_92.txt
1994 C:/Year/yea_92.txt
1995 C:/Year/yea_92.txt
1996 C:/Year/yea_92.txt
1997 C:/Year/yea_92.txt
1998 C:/Year/yea_92.txt
1999 C:/Year/yea_92.txt
2000 C:/Year/yea_92.txt
2001 C:/Year/yea_92.txt
2002 C:/Year/yea_92.txt
2003 C:/Year/yea_92.txt
2004 C:/Year/yea_92.txt
2005 C:/Year/yea_92.txt
2006 C:/Year/yea_92.txt
2007 C:/Year/yea_92.txt

I suspect it is because with each loop the dictionary shuffles the order, but that seems like a poor explanation. Can someone expand on this behavior?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
cptpython
  • 393
  • 2
  • 5
  • 12

1 Answers1

3

You are using the wrong operator to do boolean testing. & is the binary bitwise operator, not the boolean logic operator. Because it has a different operator precedence you are really calculating something else:

x > 1991 & x <= 2000

is interpreted as

x > (1991 & x) <= 2000

For 16 of your years that'll be true, including 2001 through to 2007.

Use and instead:

x > 1991 and x <= 2000

or use comparison chaining:

1991 < x <= 2000

Put together, simplifying the last test to else:

for x in range(1985, 2008):
    if x <= 1991:
        test_dict[x] = file_0
    elif 1991 < x <= 2000:
        test_dict[x] = file_1
    elif 2000 < x <= 2005:
        test_dict[x] = file_2
    else:
        test_dict[x] = file_3
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343