首页 > 解决方案 > 如何将我自己的函数放在 if 语句中?

问题描述

我正在尝试制作一个简单的二十一点游戏,我希望能够创建我自己的函数,a 已经可以做到,然后将它放在 if 语句中,这样如果用户想要“站立”,那么它就会运行该函数“站立”。但是,当 python 读取代码时,即使用户说“Hit”,它也会看到所有函数并运行所有函数。

def stand():
    print("You have chosen to Stand")
    #my stand code will go here
def hit():
    print("You have chosen to Hit")
    #my Hit code will go here
def doubledown():
    print("You have chosen to Double Down")
    #my Double Down code will go here
def step():
    step = input("What would you like to do now? Stand, Hit or Double Down")
    if step == ("Stand") or ("stand"):
        stand()
    if step == ("Hit") or ("hit"):
        hit()
    if step == ("Double down") or ("down"):
        doubledown()
    else:
        step()
step()

我希望用户能够一次运行“Hit”、“double down”或“stand”功能 1,而无需全部运行。

标签: pythonfunctionif-statementstatementsblackjack

解决方案


因为这里错误使用了 if 语句,例如“if step == ("Hit") or ("hit"):” python 会执行 step==("Hit") 并且结果为 False 或 True 取决于用户输入但它遵循字符串“hit” python 会像 True 这样读取它,最后,它就像“if (step==(“Hit”)) 或 (True) ,那么你的每个 if 语句都会被完成,因为逻辑上是 True !

您应该更改代码,例如 if (step==sth) 或 (step==sth)


推荐阅读