0

Im trying to read a file and make sure that each value is in order. I dont think im converting the string into the integer correctly. Here is some of my code. I am also trying to use flags.

fileName = input("What file name? ")
infile = open(fileName,'r')
correct_order_flag = False
i = 0
line = infile.readline()
while line !="": 
    for xStr in line.split(" "):
        if eval(xStr) [i] < i:
            correct_order_flag = True
        else:
            correct_order_flag = False
    i = i+1
if correct_order_flag:
    print("Yes, the numbers were in order")
else:
    print("No, the numbers were not in order")
count = i - 1
print("There were", count, "numbers.")
2
  • 2
    print xStr in order to solve this Commented Oct 30, 2011 at 22:00
  • Jakob's comment was inappropriate. Pythonistas tend to avoid using eval() because it can present a security risk when evaluating untrusted data. There are legitimate use cases for eval(), but this isn't one of them because the str() function will do what you want. Commented Oct 30, 2011 at 22:19

4 Answers 4

4

You are correct - you are indicating with eval(xStr)[i] that eval(xStr) is an array, and thus can be subscripted. What it looks like you may want (since you say you want to convert the string to an int) is just int(xStr), to make that whole line:

if int(xStr) < i:
Sign up to request clarification or add additional context in comments.

Comments

1

For starters, you don't read the whole file at all. Try this:

with open(fileName) as f:
    for line in f:
        # here goes your code

Not sure though, what do you mean by "each value is in order", but using eval() is a VERY bad idea for any purpose.

Comments

0

I would like to add that because you are comparing xstr[i] to i that unless your first number is less than zero the flag will change, meaning that the sequence 1 2 3 4 5 would print out saying "NO, the numbers were not in order"

Comments

0

As Chris indicated, int(s) is the preferred way to convert a string to an integer. eval(s) is too broad and can be a security risk when evaluating data from an untrusted source.

In addition, there is another error in the script. The *correct_order_flag* is being set on every iteration, so one entry with incorrect order can be masked by a subsequent entry in the correct order. Accordingly, you should break out of the loop when incorrect ordering is found.

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.