为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

梦里花落0921 2021-09-28 20:35:53
我正在尝试制作一个简单的二十一点游戏,我希望能够创建自己的功能,这已经可以做到,然后将其放在 if 语句中,以便如果用户想要“站立”,则它运行该功能“站立”。但是,当 python 读取代码时,即使用户说“命中”,它也会看到所有函数并运行所有函数。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 ("stand"):        stand()    if step == ("Hit") or ("hit"):        hit()    if step == ("Double down") or ("down"):        doubledown()    else:        step()step()我希望用户能够一次运行 'Hit'、'double down' 或 'stand' 功能 1,而无需所有这些功能都运行。
查看完整描述

2 回答

?
守候你守候我

TA贡献1802条经验 获得超10个赞

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 step== "stand"):

        stand()

    elif (step == "Hit" or step=="hit"):

        hit()

    elif (step == "Double down" or step=="down"):

        doubledown()

    else:

        step()

step()

问题在于 if 语法。


查看完整回答
反对 回复 2021-09-28
?
九州编程

TA贡献1785条经验 获得超4个赞

因为在这里错误地使用了 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) 一样改变你的代码


查看完整回答
反对 回复 2021-09-28
  • 2 回答
  • 0 关注
  • 247 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号