python - 如何使用逻辑运算符

标签 python python-3.x logical-operators

我已经尝试了一切,如果你不选择“ST”,它会不断地围绕 while 循环循环。我不知道该怎么做,如果有人能告诉我,那将会非常有帮助。我在顶部添加了一些上下文的代码;我只需要 while 循环的帮助。我正在使用 while循环,所以如果他们没有选择给定的位置,他们必须重新选择。

这是我的代码:

pos = input("What Is Your Choice")

if pos == "ST":
    shot = 8
    print("Shot Is",shot)
    passing = 6
    print("Passing Is",passing)
    pace = 6
    print("Pace Is",pace)
    defending = 2
    print("Defending Is",defending)

if pos == "MID":
    shot = 6
    print("Shot Is",shot)
    passing = 6
    print("Passing Is",passing)
    pace = 6
    print("Pace Is",pace)
    defending = 4
    print("Defending Is",defending)

if pos == "DEF":
    shot = 2
    print("Shot Is",shot)
    passing = 6
    print("Passing Is",passing)
    pace = 4
    print("Pace Is",pace)
    defending = 8
    print("Defending Is",defending)

if pos == "GK":
    dive = 7
    dist = 8
    catch = 7

print(pos)

while pos != "ST" and "MID" and "DEF" and "GK" and "St" and "Mid" and 
"Def" and "Gk":
    print("What Position Do You Want To Play?")
    time.sleep(1)
    print("The Options Are..")
    time.sleep(1)
    print("ST (Striker)")
    time.sleep(1)
    print("MID (Midfielder)")
    time.sleep(1)
    print("DEF (Defender)")
    time.sleep(1)
    print("GK (Goalkeeper)")
    time.sleep(1)

pos = input("What Is Your Choice")

最佳答案

这部分是错误的:

while pos != "ST" and "MID" and "DEF" and "GK" and "St" and "Mid" and "Def" and "Gk":

pos != "ST" 被评估,其余字符串不与任何内容进行比较。事实上,该部分的评估如下:

while (pos != "ST") and ("MID") and ("DEF") and ("GK") and ("St") and ("Mid") and ("Def") and ("Gk"):

非空字符串始终为 True,因此只要 pos != "ST"True,就永远不会得到跳出循环。您可能想要做的是:

while pos != "ST" and pos != "MID" and pos != "DEF" and pos != "GK" and pos != "St" and pos != "Mid" and pos != "Def" and pos != "Gk":

但是,正如其中一条评论已经指出的那样,您可以只使用 in:

while pos not in {"ST", "MID", "DEF", "GK", "St", "Mid", "Def", "Gk"}:

请注意,我使用了 set因为他们提供了更有效的成员资格测试。在这个小例子中可能并不重要,但它仍然是一个更好的选择。

关于python - 如何使用逻辑运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53286704/

相关文章:

python - 使用 python 切割地质钻孔(csv 数据文件)以提取一些值

python - If 语句不起作用 (Python)

python - 使用streamlit Python代码找不到上传文件的路径

java - 如何检查一个值是 A 或 B,另一个值是 A 或 B?

r - 在R中同时比较多个向量?

python - 使用 Pymssql 将具有 Null 值的记录插入 SQL Server 时出错

python - 矩形类 Python

python-3.x - 在 IPython (Py 3.4) 笔记本中使用 turtle

python-3.x - 没有名为 cntk 的模块

javascript - 除非在 Perl 中相当于 !在 JavaScript 中?