为什么 `letter=="A" or "a"` 始终为真?

1 投票
6 回答
540 浏览
提问于 2025-04-16 08:05

请看一下这段代码。我正在用一个机器人车来画字母,在这段代码中,当我输入小写字母b时,它却还是画出了小写字母a。

import create

# Draw a:
def drawa():
 #create robot
 robot = create.Create(4)
 #switch robot to full mode
 robot.toFullMode()
 for i in range(1280):
  robot.go(20,30)
 robot.stop()
 robot.move(-40,20)

# Draw b:
def drawb():
 #create robot
 robot = create.Create(4)
 #switch robot to full mode
 robot.toFullMode()
 robot.move(-100,20)
 for i in range(1270):
  robot.go(20,-30)
 robot.stop()

# Draw c:
def drawc():
 #create robot
 robot = create.Create(4)
 #switch robot to full mode
 robot.toFullMode()
 for i in range(700):
  robot.go(20,30)
 robot.stop()

# Define Main Function
def main():
 # While loop
 while(True):
  # Prompt user to enter a letter
  letter = raw_input("Please enter the letter you want to draw: ")
  # If user enters the letter a, draw a
  if letter=="A" or "a":
   drawa()
  # If user enters the letter b, draw b
  elif letter=="B" or "b":
   drawb();
  # If user enters the letter c, draw c
  elif letter=="C" or "c":
   drawc();
  # If user enters anything other than a letter from a-z,
  # ask them to enter a valid input
  else:
   print("Please enter a letter from a-z.")

main()

请帮帮我。

6 个回答

0
 if letter in ('A', 'a'):
  drawa()
 # If user enters the letter b, draw b
 elif letter in ('B', 'b'):
  drawb()

你应该这样写,原因已经说明了。请注意,最好用一个元组 ('A', 'a'),而不是用列表。

1

这段代码 if letter=="A" or "a": 是不对的。正确的写法应该是 if letter == "A" or letter == "a":

你的代码实际上是在判断 if yourcondition or True(在布尔上下文中,非空字符串被认为是true),这基本上就等于 if True

其他的if条件也是一样的道理。

8

这是因为你的条件设置的问题。当你说...

if letter == "A" or "a"

...实际上你是在说...

if it's true that 'letter' equals 'A', or is true that 'a'

...而且 "a" 作为一个非空字符串,总是被认为是对的。你在 or 的右边并没有对 letter 提出任何要求。你可以这样做:

if letter == "A" or letter == "a"

或者,因为我们在用 Python:

if letter in ["A", "a"]

祝好运!

撰写回答