Python script: upper bound of range not being included

52 Views Asked by At

I wrote this script:

inpf = input('input file name:')
lb = input('lower bound:')
ub = input('upper bound:')
with open(inpf, 'r') as f:
    contents = f.readlines()
    for i in contents:
        if lb <= i <= ub:
            print(i, end='')

But it's not performing as expected and I can't figure out why. For the first input (inpf) I put in the name of a .txt file named input1.txt, with the following contents:

aspiration
classified
federation
graduation
millennium
philosophy
quadratics
transcript
wilderness
zoologists

For the second input (lb) I put in 'classified' (without quotes).

For the third input (ub) I put in 'millennium' (without quotes).

The output should be:

classified
federation
graduation
millennium

But for some reason the lower bound (classified) is included in my output, but not the upper bound (millennium). Whenever I run into coding problems, I just consult with ChatGPT, Bard, or Bing Chat and get answers no problem. But this one has all 3 LLMs stumped. They just keep giving back exactly the same code as what I wrote, or something that gets the same incorrect results.

Can anyone help me solve this mystery?

I tried different variations with the operators, and using "if i >= lb or i <= ub" instead of "if lb <= i <= ub", but got the same results.

2

There are 2 best solutions below

0
Julien On

All your i's have a '\n' character at the end. So you are comparing 'millennium\n' <= 'millennium' which is False. So strip your lines:

    if lb <= i.strip() <= ub:
        print(i)
0
Connor Davidson On

Each line has a line break at the end of it, \n

Your working code would look like this:

inpf = input('input file name:')
lb = input('lower bound:')
ub = input('upper bound:')
with open(inpf, 'r') as f:
    contents = f.readlines()
    for i in contents:
        if lb <= i <= ub + "\n":
            print(i, end='')