具有定义函数的递归,用于基于文本的简单Python程序

时间:2018-07-06 08:40:26

标签: python loops recursion

我正在编写我的第一个程序-它是一个成语生成器,它以Madlibs风格结合随机动词,名词和代词(我输入的)列表中的各个元素,并生成幽默的表达。这是我的源代码的简化版本:

baseFunction = True
def mainFunction() :
  import random
  quest = input("Which language do you want it in? Type 'French' or 'English'. ")
  if quest == "French" or "french":
      verb = 
      #list of verbs I have manually entered
      noun = 
      #list of nouns I have manually entered
      pronoun = 
      #list of pronouns I have manually entered
      morenouns = 
      #list of nouns I have manually entered
      phrase = random.choice(verb) + random.choice(noun) + random.choice(pronoun) + random.choice(morenouns)
      print(phrase)
      print("Now, give it some meaning and use in the world!")

  elif quest == "English" or "english":
      verb = 
      #another list of verbs I have manually entered  
      noun = 
      #another list of nouns I have manually entered
      pronoun = 
      #another list of pronouns I have manually entered
      morenouns = 
      #another list of nouns I have manually entered
      phrase = random.choice(verb) + random.choice(noun) + random.choice(pronoun) + random.choice(morenouns)
      print(phrase)
      print("Now, invent some meaning for it and use it in the world!")
      f8 = input("Do you want to make another one? Say 'yes' if you do. ")
      if f8 == "yes" or "Yes":
          mainFunction()
      else:
          print("Thanks for playing!")
  else:
       print("Didn't quite catch that. Try again! (say yes!)")
       mainFunction()
def malif() :
   ques = input("Want to hear a funny idiom? Say 'yes' or 'no'. ")
   if ques == "yes" or "Yes":
       mainFunction()
   elif ques == "no" or "No":
       print("Wrong answer. Try again! (say yes)")
       malif()
   else:
       print("Didn't quite catch that. Say 'yes' or 'no'.")
while baseFunction :
    malif()
    mainFunction()

从本质上讲,我是在问用户是否要制作成语,为他们提供一种语言选择,为他们生成表达式,然后询问他们是否要重复该过程。当我在PyCharm中运行脚本时,它按顺序运行两个函数(即,首先是malif(),然后是mainFunction(),如我在结尾处所示),但是它并没有注意我的输入(例如if我说“不”,它无论如何都会运行mainFunction,即使我说“英语”,它也将始终以法语来执行。

我使用了本条目(Python - How to make program go back to the top of the code instead of closing)中讨论的一些技巧。我认为问题在于以自己的定义调用函数(例如,如果我对输入的“ que”(在malif()中定义)回答“ no”,则调用malif())。但是,我已经按照我所链接的问题中讨论的技巧进行了操作,但仍无法按照我希望的方式进行。我在格式化代码时是否做错了(例如,在缩进方面),或者如果我做错的事情不明显,是否有办法将函数循环回到最初问题中未建议的开头?

谢谢!

1 个答案:

答案 0 :(得分:0)

使用字符串作为输入时,首先要注意一些技巧。 Python将区分大写字母和非大写字母,因此处理字符串的一种好方法是首先lower()(或upper(),...):

示例:

ques = input("Enter Yes or No: ")
ques = ques.lower()

if ques == "yes":
    # do something
elif ques == "no": 
    # do something else
else:
    # raise error

现在,我觉得您的代码是以一种有趣的方式构建的。一个好习惯是将导入和功能与主程序分开。如果导入了模块(文件),则第一个2将被导入,而执行文件时将播放最后一个2。为此,您可以使用以下方法:

# -*- coding: utf-8 -*-
"""
docstring of the module
"""

# Imports
import random
import os

# Functions
def f():
    return "Hello world"

# Main program
if __name__ == '__main__':
    # Calling the function, taking the inputs and so on

在主程序中,处理引发异常的可能性非常有用。此外,如果使用cmd显示程序,则在出现错误时,cmd将立即关闭。此语法非常有用:

if __name__ == '__main__':
    try:
        # Do stuff

    except:
        import sys
        print (sys.exc_info()[0])
        import traceback
        print (traceback.format_exc())

    os.system("pause") # for windows, else easy way is to have an empty input to freeze the cmd

现在输入您的代码。我会这样修改:

# -*- coding: utf-8 -*-
"""
Docstring
"""

# Imports
import random
import os


# Functions
def build_a_phrase(language) :
    if language == "french":
        verb = ["vendre", "atterir", "attaquer", "jeter"]
        #list of verbs I have manually entered
        noun = ["arbre", "poisson", "chien"]
        #list of nouns I have manually entered
        pronoun = ["un", "les"]
        #list of pronouns I have manually entered
        morenouns = ["chat", "oiseau"]
        #list of nouns I have manually entered
        choices = [random.choice(verb), random.choice(noun), random.choice(pronoun), random.choice(morenouns)]
        phrase = " ".join(choices) # Add a space between the words

        return phrase

    elif language == "english":
        verb = ["...", "...", "..."]
        #another list of verbs I have manually entered  
        noun = ["...", "...", "..."]
        #another list of nouns I have manually entered
        pronoun = ["...", "...", "..."]
        #another list of pronouns I have manually entered
        morenouns = ["...", "...", "..."]
        #another list of nouns I have manually entered
        choices = [random.choice(verb), random.choice(noun), random.choice(pronoun), random.choice(morenouns)]
        phrase = " ".join(choices) # Add a space between the words

        return phrase


if __name__ == '__main__':
    try:
        # Parameters
        available_language = ["french", "english"]
        available_answers = ["yes", "no"]

        # Safety implementation of an input
        quest = ""
        i = 0
        while quest.lower() not in available_answers:
            quest = input("Want to hear a funny idiom? Say 'yes' or 'no'. ")
            i += 1
            if i == 2: # number of tries
                break

        if quest.lower() == "no":
            print ("I'm sure you meant yes.")

        language = ""
        i = 0
        while language.lower() not in available_language:
            language = input("Which language do you want it in? Type 'French' or 'English'.\n")
            i += 1
            if i == 2: # number of tries
                break

        while True:
            sentence = build_a_phrase(language)
            print (sentence)
            print ("Now, give it some meaning and use in the world!")

            f8 = ""
            i = 0
            while f8.lower()  not in available_answers:
                f8 = input("Do you want to make another one? Say 'yes' if you do. ")
                i += 1
                if i == 2: # number of tries
                    break

            if f8.lower() == "no":
                print("Thanks for playing!")
                break

    except:
        import sys
        print (sys.exc_info()[0])
        import traceback
        print (traceback.format_exc())

    os.system("pause")

希望您将从此答案中获得一些好技巧,并养成一些好习惯:) 尚未完成,当输入错误时,应该引发错误,而不是等待错误导致输入错误(例如,应放置raise语句而不是换行符)