猿问

如何将我自己的函数放在 if 语句中?

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


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,而无需所有这些功能都运行。


梦里花落0921
浏览 248回答 2
2回答

守候你守候我

def stand():    print("You have chosen to Stand")    #my stand code will go heredef hit():    print("You have chosen to Hit")    #my Hit code will go heredef doubledown():    print("You have chosen to Double Down")    #my Double Down code will go heredef step():    step = input("What would you like to do now? Stand, Hit or Double Down")    if (step == "Stand" or step== "stand"):        stand()    elif (step == "Hit" or step=="hit"):        hit()    elif (step == "Double down" or step=="down"):        doubledown()    else:        step()step()问题在于 if 语法。

九州编程

因为在这里错误地使用了 if 语句,例如“if step == ("Hit") or ("hit"):” python 将执行 step==("Hit") 并且根据用户输入结果为 False 或 True但它跟随字符串“hit”python 会像 True 一样读取它,所以最后,它就像“if (step==(“Hit”)) or (True) ,那么你的每一个 if 语句都会被执行,因为逻辑上是 True !你应该像 if (step==sth) 或 (step==sth) 一样改变你的代码
随时随地看视频慕课网APP

相关分类

Python
我要回答