0

我最近开始编写一个 Python 程序,我想在其中“引导”用户完成所有答案。我认为最好的表达方式是举一个例子:

因此,假设我有一份调查问卷,其中有 2 个问题,但只有在用户回答之前的问题时才能询问这些问题:

  • Q1:您是 18 岁或以上吗?
  • A1:是的(重定向到问题二
  • A1:否(*重定向到说明用户不能参与问卷调查的文字)

我也在尝试用它做更多的事情。我的完整计划是:

有一个初始问题,询问用户想要使用三个功能中的哪一个。

  • 第一个功能:检查用户是否可以申请(年龄、状态等)
  • 第二个功能:列出申请的步骤
  • 第三个功能:提供问答列表。

到目前为止,我编写的代码仅针对第一个函数,并且有很多错误(我以前从未编写过代码)。

  • 您如何以适合我想要做的整个方案的方式格式化此编码?
  • 我如何做到这一点,以便每当用户犯错(不输入 y 或 n)时它不会崩溃,而是循环回到问题?

到目前为止我的代码:

print ("Answer all yes or no questions with Y or N")
while True:
  idade = input("Are you over 18? Y/N")
  if idade.lower() not in ('y', 'n'):
    print("Answer only with Y or N")
  else:
    if idade == "Y" or idade == "y":
      crime = input("Have you ever been arrested or convicted before?")
    if idade == "N" or idade == "n":
      print("Sorry, you can't apply. ")
  if crime.lower() not in ('y', 'n'):
      print("Answer only with Y or N")
  else:
     if crime == "Y" or crime == "y":
      print("Sorry, you can't apply. ") 
     if crime == "N" or crime == "n":
      visto = input("Do you have visa TYPE_A'? ")
  if visto.lower() not in ('y', 'n'):
    print("Answer only with Y or N")
  else:
        if visto == "Y" or visto == "y":
          print("THAT'S AS FAR AS I'VE GONE")
        if visto == "N" or visto == "n":
          print("THAT'S AS FAR AS I'VE GONE")
          break
4

3 回答 3

1
def valid_input(message):
  inp = input(message)
  while inp.lower() not in ('y','n'):
    inp = input('Please input "y" or "n" only. ' + message)
  return inp.lower() == 'y' # So the return value is simply True or False


print ("Answer all yes or no questions with Y or N.")
while True:
  idade = valid_input("Are you over 18? Y/N: ")
  if not idade:
    print('Sorry, you can\'t apply.')
    break
  crime = valid_input("Have you ever been arrested or convicted before? Y/N: ")
  if crime:
      print("Sorry, you can't apply. ") 
      break
  else:
    visto = valid_input("Do you have visa TYPE_A'? ")
    if visto:
      print("THAT'S AS FAR AS I'VE GONE")
      break
    else:
      print('You don\'t have that visa type.')
      break

To "remember" previous values, simply reuse the variable name. Example:

question = valid_input('Question: ')
another_question = valid_input('Another: ')
if question:
    # Do stuff
    if another_question:
        # Do other stuff
于 2019-12-16T15:26:54.363 回答
0

如果我是你,我会设置一个函数。

def q(question):
    answer = input(question).lower()
    if 'y' is answer:
        return True
    elif 'n' is answer:
        return False
    else
        print('invalid input')
        return q(question)

您的代码可以随时调用此函数,并将返回 true 或 false。如果用户输入“y”则为真,如果输入“n”则为假。如果两者都没有输入,则再次调用该函数。然后可以像这样调用该函数:

if q('Are you 18? (N/Y)'):
    if q("Have you ever been arrested or convicted before?"):
        #and so on
if q()#input question in here if the user isn't over 18 

然后,您可以像上面那样“嵌套”您的问题。

于 2019-12-16T15:22:38.083 回答
0

我想这可能有点过头了,但我认为这是一个很好的使用字典来创建一个相互关联的问题系统。这个解决方案的好处是,如果您需要重复一个问题或类似的问题,您不必输入两次相同的内容。它也很容易扩展,看起来很干净。

字典questions使用问题的名称作为它的键。第一个问题始终是"START",但您可以根据需要更改此问题。每个问题都是它自己的字典,允许您打印文本、提示、可能的操作,还可以决定选择某个答案时会发生什么。

  • "text"如果您想告诉用户一些不是问题的内容,则使用该键,并首先执行。您可以使用"text"and "prompt",尽管这可能不是必需的。
  • "prompt"就是问题所在。
  • "y"如果选择了该答案,"n"则是您想要回答的问题的名称。

  • "action"用于告诉程序在提出问题时是否有需要做的事情。我实施的唯一行动是结束问卷。

要运行程序,请调用exec_questions(questions)questions您的字典在哪里。

questions = {
    'START':
        {
            'prompt':'Are you 18 or over?',
            'y':'q2',
            'n':'fail'
        },
    'q2':
        {
            'prompt':'Have you ever been arrested or convicted?',
            'y':'fail',
            'n':'q3'
        },
    'q3':
        {
            'prompt':'Do you have a visa TYPE_A?',
            'y':'q4',
            'n':'fail'
        },
    'q4':
        {
            'text':'THAT\'S AS FAR AS I\'VE GONE',
            'action':'end'
        },
    'fail':
        {
            'text':'Sorry, you can\'t apply',
            'action':'end'
        }
}

def exec_questions(questions):
    print("Please answer all questions using y/n")

    this_question = questions['START']
    while True:
        if 'text' in this_question.keys():
            print(this_question['text'])

        if 'action' in this_question.keys():
            if this_question['action'] == 'end':
                return

        if 'prompt' in this_question.keys():
            while True:
                res = input(this_question['prompt']+"\n > ").lower()
                if not res.lower() in ('y','n'):
                    print("Please type y/n")
                    continue
                break

            this_question = questions[this_question[res]]

exec_questions(questions)  
于 2019-12-16T16:53:31.677 回答