[英]Python - How do I make it so that my other program only executes when an if statement is in agreement?
My program is meant to make some sort of online cookbook and depending on what I want to make, I can choose which program to execute.我的程序旨在制作某种在线食谱,根据我想要制作的内容,我可以选择执行哪个程序。 In order to finally have got it to work, the integer I type in will correspond to the code that I want to run:为了最终让它工作,我输入的 integer 将对应于我要运行的代码:
enter code here
cookbook = int(input("What recipe would you like to make? (Please state the number)\n"))
if cookbook == 1:
import mymodule as mx
mx.greeting("Nana")
a = mx.person1["age"]
print(a)
mx.omin(2)
mx.tmin(4)
mx.cmin(10)
mx.smallest(0)
else:
print("Updates pending")
It seems you want to change which python file you are going to run.您似乎想更改要运行的 python 文件。 You could do this simply by changing the namespace from the imports.您可以简单地通过更改导入的命名空间来做到这一点。
cookbook = input("What recipe would you like to make?")
if cookbook == "pepper":
import pepper as recipe # This is the name of the file I want to execute
elif cookbook == "pasta":
import pasta as recipe
recipe.run()
There can be more elegant ways to do it, and use the name itself to load the file directly, but I think this is closest to what you were trying to do.可以有更优雅的方法来做到这一点,并使用名称本身直接加载文件,但我认为这最接近你想要做的。
Here is an example with 3 files, as I understand what you are trying:这是一个包含 3 个文件的示例,因为我了解您正在尝试的内容:
cookbook.py食谱.py
cookbook = input("What recipe would you like to make? ")
if cookbook == "pepper":
import pepper as recipe
elif cookbook == "pasta":
import pasta as recipe
recipe.run()
pepper.py辣椒.py
def run():
print('\n1: Grow plant')
print('\n2: Get pepper')
pasta.py意大利面.py
def run():
print('\n1: Mix water with flour and egg')
print('\n2: Flatten')
print('\n2: Boil in water')
You then run cookbook.py
and type either 'pepper' or 'pasta'然后运行cookbook.py
并输入“pepper”或“pasta”
What helps is that instead of using words to select which option is to be imported, use numbers and tell the user that in the question.有帮助的是,不要使用单词 select 要导入哪个选项,而是使用数字并在问题中告诉用户。 Functions don't seem to be able to process user input, so input it in the code before running as in "mx.omin(2)".函数似乎无法处理用户输入,因此在运行之前将其输入到代码中,就像在“mx.omin(2)”中一样。
cookbook = int(input("What recipe would you like to make? (Please state the number)\n"))
if cookbook == 1:
import mymodule as mx
mx.greeting("Nana")
a = mx.person1["age"]
print(a)
mx.omin(2)
mx.tmin(4)
mx.cmin(10)
mx.smallest(0)
elif cookbook == 2:
import sauce as mx
mx.greeting("Nana")
mx.cabmin(0.6666)
mx.carmin(2)
mx.cookmin(200)
mx.smallest(0)
mx.confidence("OK")
mx.final("sauce")
else:
print("Updates pending")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.