函数解包列表不起作用

2024-04-24 21:18:21 发布

您现在位置:Python中文网/ 问答频道 /正文

import os.path
import re
def request ():
    print ("What file should I write to?")
    file = input ()
    thing = os.path.exists (file)
    if thing == "true":
        start = 0
    elif re.match ("^.+.\txt$", file):
        stuff = open (file, "w")
        stuff.write ("Requests on what to add to the server.")
        stuff.close ()
        start = 0
    else:
        start = 1
    go = "yes"
    list1 = (start, file, go)
    return list1
start = 1
while start == 1:
    request ()
    (start, file, go) = list1

我尝试返回getlist1来返回并在循环中解包,这样我就可以设置while循环之后的变量。每当我试着运行这个然后进入”东西.txt“,我得到NameError: name 'list1' is not defined。我是不是少了点什么?在


Tags: topathimportretxtgoosrequest
1条回答
网友
1楼 · 发布于 2024-04-24 21:18:21

试试这个:

# -*- coding: utf-8 -*-
#!/usr/bin/python


import os.path
import re
def request ():
    print ("What file should I write to?")
    file = input ()
    thing = os.path.exists (file)
    # thing is a boolean variable but not a string, no need to use '=='
    if thing:
        start = 0
    elif re.match ("^.+.\txt$", file):
        stuff = open (file, "w")
        stuff.write ("Requests on what to add to the server.")
        stuff.close ()
        start = 0
    else:
        start = 1
    go = "yes"
    list1 = (start, file, go)
    return list1
start = 1
while start == 1:
    # you need to get return value of function request
    list1 = request ()
    (start, file, go) = list1
    # Or you can simply write this way  (start, file, go) = request()

相关问题 更多 >