[英]How do I run a function from an input before the code for the function has been read?
I am writing a game, similar to mastermind, and I want a choice bewteen an easy or hard version. 我正在写一个类似于mastermind的游戏,我想选择一个简单或困难的版本。 I'm not sure how to do this as I need the question before the actual game starts but then there's an error because the function is being called to run before it has been assigned.
我不确定如何执行此操作,因为在实际游戏开始之前我需要一个问题,但是会出现错误,因为在分配功能之前调用了该函数。
def difficulty():
difficulty = input("would you like to the easy or hard version?")
if difficulty == ("easy"):
easy()
elif difficulty == ("hard"):
hard()
difficulty()
This is the start then after is the function with the harder game code then the easier game code. 这是开始,然后是具有较难的游戏代码然后较容易的游戏代码的功能。 I am trying to run the easy if they request easy and vice versa but the easy () and hard() don't run the code as it isn't assigned yet.
如果他们要求easy,我试图运行easy,反之亦然,但是easy()和hard()不会运行代码,因为尚未分配代码。 I think this is because python reads the code from top to bottom and stops when it finds an error but not sure.
我认为这是因为python从上至下读取代码,并在发现错误但不确定时停止。
I have never used this before so I apologise if things are unclear or I have done some things wrong. 我以前从未使用过它,所以如果事情不清楚或做错了事,我深表歉意。
I am also relatively new to python. 我也是python的新手。
If anybody could help me I would greatly apprectiate it. 如果有人可以帮助我,我将不胜感激。
Python is quite smart when it comes to identifying functions inside a module. 在识别模块内部的函数时,Python非常聪明。 For instance you could do this:
例如,您可以这样做:
def x():
y()
def y():
print("Y")
x()
and it would execute correctly. 它将正确执行。
You are right about the execution of a code block that happens from top to bottom, as well as the definitions of those functions will also be constructed top to button, but executed afterwards. 您对从上到下执行的代码块的执行是正确的,并且这些功能的定义也将自上而下地构造,但随后将执行。
I see some issues in your code. 我在您的代码中看到了一些问题。
difficulty = input("would you like to the easy or hard version?")
but at the same time you have a function called def difficulty
. difficulty = input("would you like to the easy or hard version?")
但同时您有一个名为def difficulty
的函数。 There is a conflict there, try to rename that variable. ("easy")
, it's overkill, you can compare directly to "easy"
. ("easy")
,这太过分了,您可以直接将其与"easy"
进行比较。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.