python - 如何将我自己的函数放在 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,而无需全部运行。
解决方案
因为这里错误使用了 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)
推荐阅读
- arrays - 将整数数字拆分为数组帕斯卡
- binary - 在 bin 文件中搜索字节并找到地址?网络
- python - 如何将新行附加到 Dataframe 的特定列并用 Nan 填充缺失值
- typescript - 来自模式的打字稿类型
- emacs - Dired 与 015(八进制?)一起出现
- javascript - 使用 vanilla javascript 使用 parcel-bundler 解决延迟加载图像
- reactjs - Typescipt:用于在反应中设置默认道具的交集
- vb.net - 超链接控件:索引超出了数组的范围
- javascript - Javascript:计算数组中所有对象值的总和
- windows - 如何使用 Powershell 暂停另一个进程