Python 如何按顺序运行多个功能?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29075601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:03:11  来源:igfitidea点击:

How to run multiple functions in order?

pythonfunctionpython-3.x

提问by Emily

This should be an easy one for experienced coders out there... I am writing a program that outputs anagrams (from a given list) from a jumbled input. I believe my code includes all the necessary functions to produce the desired result, but I cannot figure out how to make the program run the respective functions in order. A sample output is:

对于有经验的编码人员来说,这应该是一个简单的程序......我正在编写一个程序,从混乱的输入中输出字谜(来自给定的列表)。我相信我的代码包含产生所需结果的所有必要功能,但我无法弄清楚如何让程序按顺序运行相应的功能。示例输出是:

Please enter a jumbled word: lsitNe
Your words are:
silent
listen
enlist
tinsel

This is my output, currently:

这是我的输出,目前:

  Please enter a jumbled word: dff
Traceback (most recent call last):
  File "/Users/edinnerman/Desktop/poop.py", line 53, in <module>
    main()
  File "/Users/edinnerman/Desktop/poop.py", line 5, in main
    yay_anagrams = anagramlist(lword)
NameError: name 'lword' is not defined

How do I reformat my code to output all anagrams listed in a text file given a user input? Here is my code:

如何重新格式化我的代码以在给定用户输入的情况下输出文本文件中列出的所有字谜?这是我的代码:

 #0: Create a main function to bring all functions together for the output.
def main():
    textfile = open('words.txt', 'r').read()
    dictionary_of_words = filename(textfile)
    yay_anagrams = anagramlist(lword)
    double_whammy = binary_search(fresh_list, ltextfile)
    answer = output()

#1, 2: Take a filename as a parameter and ask user for word to unjumble. Lowercase all.
def filename(textfile):
    ltextfile = textfile.lower()
    scrambled_eggs = input("Please enter a jumbled word: ")
    lword = scrambled_eggs.lower()

#3: Create an anagram list (already lowercase) for the jumbled word.
def anagramlist(lword):
    if lword == "":
        return([lword])
    else:
        yay_word = lword[1:]
        first_letter = lword[0]
        fresh_list = []
        for mixed_word in filename(yay_word):
            for pos in range(len(mixed_word) + 1):
                fresh_list.append(mixed_word[:pos] + first_letter[0] + mixed_word[pos:])
            return fresh_list

#4: Check if any words in anagram list match dictionary list.
def binary_search(fresh_list, ltextfile):
    for eachword in fresh_list:
        low = 0
        high = len(list) - 1 
    while low <= high:
        mid = (low + high)//2
        item = list[mid]
    if fresh_list == item:
        return True
    elif fresh_list < item:
        high = mid - 1
    elif fresh_list > item:
        low = mid + 1
    return False

#5: Print appropriate statements.
def output():
    if fresh_list == True:
        newlist = set()
        for item in fresh_list:
            newlist.add(item)
        print("Your words are:/n", newlist)
    if fresh_list == False:
        print("Your word cannot be unjumbled.")       
main()

Please excuse some of the minor coding errors I might have in this code.

请原谅我在这段代码中可能有的一些小编码错误。

回答by J Richard Snape

Your most major problem here is that you have not got the flow right in terms of assigning your results to variables. As recommended in comments - you might want to take a look at the python function definition tutorial section. I've put some particular things you need to address below.

你在这里最大的问题是你在将结果分配给变量方面没有得到正确的流程。正如评论中所推荐的那样 - 您可能需要查看python 函数定义教程部分。我在下面列出了一些您需要解决的特定事项。

Problem 1

问题一

In particular - you need to consider the returnstatement. If your function definition does not have a returnstatement, then assigning a variable to its result is meaningless. Try an example:

特别是 - 您需要考虑该return声明。如果您的函数定义没有return语句,那么为它的结果分配一个变量是没有意义的。尝试一个例子:

def main():
    x = 1+1

