0

I am playing first time with input in python and getting some error on this code:

    import random

    x = input("Name of the File? ")
    lines = open(x).read().splitlines()
    myline =random.choice(lines)
    print(myline)

when I run it, it ask me for name.. then I enter: data.txt and getting this error:

    NameError: name 'data' is not defined

1 Answer 1

1

Use raw_input() instead:

import random

x = raw_input("Name of the File? ")
lines = open(x).read().splitlines()
myline =random.choice(lines)
print(myline)

The reason that input() isn't working for you is that it reads your input and then attempts to evaluate it with eval. When you enter the input data it attempts to eval(data) which results in NameError (unless there happens to be a variable with that name in scope). You can make it work with input(), however, you need to enter quotes so that it is evaluated as a string, e.g. enter "data".

Sign up to request clarification or add additional context in comments.

2 Comments

@Jerome - glad to hear it.
@Jerome If this answer worked for you, you should click the outlined checkmark below the votes to "accept" it. See What does it mean when an answer is accepted? if you have any questions.

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.