【问题标题】:Where to install the quit() function? [duplicate]在哪里安装 quit() 函数? [复制]
【发布时间】:2020-08-14 15:37:03
【问题描述】:

这是输入:

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)

这是输出

NameERROR: name 'quit' is not defined

quit()exit()os._exit()sys.exit(),没有任何效果。我想它不在库中,我在哪里可以下载包含quit()函数的模块?

【问题讨论】:

  • 要使用ossys,您首先需要import 他们。
  • 您的代码对我有用。 quit()exit() 是内置的。如果你想使用sys.exit(),你必须先import sys。没有os.exit()
  • 请在发布问题之前搜索堆栈溢出以查找类似错误。有类似的问题有答案。检查此链接 [stackoverflow.com/q/45066518/9010467]

标签: python


【解决方案1】:

相信你在找exit()

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

输出: 0 1 2 3 4 5
“exit() 不工作”
检查 except 块是否正在执行

【讨论】:

    【解决方案2】:

    您可能需要了解有关try except else finally 语法的更多信息。你可以。在此处获取更多信息。

    Python try-else

    我还建议您通读 python 中的文件打开选项。链接在这里https://docs.python.org/3/tutorial/inputoutput.html。我会使用 with 选项。我不会更改您的代码以反映所有新变化,因为您仍在探索 Python 的精彩世界。

    与此同时,这里有一些方法可以解决您当前的问题。

    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)
    

    或者你也可以尝试这样做。

    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)
    

    【讨论】:

      猜你喜欢
      • 2015-03-03
      • 2019-10-10
      • 1970-01-01
      • 2011-01-05
      • 2020-02-23
      • 1970-01-01
      • 1970-01-01
      • 2014-12-26
      • 1970-01-01
      相关资源
      最近更新 更多