【问题标题】:my code will not execute the if/ elif part in this我的代码不会执行 if/elif 部分
【发布时间】:2019-01-19 17:11:57
【问题描述】:

当我运行这段代码(其中的一部分)并得到单词 = 输入时,它会运行它并让我输入我的答案。但不是执行 if / elif 代码,而是说退出代码 0。我不明白为什么会这样,所以请帮忙。我试图在这里和那里删除代码,但它什么也没改变。

rand1 = random.randint(1, 2)
rand2 = random.randint(1, 4)
rand = random.randint(1, 1)
word = input("use a word that is 1-10 letters on a space, type a number 1 -    100 for the space: ")
if rand == "1":
    print("randomly generating")
elif rand1 == "1":
    a1 = word[0]
    a2 = word[1]
    a3 = word[2]
    a4 = word[3]
    a5 = word[4]
    a6 = word[5]
    a7 = word[6]
    a8 = word[7]
    a9 = word[8]
    a10 = word[9]
    letters()

这只是一部分,因为整个代码太长,无法在这里发布

这里是字母enter image description here

【问题讨论】:

  • 想想rand是什么类型,"1"是什么类型。它们是一样的吗?
  • 1 != "1",你永远不会让字符串等于整数。
  • 您可能不想处理ifelif 中的两个不同 案例吗?或者如果不是:只需删除 elif-line...
  • 在 elif 之后还有更多我没有显示的内容
  • 但是你显示的 elif 永远不会运行

标签: python if-statement python-3.7


【解决方案1】:

原因是 rand 生成一个整数,而您将它与字符串进行比较。

还有

if rand == "1":
    print("randomly generating")
elif rand1 == "1":
    a1 = word[0]
    a2 = word[1]
    a3 = word[2]
    a4 = word[3]
    a5 = word[4]
    a6 = word[5]
    a7 = word[6]
    a8 = word[7]
    a9 = word[8]
    a10 = word[9]
    letters()

此代码似乎不合逻辑,因为 if 将始终运行为 rand 将始终等于 1,而 elif 将永远不会运行。这就像说不做就做某事:) rip English

尝试使用

if rand == "1":
    print("randomly generating")
    if rand1 == "1":
        a1 = word[0]
        a2 = word[1]
        a3 = word[2]
        a4 = word[3]
        a5 = word[4]
        a6 = word[5]
        a7 = word[6]
        a8 = word[7]
        a9 = word[8]
        a10 = word[9]
        letters()

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-26
    • 2021-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多