我想问问题,如果我几乎回答完所有问题,然后在字符串位置输入一个整数,它将重复该问题,而不是像开始那样从头开始重复。
我尝试将每个输入放入一个循环中,并为无效输入创建另一个输入,但这效率低下,并且实际上不起作用。
def create_entry():
c = connection.cursor()
tables = ["Cpus", "Cores", "Manufactures", "Sockets"]
print(tables)
while True:
tables_display = input("What Table Do Want To Make An Entry Too? ")
append_table_cpu = input("What Is The Name Of Your Cpu You Are Adding? ")
append_table_cost = input("How Much Does The Cpu You Are Adding Cost? ")
append_table_speed = input("How Fast Is The Cpu That You Are Adding?, Write Like This 2.00GHz")
append_table_cores = input("How Many Cores Does Your Cpu Have? ")
append_table_threads = input("How Many Threads Does The Cpu You Are Adding Have? ")
append_table_socket = input("What Type Of Socket Does Your Cpu Use? ")
tuple_insert = (tables_display, append_table_cpu, append_table_cost, append_table_speed, append_table_cores, append_table_threads, append_table_socket)
sql_query = ("INSERT INTO Cpus (Name,Cost,Speed_GHz,Cores,Threads,Socket) VALUES (?,?,?,?,?,?,?)")
c.execute(sql_query,tuple_insert)
results = c.fetchall()
for i in results:
print("Id: Manufactures: ".format(i[0],i[1]))
while True: #Puts Everything In A Loop
try:
option_1 = int(input("What Would You Like To Do To The Cpu Database, 1) Make An Entry, 2) Read The Data Or 3) Delete Data. Type 1, 2, ,3 "))
if option_1 == 1:
create_entry()
except:
print("Please Type A Valid Reply")
continue
我希望能够在数据库的字符串列中输入整数,或者输入无效的答复(例如不存在的表名),并且它从一开始就重复了我的问题。请保持基本答案。
答案 0 :(得分:0)
您可以使用正则表达式来验证输入。一会儿问,如果输入与正则表达式匹配,请将输入添加到answers
并继续询问;如果没有,请显示一条消息并再次询问(继续循环)。下面是一个示例(您的代码摘录):
import re
tables = ["Cpus", "Cores", "Manufactures", "Sockets"]
questions = [
("What Table Do You Want To Make An Entry To? ", "({})".format("|".join(tables))),
("What Is The Name Of Your Cpu You Are Adding? ", ".*"),
("How Much Does The Cpu You Are Adding Cost? ", "\d+"),
("How Fast Is The Cpu That You Are Adding? (e.g. 2.00GHz) ", "\d+\.?\d*[GMT]?Hz"),
("How Many Cores Does Your Cpu Have? ", "\d+"),
("How Many Threads Does The Cpu You Are Adding Have? ", "\d+"),
("What Type Of Socket Does Your Cpu Use? ", "(DIP|PLCC|Socket\s?[1-8])")
]
answers = []
for question, regex in questions:
while True:
answer = input(question)
if re.fullmatch(regex, answer):
answers.append(answer)
break
print("Invalid value")
sql_query = ("INSERT INTO Cpus (Name,Cost,Speed_GHz,Cores,Threads,Socket) VALUES (?,?,?,?,?,?,?)")
c.execute(sql_query, answers)
最后一个循环将永远询问,别忘了添加一个选项来停止询问,并break
while循环。