【问题标题】:PyCharm Error - Name 'chicks' can be undefinedPyCharm 错误 - 名称“小鸡”可能未定义
【发布时间】:2020-06-10 17:15:25
【问题描述】:

我正在学习 Python,并遵循Tech with Tim 的教程系列,然后我编写了自己的 Python 代码,询问你喜欢什么动物,如果你有它,它是什么年龄,它的名字是什么,我收到了这个错误在 PyCharm 上。名称“小鸡”可以未定义。

我只有 7 岁,所以如果我错过了什么,请放轻松,下面是我的代码:

# variables
animal = input("What animal do you like? ")
animal_array = ["Chicks", "chicks"]
chicks_array = ["Yes", "yes"]
other_animals = [""]
yes_answer = ["Yes", "yes"]
# if statements
if animal in animal_array:
    print("Me too!")
    chicks = input("Do you have a chick? ")

else:
    print("Ok")
    animal_q = input("Do you have a/an/some " + animal + "? ")


if chicks in chicks_array:
    chick_name = input("What is your chick's name? ")
    chicks_age = input("What is your chick's age? ")


else:
    print("Ended")

【问题讨论】:

  • 问题是因为当if animal in animal_array: 评估为假时,chicks 永远不会被定义。

标签: python pycharm jetbrains-ide


【解决方案1】:

尝试在开头添加一个新变量“chicks”:

# variables
chicks = ''
animal = input("What animal do you like? ")
animal_array = ["Chicks", "chicks"]
chicks_array = ["Yes", "yes"]
other_animals = [""]
yes_answer = ["Yes", "yes"]

这样,即使你不说你有一个小鸡,变量仍然是定义的。

玩得开心学习 python!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    • 2022-01-01
    • 2015-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-02
    相关资源
    最近更新 更多