y = main()
print(y)

You might be expecting 2- in fact you'll see None, because the function doesn't return anything. If you alter it, so that it reads:

您可能会期待2- 事实上您会看到None,因为该函数不返回任何内容。如果你改变它,它会写成:

def main():
    x = 1+1
    return x

y = main()
print(y)

you'll now get output 2. Your functions filename()and output()suffer from this.

你现在会得到 output 2。您的功能filename()output()遭受此。

Problem 2

问题二

You can only use the values of variables in a code block if they have already been assigned.

您只能在代码块中使用已分配的变量值。

For example - consider the following very simple program

例如 - 考虑以下非常简单的程序

def message(x):
    return 'You input the string ' + x

def main():
    first_in = input('Please give me some input')
    result = message(in_from_above)
    print(result)

main()

This will fail in a similar way to your program, because in_from_aboveis not a variable that has been defined in your program. If you change it to:

这将以与您的程序类似的方式失败,因为in_from_above不是已在您的程序中定义的变量。如果将其更改为:

def message(x):
    return 'You input the string ' + x

def main():
    first_in = input('Please give me some input')
    result = message(first_in)
    print(result)

main()

it will output the message returned. This problem affects your sequence in main(), beginning with trying to send lwordto the anagramlist()function when you haven't assigned any value to lwordwithin the main()function.

它将输出返回的消息。此问题会影响您在 中的序列main(),首先lwordanagramlist()在您尚未在function 中分配任何值时尝试发送到lwordmain()函数

NoteI can see you have assigned a value to lwordin the filename()function. You might be expecting that assignment to be available to the main()function. It will not. This is to do with something called variable scoping. In general in Python, variables are local, or available only in the block of code where they are defined and assigned. The other type of variable is a globalvariable - where variables are available to code program wide. You can explicitly make an assigment from within a function global, but I can say with some certainty that you don't need to do that for this assignment and would recommend you didn't. Scoping is discussed very briefly in the Python docs here. Scoping is a pretty fundamental programming concept and worth spending some time getting your head around. Play around with some simple examples - use the same variable names inside and outside functions, see what you get etc.

注意我可以看到您lwordfilename()函数中分配了一个值。您可能希望该分配可用于该main()函数。它不会。这与称为变量作用域的东西有关。通常在 Python 中,变量是局部的,或者仅在定义和分配它们的代码块中可用。另一种类型的变量是全局变量 - 其中变量可用于代码程序范围。您可以在 function 内显式地进行global赋值,但我可以肯定地说,对于此赋值,您不需要这样做,并且建议您不要这样做。此处的 Python 文档中非常简要地讨论了范围. 范围是一个非常基本的编程概念,值得花一些时间来了解一下。玩一些简单的例子——在函数内部和外部使用相同的变量名,看看你得到了什么等等。

General comment

一般评论

When stuff goes wrong, to help with debugging, simplify your cases and understand where they're going wrong. You can see I've demonstrated the main problems you have with very simple cases. You can do the same. The logic in your functions may or may not work exactly as you like, but until you get these fundamentals sorted, it will be impossible to debug more complicated cases.

当出现问题时,为了帮助调试、简化案例并了解问题出在哪里。您可以看到我已经用非常简单的案例演示了您遇到的主要问题。你也可以做到的。您函数中的逻辑可能会也可能不会完全按照您的意愿工作,但是在您整理好这些基础知识之前,将无法调试更复杂的情况。

Edit - recommendation

编辑 - 推荐

Just took another look over your code and I would also recommend splitting up functions for #1 and #2 - i.e. one function to lower case your dictionary and another to get the lower case user input. It's not essential, but it will make your code easier to understand and your life easier.

再看看你的代码,我还建议将 #1 和 #2 的函数分开 - 即一个函数来小写你的字典,另一个函数来获取小写的用户输入。这不是必需的,但它会让你的代码更容易理解,让你的生活更轻松。