【问题标题】:Why does this code print something different depending on the indentation?为什么此代码会根据缩进打印出不同的内容?
【发布时间】:2022-01-16 19:19:15
【问题描述】:

我注意到当print(msg) 没有在for 循环内缩进并且缩进与for循环相同的位置时,它只打印我所做的更新语句中的信息,但是当它是方式时它在下面,它应该如何为我提供我所要求的信息。

这是我的代码:

import sqlite3

conn = sqlite3.connect(':memory:')

with conn:
    cur = conn.cursor()
    cur.execute("CREATE TABLE IF NOT EXISTS tbl_roster(\
        col_name TEXT, \
        col_species TEXT, \
        col_iq TEXT \
        )")
    conn.commit()

with conn:
    cur = conn.cursor()
    cur.execute("INSERT INTO tbl_roster(col_name, col_species, col_iq) VALUES (?, ?, ?)", ('Jean-Baptiste Zorg', 'Human', '122'))
    cur.execute("INSERT INTO tbl_roster(col_name, col_species, col_iq) VALUES (?, ?, ?)", ('Korben Dallas', 'Meat Popsicle', '100'))
    cur.execute("INSERT INTO tbl_roster(col_name, col_species, col_iq) VALUES (?, ?, ?)", ("Ak'not", 'Mangalore', '-5'))
    conn.commit()


with conn:
    cur = conn.cursor()
    cur.execute("UPDATE tbl_roster SET col_species=? WHERE col_name=? AND col_iq=?",('Human', 'Korben Dallas', '100'))
    conn.commit()


with conn:
    cur = conn.cursor()
    cur.execute("SELECT col_name, col_iq FROM tbl_roster WHERE col_species = 'Human'")

    varSpecies = cur.fetchall()
    for item in varSpecies:
        msg = "Name: {} \nIQ: {}  ".format(item[0], item[1])
        print(msg)

【问题讨论】:

  • 请将您的代码以文本形式发布! Stack Overflow 不接受代码截图。
  • 给出minimal reproducible example 作为文本,但可能:因为缩进在 Python 中有意义。
  • @KlausD。抱歉,抱歉不知道 Stack Overflow 不接受截图。谢谢。

标签: python database sqlite indentation


【解决方案1】:

Python 使用缩进来定义块。如果您在for 循环下缩进print 行,则每次迭代都会调用它。如果不这样做,循环将在每次迭代中迭代并覆盖 msg,然后当它完成时,print 语句将打印最后一个值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-02
    • 1970-01-01
    • 1970-01-01
    • 2014-11-23
    • 1970-01-01
    • 2019-10-15
    • 2019-11-17
    • 1970-01-01
    相关资源
    最近更新 更多