想知道为什么这段代码会导致语法错误? [关闭]

不知道为什么这段代码会导致语法错误,有人知道为什么吗?

  # Ask for user input
    choice = input ("Enter the letter A or B: ")

    # Detect choice
    if choice == A:
        print ("You entered A!")
    elif choice == B:
        print ("You enetered B")
    else:
        print ("You didn't enter A or B!")
评论
  • eomnis
    eomnis 回复

    You try to tell him if choice == A. This means that A is a variable, and if A is not defined, it will not work ! You forgot to put 2 " to make it a string, and then to be able to compare it. So now your code looks like:

      # Ask for user input
        choice = input ("Enter the letter A or B: ")
    
        # Detect choice
        if choice == "A":
            print ("You entered A!")
        elif choice == "B":
            print ("You enetered B")
        else:
            print ("You didn't enter A or B!")
    

  • 网名已过期
    网名已过期 回复

    由于输入存储为字符串,因此需要将其与字符串进行比较:

    if choice == 'A':
        print ("You entered A!")
    elif choice == 'B':
        print ("You enetered B")
    else:
        print ("You didn't enter A or B!")
    

  • hquia
    hquia 回复

    您必须写“ A”和“ B”而不是A和B。引号之间的单词是一个字符串,没有引号的是变量。您写入选择变量的是一个字符串