-3

This is the INPUT:

inp = input("Enter the file name: ")
count = 0
try:
    x = open(inp)
except:
    print("This won't work")
    quit() 
for line in x:
    count += 1
print("There are", count, "lines in", inp)

This is the OUTPUT

NameERROR: name 'quit' is not defined

quit(), exit(), os._exit(), sys.exit(), nothing works. I think it's not in the library, where can I download the module containing the quit() function?

martineau
  • 119,623
  • 25
  • 170
  • 301
  • 1
    To use `os` or `sys` you first need to `import` them. – TheLazyScripter Aug 14 '20 at 15:45
  • https://www.geeksforgeeks.org/python-exit-commands-quit-exit-sys-exit-and-os-_exit/ – Dan Aug 14 '20 at 15:48
  • Your code works for me. `quit()` and `exit()` are built-in. If you want to use `sys.exit()` you must first `import sys`. There is no `os.exit()`. – martineau Aug 14 '20 at 16:01
  • 1
    Please search stack overflow for similar errors before posting the question. There is similar questions with answers. Check this link [https://stackoverflow.com/q/45066518/9010467] – Rohit Aug 14 '20 at 16:01

2 Answers2

0

I believe you looking for exit()

for i in range(10):
    print(i)
    if i ==5:
        exit()

output: 0 1 2 3 4 5
"exit() is not working"
Check except block is executing or not

user13966865
  • 448
  • 4
  • 13
0

You may have to learn more about the try except else finally syntax. You can. get more information about that here.

Python try-else

I would also recommend that you read through the file open options in python. Link to that is here https://docs.python.org/3/tutorial/inputoutput.html. I would use the with option. I am not changing your code to reflect all the new changes as you are still discovering the wonderful world of python.

In the meanwhile, here are some ways you can address your current problem.

inp = input("Enter the file name: ")
count = 0
try:
    x = open(inp) #this will open in read text mode 
except:
    print("This won't work")
else: #refer to https://stackoverflow.com/questions/855759/python-try-else
    for line in x:
        count += 1
    print("There are", count, "lines in", inp)

Or You can try to do it this way too.

inp = input("Enter the file name: ")
count = 0
success = True
try:
    x = open(inp) #this will open in read text mode 
except:
    print("This won't work")
    success = False

if success:
    for line in x:
        count += 1
    print("There are", count, "lines in", inp)
Joe Ferndz
  • 8,417
  • 2
  • 13
  • 33