我的代码将不会执行if / elif部分

时间:2019-01-19 17:11:58

标签: python if-statement python-3.7

当我运行这段代码(部分代码)并且输入=输入这个词时,它将运行该代码并输入答案。但是,除了执行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

1 个答案:

答案 0 :(得分:-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()

希望有帮助