如何在 'if' 语句中使用多个 'or' 布尔运算符来执行 python 中的不同类型的任务?[复制]

How to use multiple 'or' Boolean operators in an 'if' statement to carry out different types of tasks in python? [duplicate]

提问人:LukeWantsToAskAQuestion 提问时间:2/19/2023 最后编辑:LukeWantsToAskAQuestion 更新时间:2/19/2023 访问量:58

问:

我真的不知道这个问题怎么说,但我希望“h”或“j”或“k”输入显示它们各自的值

from pynput.keyboard import Key, Controller
import time
import random

keyboard = Controller()

wasd = ["w","a","s","d","j","h","k"]

for x in range(1,11):
    if wasd[random.randint(0,6)] == "w":
        keyboard.press("w")
        time.sleep(0.5)
        keyboard.release("w")
    elif wasd[random.randint(0,6)] == "a":
        keyboard.press("a")
        time.sleep(1)
        keyboard.release("a")
    elif wasd[random.randint(0,6)] == "s":
        keyboard.press("s")
        time.sleep(0.1)
        keyboard.release("s")
    elif wasd[random.randint(0,6)] == "d":
        keyboard.press("d")
        time.sleep(1)
        keyboard.release("d")
    elif wasd[random.randint(0,6)] == "h" or "j" or "k":
        keyboard.press("h" or "j" or "k")
        time.sleep(0.03)
        keyboard.release("h" or "j" or "k") 

这是代码,这是输出:shdhswhhhh

因此,每当它 h、j 或 k 时,它只键入 h

python-3.x if-statement 布尔逻辑

评论

1赞 Maurice Meyer 2/19/2023
elif wasd[random.randint(0,6)] in "hjk":
0赞 slothrop 2/19/2023
elif wasd[random.randint(0,6)] in "hjk": keyboard.press("h" or "j" or "k")?

答:

0赞 codester_09 2/19/2023 #1

在您提供的代码中,以下行不正确:

elif wasd[random.randint(0,6)] == "h" or "j" or "k":

这行代码始终为 True,因为“j”和“k”是 Python 中考虑的非空字符串。因此,此条件下的代码块每次都会执行,并且始终键入“h”。True

若要解决此问题,可以将该行更改为:

elif wasd[random.randint(0,6)] in ["h", "j", "k"]:

此代码将检查 中的随机元素是否来自 。如果是,则将执行此条件下的代码块,并键入相应的字符。wasd

此外,keyboard.press(“h” 或 “j” 或 “k”) 将始终按 “h”。

所以你可以把它改成


keyboard.press(random.choice(["h", "j", "k"]))


OP 的评论“如果 [”h“, ”j“, ”k“] 中的 wasd[random.randint(0,6)] 的结果是 'k',那么它不会从 keyboard.press(random.choice([”h“, ”j“, ”k“])) 中重新选择另一个字母,使第一个选择变得多余吗?

为此,只需将您的随机选择值保存在这样的变量中即可

for x in range(1,11):
    randomChoice = wasd[random.randint(0,6)]
    if randomChoice == "w":
        keyboard.press("w")
        time.sleep(0.5)
        keyboard.release("w")
    elif randomChoice == "a":
        keyboard.press("a")
        time.sleep(1)
        keyboard.release("a")
    elif randomChoice == "s":
        keyboard.press("s")
        time.sleep(0.1)
        keyboard.release("s")
    elif randomChoice == "d":
        keyboard.press("d")
        time.sleep(1)
        keyboard.release("d")
    elif randomChoice == "h" or "j" or "k":
        keyboard.press(randomChoice)
        time.sleep(0.03)
        keyboard.release(randomChoice) 

问题2.random.choice有什么用?

答。它是一个从给定序列中选择随机值的函数。

评论

0赞 LukeWantsToAskAQuestion 2/19/2023
对不起,这个愚蠢的问题,但事情是干什么用的?而且,它不会重新洗牌选择吗,例如,如果结果来自“k”,那么它不会从 中重新选择另一个字母,使第一个选择变得多余吗?random.choicewasd[random.randint(0,6)] in ["h", "j", "k"]keyboard.press(random.choice(["h", "j", "k"]))