用户输入错误信息时出现错误

时间:2009-06-04 11:25:16

标签: python csv reporting user-input

所以,我最近开始学习python ...我正在编写一个从csv中提取信息的小脚本,我需要能够通知用户输入错误

例如

询问用户他的身份证号码,身份证号码是从r1到r5的任何内容 我希望我的脚本能够告诉用户他们输入了错误的内容 例如,如果用户输入a1或r50,则需要通知用户他们输入了错误的参数。我该怎么做?

我已经调查过了 def语句,但我似乎无法掌握python中的所有语法....(我不知道所有的命令......参数和东西)

非常感谢任何帮助= D

while True: 
    import csv 
    DATE, ROOM, COURSE, STAGE = range (4) 
    csv_in = open("roombookings.csv", "rb") 
    reader = csv.reader (csv_in) 
    data = [] 
    for row in reader: 
        data.append(row) 
    roomlist = raw_input ("Enter the room number: ") 
    print "The room you have specified has the following courses running: " 
    for sub_list in data: 
        if sub_list[ROOM] == roomlist: 
            Date, Room, Course, Stage = sub_list 
            print Date, Course

2 个答案:

答案 0 :(得分:1)

我不确定你要求的是什么,但是如果你想检查用户是否输入了正确的id,你应该尝试使用正则表达式。看看Python Documentation on module re。或者请谷歌搜索“python re”

这是一个检查用户输入的示例:

import re

id_patt = re.compile(r'^r[1-5]$')
def checkId(id):
    if id_patt.match(id):
        return True
    return False

HTH,问候。

编辑:我再次读到你的问题,这里还有一些代码: (只需将其粘贴到上一个代码片段下面)

validId = False
while not validId:
    id = raw_input("Enter id: ")
    validId = checkId(id)

顺便说一句,它可以用非常短的方式编写,但对于Python新手来说,这段代码应该更容易理解。

答案 1 :(得分:1)

说真的,阅读教程。 official一个非常好。我也喜欢this book为初学者。

import csv

while True:
    id_number = raw_input('(enter to quit) ID number:')

    if not id_number:
        break

    # open the csv file
    csvfile = csv.reader(open('file.csv'))
    for row in csvfile:
        # for this simple example I assume that the first column 
        # on the csv is the ID:
        if row[0] == id_number:
            print "Found. Here's the data:", row
            break
    else:
        print "ID not found, try again!"

EDIT 现在你已经添加了代码,我更新了示例:

import csv
DATE, ROOM, COURSE, STAGE = range(4) 

while True: 
    csv_in = open("roombookings.csv", "rb") 
    reader = csv.reader(csv_in) 
    roomlist = raw_input("(Enter to quit) Room number: ") 
    if not roomlist:
        break
    print "The room you have specified has the following courses running: " 
    for sub_list in reader: 
        if sub_list[ROOM] == roomlist: 
            print sub_list[DATE], sub_list[COURSE]