python程序未按预期打印

2024-04-19 00:17:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些基本的代码,不明白为什么它不会打印。 我没有得到任何错误,但打印总数不打印任何东西,甚至0。有人能解释给我吗

def dashcount(x):
    x.split(' ')
    for num in x:
        total = 0
        if num == "0" or num == "6" or num == "9":
            total += 6

        elif num == "1":
            total += 2

        elif num == "2" or num == "3" or num == "5":
            total += 5

        elif num == "4" or num == "7":
            total += 4

        elif num == "8":
            total += 7
    return total
    print total

dashcount("1234")

Tags: or代码inforreturnifdef错误
2条回答
return total

这完全是你的职责。return语句后面的任何行都将被忽略

确保在return之前print

您还应该删除x.split(" ")。它现在什么也没做

return语句退出函数,print为什么不能执行。可以将print移到函数中,也可以将print dashcount("1234")移到函数中

此外,x.split(' ')什么都不做(但也不是必需的,因为您要用for num in x迭代每个数字)。您还应该将total = 0移动到循环前面

相关问题 更多 >