Python 在函数调用期间未调用 input()

Python input() not being called during function call

这是我为提高 Python 技能而编写的一个简单的基于文本的游戏的代码片段。 我计划使用 input_check() 来简化我稍后在项目中编写的大量代码,但目前我无法让它工作。我 运行 在带有 Pylance 扩展的最新 VS Code 大师上使用它,它不会在我的代码中标记任何错误。我已经 运行 多次测试以确保 input_check() 是问题所在,删除它并简单地 运行 多次调用代码就可以了。

import time

def rules():
  print("The rules of this game are:")
  time.sleep(0.5)
  print("rules")
  time.sleep(0.5)
  print("rules")
  time.sleep(0.5)
  print("rules")
  time.sleep(0.5)
  print("rules")
  time.sleep(0.5)
  print("rules")
  time.sleep(0.5)
  input_check("Do you understand?\n", rules(), "Ok. Starting game...")
  
def input_check(question: str, function, confirmation: str):  
  yes_no = input(question)

  if yes_no.lower() == "n" or "no":
    function
  elif yes_no.lower() == "y" or "yes":
    print(confirmation)
    time.sleep(1)
  else:
    print("Invalid input.")
    input_check(question, function, confirmation)


input_check("Do you know the rules?\n", rules(), "Ok. Starting game...") 

我几乎是 Python 的新手,所以我不知道是否采用 function 参数然后 运行 稍后在 input_check() 中将其作为函数] 是否有效,但这不是问题。

应该有一个提示 运行 define yes_no with input() 但它永远不会达到这个。相反,它似乎跳到 运行ning rules()(只有当用户输入 'no' 或 'n' 时才会发生),以及 rules() 运行s 连续直到停止,完全跳过 input_check() .

我的问题是:

  1. 为什么 input_check() 被完全忽略了?
  2. 你能 运行 将代码按原样(function 参数)作为参数吗?还是我需要额外的步骤才能做到 运行?
  3. 是否有 better/more 有效的方法来做到这一点? (例如,一个解析输入的包,避免了你自己的函数)

看看这个声明:

input_check("Do you know the rules?\n", rules(), "Ok. Starting game...")

当您这样做时,Python 将立即调用 rules 函数,因此它可以将其结果传递给 input_check。你的 rules 函数打印出一堆东西,然后有完全相同的行,它将一次又一次地调用 rules() ,一次又一次,一次又一次......它永远没有机会打电话 input_check。还在处理参数中

如果您想传递函数对象而不调用它,请不要使用括号:

input_check("Do you know the rules?\n", rules, "Ok. Starting game...")

注意input_check函数会一直调用传入的函数。您不需要在 rules.

中再次调用它

跟进

这和你想的不一样:

  if yes_no.lower() == "n" or "no":

解析为:

  if (yes_no.lower() == "n")   or "no":

并且由于“否”为真,所以 if 将始终被采纳。您应该使用其中之一:

  if yes_no.lower() in ("n" or "no"):
  if yes_no.lower()[0] == "n":

接下来,你有这个:

  if yes_no.lower() == "n" or "no":
    function

此处,您确实要调用该函数,因此需要添加括号:

  if yes_no.lower()[0] == "n":
    function()
inputCheck("Do you know the rules?\n", rules(), "Ok. Starting game...")

规则后不需要任何 parantheses(),而不是将函数作为参数传递 运行。这样写:-

inputCheck("Do you know the rules?\n", rules, "Ok. Starting game...") 

也在这里:-

if yes_no.lower() == "n" or "no":
   function

需要在函数后加(),写:-

if yes_no.lower() == "n" or "no":
  function()

如果它确实解决了问题,请告诉我

  1. 问题是您使用 rules() 作为参数来传递函数。您需要更改为:inputCheck("Do you know the rules?\n", rules, "Ok. Starting game...").

rules(): 将调用函数 rules()

规则:函数可以作为参数传递给另一个函数。

你可以来这里获取更多信息:

What is the difference between calling function with parentheses and without in python?.

注意:我看到你的示例代码有很多错误(当使用 def rules() 作为对象或函数时)。你应该学习如何调试,它会帮助你有效地修复错误

连同其他答案,我发现了另一个语义错误:您的第一个 if 语句将始终计算为真,因为它将计算 'no' 的布尔值,如下所示

if yes_no.lower() == 'n' or 'no' == True:

由于非空字符串的计算结果为真,因此该语句将始终执行。你可以添加

而不是你拥有的
yes_no.lower() == 'no'

给你

if yes_no.lower() == "n" or yes_no.lower() == "no":

使语句仅在 yes_no.lower 为 'n' 或 'no'

时才计算为真

如需进一步说明,请参阅

Why is my python if statement not working?

你得到了很多关于代码当前行为的解释,但没有 关于如何做我认为你想做的事情的很多实用建议。你不 需要来回传递规则函数。你需要最重要的 获取用户输入的工具:while-true 循环。

def game():
    if not yesno('Do you know the rules'):
        rules()
    print("Ok. Starting game ...")

def rules():
    while True:
        print("The rules of this game are ... BLAH BLAH")
        if yesno('Do you understand'):
            break

def yesno(question):  
    while True:
        yn = input(f'{question}? [yes/no]: ').lower()
        if yn in ('y', 'yes'):
            return True
        elif yn in ('n', 'no'):
            return False
        else:
            print("Invalid input.")