对我来说,在脚本中有代码但在被要求之前不运行是一种什么方法?

2024-10-01 17:27:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道,在python中,我如何能够编写代码,并且在用户输入某个输入之前不执行它,例如

a = 1
raw_input("type a if you want to run '1'")

但在本例中,它不是“1”,而是代码。在用户输入“a”之前不运行

好的:这是我游戏的一部分:

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?"

我想移动所有的代码,当用户输入一个输入,例如“买”它执行这个代码,但只有这样,我不想复制+粘贴它后,每次输入,当我问用户他们想做的下一步


Tags: theto代码用户youinputifbuy
1条回答
网友
1楼 · 发布于 2024-10-01 17:27:54

您想声明一个函数

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()

我强烈建议您阅读评论中已经链接的文档。更好的编程实践是将balance和FinalPrice作为参数传递到函数中并在最后返回它们,甚至更好的实践是为每个价格定义单独的变量,但是阅读文档可能比在这里询问更有帮助

相关问题 更多 >

    热门问题