在Python中,if / else语句的'else'子句永远不会触发

时间:2014-12-03 19:19:25

标签: python

我是Python的初学者。我无法在此代码中获得最后的else语句:

for row in result:
    how_many = len(row)
    for num in range(0, how_many):
        pprint(" row: " + str(num))
        c_as_str = str(row[num])
        print(c_as_str)    
        if num == 9: 
            if c_as_str != '':
                c = json.loads(c_as_str)  
                pprint(c)
        else: 
            print(" here is the row: ")
            pprint(c_as_str)

我从数据库中取出行。第10列(索引9)是一些存储为字符串的JSON。所以对于那一行,我需要将其转换为JSON。对于所有其他字符串,我只想将它们打印为字符串。

最后的其他声明永远不会发生。为什么?每行有15列。我希望其中14个列将在else语句中打印,但它永远不会发生。可以

1 个答案:

答案 0 :(得分:1)

我认为它有效:

from pprint import pprint for row in [[1,2,3],[4,5,6]]: how_many = len(row) for num in range(0, how_many): pprint(" row: " + str(num)) c_as_str = str(row[num]) print(c_as_str) if num == 9: if c_as_str != '': c = json.loads(c_as_str) pprint(c) else: print(" here is the row: ") pprint(c_as_str)

输出:

' row: 0'
1
 here is the row: 
'1'
' row: 1'
2
 here is the row: 
'2'
' row: 2'
3
 here is the row: 
'3'
' row: 0'
4
 here is the row: 
'4'
' row: 1'
5
 here is the row: 
'5'
' row: 2'
6
 here is the row: 
'6'
相关问题