0

所以,我最近开始学习 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
4

2 回答 2

1

我不确定你要什么,但如果你想检查用户是否输入了正确的 id,你应该尝试正则表达式。查看模块 re 上的 Python 文档。或向谷歌询问“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 新手来说,这段代码应该更容易理解。

于 2009-06-04T11:57:55.080 回答
1

说真的,看教程。官方的还不错。我也喜欢这本书,适合初学者。

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!"

编辑现在您已经添加了代码,我更新了示例:

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]
于 2009-06-04T12:03:23.307 回答