我正在处理带有异常处理的输入验证,我的代码可以工作,但是它会打印错误消息两次,我无法弄清楚如何使验证循环只打印其中一个错误消息而不是两者。
这是我的代码:
def main():
low = 0
high = 10
get_num_in_range(low,high)
def get_num_in_range (low,high):
prompt = 'Enter a number between: ' + str(low) + ' and ' + str(high) + ': '
answer = low-1 #just get me in to loop
while answer < low or answer > high:
try:
answer = int(input(prompt))
except ValueError:
print('Invalid data type!')
if answer < low or answer > high:
print('Invalid!')
return answer
main()
输出如下:
输入介于0和10之间的数字:a
数据类型无效!
无效!
输入介于0和10之间的数字:
如何让循环只打印相关的错误消息?
编辑:解决了哈!我是一个白痴我在异常处理程序之外进行了'if'验证。 固定代码:while answer < low or answer > high:
try:
answer = int(input(prompt))
if answer < low or answer > high:
print('Invalid!')
except ValueError:
print('Invalid data type!')
return answer
答案 0 :(得分:1)
另一种选择可能是查看try-except-else子句(https://docs.python.org/2/tutorial/errors.html)。
CREATE TABLE "TASK_LIST"
(
"TASK_ID" INT not null primary key GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
"TASK_NAME" VARCHAR(50),
"TASK_DESCRIPTION" VARCHAR(50),
"TASK_PRIORITY" VARCHAR(100),
"TASK_STATUS" VARCHAR(20),
"TASK_START_TIME" TIMESTAMP,
"TASK_END_TIME" TIMESTAMP,
"TASK_ARCHIVED" BOOLEAN
);
//...NOTE: the task_id column value is auto-generated...
insert into task_list (task_name, task_description, task_priority, task_status, task_start_time, task_end_time, task_archived) values('Gathering Requirement', 'Requirement Gathering', 'MEDIUM', 'ACTIVE', CURRENT TIMESTAMP, {fn TIMESTAMPADD(SQL_TSI_HOUR, 1, CURRENT_TIMESTAMP)}, false);
insert into task_list (task_name, task_description, task_priority, task_status, task_start_time, task_end_time, task_archived) values('Application Designing', 'Application Designing', 'MEDIUM', 'ACTIVE', CURRENT TIMESTAMP, {fn TIMESTAMPADD(SQL_TSI_HOUR, 2, CURRENT_TIMESTAMP)}, false);
insert into task_list (task_name, task_description, task_priority, task_status, task_start_time, task_end_time, task_archived) values('Implementation', 'Implementation', 'MEDIUM', 'ACTIVE', CURRENT TIMESTAMP, {fn TIMESTAMPADD(SQL_TSI_HOUR, 3, CURRENT_TIMESTAMP)}, false);
insert into task_list (task_name, task_description, task_priority, task_status, task_start_time, task_end_time, task_archived) values('Unit Testing', 'Unit Testing', 'LOW', 'ACTIVE', CURRENT TIMESTAMP, {fn TIMESTAMPADD(SQL_TSI_HOUR, 4, CURRENT_TIMESTAMP)}, false);
insert into task_list (task_name, task_description, task_priority, task_status, task_start_time, task_end_time, task_archived) values('Maintenance', 'Maintenance', 'LOW', 'ACTIVE', CURRENT TIMESTAMP, {fn TIMESTAMPADD(SQL_TSI_HOUR, 5, CURRENT_TIMESTAMP)}, false);
当没有捕获异常时调用else子句