我正在尝试制作一个简单的二十一点游戏,我希望能够创建自己的函数(一个已经可以做到),然后将其放在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()
我希望用户能够一次运行“击打”,“双击”或“站立”功能1而无需全部运行。
答案 0 :(得分:0)
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语法上。
答案 1 :(得分:0)
因为此处错误地使用了if语句,例如“ if step ==(“ Hit”)或(“ hit”):” python将执行step ==(“ Hit”),根据用户输入结果为False或True,但它跟随字符串“ hit”,python将读取为True,因此,最后,就像“ if(step == (“ Hit”))或(True),那么您的所有if语句都将执行,因为逻辑上为True!
您应该像这样更改代码 如果是(step == sth)或(step == sth)