Skip to main content
 首页 » 编程设计

python之If/Else 语句期间 Python 输入中单词的同义词

2025年05月04日15zhoujg

我正在编写一个基于文本的游戏,我要求用户在 python 中转向不同的方向。我想设置它以便可以使用选项的同义词/变体(例如“Right”或“right”或“r”或“R”)但不想运行它在每个 if/else 语句中。我已尝试将每个可能的选项设为一个变量:

left = "Left" or "left" or "l" or "L" 
right = "Right" or "right" or "r" or "R" 
forward = "Forward" or "forward" "f" or "F" 
axe = "Axe" or "axe" or "a" or "A" 
sword = "Sword" or "sword" 
slingshot = "Slingshot" or "slingshot" 
yes = "Yes" or "yes" or "y" or "Y" 
no = "No" or "no" or "n" or "N" 

然后我尝试在输入后放入 if/else 语句时调用它:

def section1(): 
 
  #If the person does want to go forward 
  def confirm(): 
    con = input("Are you absolutely sure you want to go this way? ") 
    if con == no: 
      print("You have gone back") 
      time.sleep(0.75) 
      section1() 
    elif con == yes: 
      section1b() 
    else: 
      print("Sorry I didn't get that") 
      time.sleep(0.75) 
      confirm() 
 
  direction = input('What way would you like to go? Right, or forward? ') 
  if direction == forward: 
    print("WARNING! This direction is well known for the great danger that make await where death is inevitable!") 
    confirm() 
  elif direction == right: 
    print("You begin your journey down the creepy corners and dark alleys.") 
    time.sleep(1) 
    section2() 
  else: 
    print("That's not an option") 
    section1() 
 
    direction = input('What way would you like to go? Right, or forward? ') 
    if direction == forward: 
        print("WARNING! This direction is well known for the great danger that make await where death is inevitable!") 
        confirm() 
    elif direction == right: 
        print("You begin your journey down the creepy corners and dark alleys.") 
        time.sleep(1) 
        section2() 
    else: 
        print("That's not an option") 
        section1() 

虽然当我运行代码并输入“right”或“forward”时,它会转到 else 语句并打印“That's not an option”然后循环返回。是否有另一种方法可以让我获取同义词(我已经尝试过将同义词列为一个列表),还是我的语法不正确?

请您参考如下方法:

Python 不是那样工作的。当 Python 执行行时 -

left = "Left" or "left" or "l" or "L" 

它执行 bool 表达式 "Left"或 "left"or "l"或 "L" 并将其结果存储在 left 中,即该 bool 表达式的结果将是 Left ,所以 left 然后指向字符串 "Left"。它不会延迟 bool 表达式的计算。向您展示的示例 -

>>> left = "Left" or "left" or "l" or "L" 
>>> left 
'Left' 

您应该创建一个集合(因为您会一直搜索这些集合,并且集合为每个 left 和 right 提供恒定时间搜索(O(1) )) 等,并改用它。示例 -

left = set(["Left","left","l","L"]) 
right = set(["Right","right","r","R"]) 

使用 in 运算符 -

if direction in forward: 

和

elif direction in right: