【问题标题】:Using elif statement "print function" not working correctly instead printing if statement's "print function" instead使用 elif 语句 \"print function\" 不能正常工作,而不是打印 if 语句\"print function\"
【发布时间】:2022-08-21 11:51:24
【问题描述】:

我正在尝试制作一个选择工具来选择我的下一个动漫,我使用随机包来选择下一个要观看的动漫,这可以正常工作我的问题在于以下我想为所选节目添加描述,例如,如果它选择 show b 我想知道它是关于什么的。当前的问题是 elif 语句中的打印功能不起作用,而是一直选择第一个的描述。

import random

print(\"Project Select\")
print(\"\")
#for future me
print(\"Summary Of Project: This Project Has The Goal To Help Select What Anime I Should Watch Next\")
print(\"\")
Anime = [\"Black Bullet\",\"Princess Connect\",\"Overlord\",\"Date A Live\", \"Chivalry of a failed knight\", \"The Detective Is Already Dead\",
\"Shimoneta\", \"I\'m Quitting Heroing\",\"The Greateast Mage\"]

selector = random.choice(Anime)

print(selector)

if(\"Black Bullet\"):
    print(\"Banana 1\")
elif(\"Princess Connect\"):
    print(\"Watermelon 2\")
elif(\"Overlord\"):
    print(\"Strawberry 3\")
elif(\"Date A Live\"):
    print(\"kiwi 4\")
elif(\"Chivalry Of A Failed Knight\"):
    print(\"apple 5\")
elif(\"The Detective Is Already Dead\"):
    print(\"blueberry 6\")
elif(\"Shimoneta\"):
    print(\"lemon 7\")
elif(\"I\'m Quitting Heroing\"):
    print(\"cherry 8\")
else:
    print(\"orange 9\")
  • 这不是 if-elif-else 语句的语法工作方式。我相信您需要先查找一些非常基本的 Python 语法。
  • \"Black Bullet\" 是一个长度非零的字符串,因此是真实的,所以if 分支将始终被采用。您是否打算与selector(即if selector == \"Black Bullet\":)进行比较?
  • @MilesBudnek 我不打算这样做,但感谢您指出它解决了问题,对不起,如果这是一个愚蠢的帖子,这是我第一次将 python 用于非学习目的。
  • 这是关于该主题的可能教程之一:favtutor.com/blogs/python-switch-case
  • 或者可能OP应该调查结构模式匹配。

标签: python python-3.x if-statement random printing


【解决方案1】:

您需要像这样使用== 运算符:

import random

print("Project Select")
print("")
#for future me
print("Summary Of Project: This Project Has The Goal To Help Select What Anime I Should Watch Next")
print("")
Anime = ["Black Bullet","Princess Connect","Overlord","Date A Live", "Chivalry of a failed knight", "The Detective Is Already Dead",
"Shimoneta", "I'm Quitting Heroing","The Greateast Mage"]

selector = random.choice(Anime)

print(selector)

if selector == "Black Bullet":
    print("Banana 1")
elif selector == "Princess Connect":
    print("Watermelon 2")
elif selector == "Overlord":
    print("Strawberry 3")
elif selector == "Date A Live":
    print("kiwi 4")
elif selector == "Chivalry Of A Failed Knight":
    print("apple 5")
elif selector == "The Detective Is Already Dead":
    print("blueberry 6")
elif selector == "Shimoneta":
    print("lemon 7")
elif selector == "I'm Quitting Heroing":
    print("cherry 8")
else:
    print("orange 9")

这就是您的代码不起作用的原因:

对于 if - elif 语句,您有:

if("Black Bullet"):
    print("Banana 1")
elif("Princess Connect"):
    print("Watermelon 2")
elif("Overlord"):
    print("Strawberry 3")
elif("Date A Live"):
    print("kiwi 4")
elif("Chivalry Of A Failed Knight"):
    print("apple 5")
elif("The Detective Is Already Dead"):
    print("blueberry 6")
elif("Shimoneta"):
    print("lemon 7")
elif("I'm Quitting Heroing"):
    print("cherry 8")
else:
    print("orange 9")

这告诉 Python:“如果"Black Bullet" 的布尔值等于True,则执行print("Banana 1"),否则,如果布尔值...”等等。

字符串的布尔值为False 的唯一方法是当字符串为空时,所以你明白为什么代码只打印Banana 1

【讨论】:

    【解决方案2】:

    这是 Python 3.x(简称 Python3)的语法示例。顺便说一句,您有错字“失败骑士的骑士精神”应该是“失败骑士的骑士精神”

    import random
    
    print("Project Select")
    print("")
    #for future me
    print("Summary Of Project: This Project Has The Goal To Help Select What Anime I Should Watch Next")
    print("")
    Anime = ["Black Bullet", "Princess Connect", "Overlord", "Date A Live", "Chivalry Of A Failed Knight", "The Detective Is Already Dead",
    "Shimoneta", "I'm Quitting Heroing", "The Greateast Mage"]
    
    selector = random.choice(Anime)
    
    print(selector)
    
    if selector == "Black Bullet":
        print("Banana 1")
    elif selector == "Princess Connect":
        print("Watermelon 2")
    elif selector == "Overlord":
        print("Strawberry 3")
    elif selector == "Date A Live":
        print("kiwi 4")
    elif selector == "Chivalry Of A Failed Knight":
        print("apple 5")
    elif selector == "The Detective Is Already Dead":
        print("blueberry 6")
    elif selector == "Shimoneta":
        print("lemon 7")
    elif selector == "I'm Quitting Heroing":
        print("cherry 8")
    elif selector == "The Greateast Mage":
        print("orange 9")
    else:
        print("Not Found!")
    

    输出:

    Project Select
    
    Summary Of Project: This Project Has The Goal To Help Select What Anime I Should Watch Next
    
    The Detective Is Already Dead
    blueberry 6
    

    如果字符串不是 ("") 为空,则 if 语句将给出真值。例如:

    if("helloworld"):
        print("yes")    #yes
    
    if(""):
        print("yes")    #no output
    

    【讨论】:

      【解决方案3】:

      这个问题是你的第一个if 语句将始终评估为True,并导致该块内缩进的代码运行。非空字符串计算为True

      >>> bool("")
      False
      >>> bool("hello")
      True
      

      要解决您的问题,您需要检查selector 的相等性,这将包含random.choice(Anime) 返回的任何内容。这是一个简单的例子:

      >>> import random
      >>> def foo(lst):
      ...     rand = random.choice(lst)
      ...     if rand == 1:
      ...         print("1 is the element")
      ...     elif rand == 2:
      ...         print("2 is the element")
      ...     elif rand == 3:
      ...         print("3 is the element")
      ...
      >>> foo([1, 2, 3])
      1 is the element
      >>> foo([1, 2, 3])
      2 is the element
      >>> foo([1, 2, 3])
      2 is the element
      >>> foo([1, 2, 3])
      1 is the element
      >>> foo([1, 2, 3])
      3 is the element
      

      【讨论】:

        【解决方案4】:

        作为所提供答案的替代方案,您可能希望使用字典将名称与食物相关联。

        assoc = {
          'Black Bullet':                  'Banana 1',
          'Princess Connect':              'Watermelon 2',
          'Overlord':                      'Strawberry 3',
          'Date A Live':                   'kiwi 4',
          'Chivalry Of A Failed Knight':   'apple 5',
          'The Detective Is Already Dead': 'blueberry 6',
          'Shimoneta':                     'lemon 7',
          'I\'m Quitting Heroing':         'cherry 8'
        }
        

        现在您可以简单地:

        print(assoc.get(selector, 'Not found!'))
        

        使用assoc.get(selector, 'Not found!') 而不是assoc[selector] 可以让我们提供一个默认值,以便在字典中找不到索引时返回,从而替换 if/elif/else 语句中的else

        如果您需要获取所有名称,则可以使用:

        list(assoc.keys())
        

        【讨论】: