我想知道如何在python中我能够编写代码,而不是在用户输入某个输入之前执行代码,例如,
a = 1
raw_input("type a if you want to run '1'")
但不是没有&#39; 1&#39;在这个例子中,它将是代码。并且直到用户输入&#39; <#39;
才会运行好的:这是我正在进行的游戏的一部分:
balance = 2500
FinalPrice = 0
buy = input("Marijuana plants cost 200$ ea, opium seeds cost 300$")
while (buy != "o") and (buy != "m"):
buy = input("That's not on the market! type 'm' if you want to buy Marijuana and 'o' if you want opium!")
if buy =="o":
o = input("How many opium seeds? Press c to cancel")
if o =="c":
input("You cancelled the trade. Type in a command to do something else")
elif buy =="m":
m = input("How many Marijuana plants? Press c to cancel")
if m=="0":
m = input("invalid number, input again")
elif m =="c":
input("You cancelled the trade. Type in a command to do something else")
mprice = (m*200)
print(mprice)
FinalPrice-=FinalPrice
FinalPrice+=mprice
mbuy = input("This is the final price, press b to buy or c to cancel")
if mbuy =="c":
input("You cancelled the trade. Type in a command to do something else")
elif mbuy =="b":
if mprice > balance:
print("Not enough money! Sell more drugs to earn more money.")
elif mprice < balance:
print("you bought", m , "Marijuana plants for", mprice , "$")
input("What do you want to do next?"
我希望在用户输入输入时移动所有这些代码,例如&#34; buy&#34;它会执行此代码,但只有这样,当我向用户询问下一步要做什么时,我不想在每次输入后复制+粘贴它
答案 0 :(得分:0)
您想声明一个函数。
def buy():
#paste all your code in here
现在,只要您想运行该功能,您只需要调用它即可。您可以以相同的方式定义许多其他函数并调用它们,而无需复制和粘贴任何代码。
command = input("Type buy if you want to buy, and sell if you want to sell.")
if command == 'buy':
buy()
elif command == 'sell':
sell()
我强烈建议您阅读评论中已经链接的文档。将平衡和FinalPrice作为参数传递给函数并在最后返回它们是更好的编程习惯,甚至更好地为每个价格定义单独的变量,但阅读文档可能比在这里要求更多。