“while”循环重新执行程序

2024-09-30 16:39:03 发布

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

首先,我只想说我是一名新的Python程序员。 我开始编写数据库客户端,但我遇到了问题。 也许这个问题对很多人来说似乎很愚蠢,但对我这个菜鸟来说却是个问题

我编写了将数据添加到数据库的主模块 我想在最后一个条件之后,用户有可能添加更多数据。 诸如此类: 重复=输入(“是否要创建新记录?(Y/N)”) 如果重复=Y: (节目从头开始) 其他: (节目结束)

应在何处发现这种情况

下面是我的代码

import sqlite3
import time
import datetime
import sys

conn = sqlite3.connect('template.db')
c = conn.cursor()

def create_table(): #
    c.execute("CREATE TABLE IF NOT EXISTS Theft(template1 TEXT, template2 TEXT, template3 TEXT, template4 TEXT, template5 TEXT)")


def data_entry():
    unix = int(time.time())
    template1 = str(datetime.datetime.fromtimestamp(unix).strftime('%Y-%m-%d %H:%M:%S'))

    c.execute("INSERT INTO Theft(template1, template2, template3, template4, template5) VALUES (?, ?, ?, ?, ?)",
                (template1, template2, template3, template4, template5))

    conn.commit()

template2 = input("ENTER template ")
template3 = input("ITEM template ")
template4 = input("INPUT template ")
template5 = input("INPUT YOUR template: ")

accept = input("Do you wanna create new record in DB? (Y/N)")
if accept == "y":
    create_table(), data_entry()
elif accept == "Y":
    create_table(), data_entry()
else:
    sys.exit(0)


c.close()
conn.close()

问候 Jmazure:)


Tags: textimportinputdatadatetimetimecreatetable
1条回答
网友
1楼 · 发布于 2024-09-30 16:39:03

您必须将输入过程放入一个无限循环中,只有当用户输入“y”或“y”以外的内容时,该循环才会中断:

while True:
    accept = input("Do you wanna create new record in DB? (Y/N)")
    if accept.lower() == "y": <  checks if accept =="y" or accept == "Y"
        create_table(), data_entry()
    else:
        break

相关问题 更多 >