我正在尝试验证我的python脚本:
def DOBSearch():
loop = True
while loop == True:
try:
DOBsrch = int(input("Please enter the birth month in a two digit format e.g. 02: "))
for row in BkRdr:
DOB = row[6]
day,month,year = DOB.split("/")
if DOBsrch == int(month):
print("W")
surname = row[0]
firstname = row[1]
print(firstname, " ",surname)
addrsBk.close
loop = False
else:
print("1 That was an invalid choice please try again.")
except ValueError:
print("That was an invalid choice please try again.")
然而,当我尝试测试脚本时,我发现存在错误/错误,因为我得到以下输出:
>>> DOBSearch()
Please enter the birth month in a two digit format e.g. 02: 2345
1 That was an invalid choice please try again.
1 That was an invalid choice please try again.
1 That was an invalid choice please try again.
1 That was an invalid choice please try again.
1 That was an invalid choice please try again.
1 That was an invalid choice please try again.
Please enter the birth month in a two digit format e.g. 02: 23456
Please enter the birth month in a two digit format e.g. 02: 4321
Please enter the birth month in a two digit format e.g. 02: 2345
Please enter the birth month in a two digit format e.g. 02: yrsdhctg
That was an invalid choice please try again.
Please enter the birth month in a two digit format e.g. 02: 02
Please enter the birth month in a two digit format e.g. 02:
这是CSV文件:
Jackson,Samantha,2 Heather Row,Basingstoke,RG21 3SD,01256 135434,23/04/1973,sam.jackson@hotmail.com
Vickers,Jonathan,18 Saville Gardens,Reading,RG3 5FH,01196 678254,04/02/1965,the_man@btinternet.com
Morris,Sally,The Old Lodge, Hook,RG23 5RD,01256 728443,19/02/1975,smorris@fgh.co.uk
Cobbly,Harry,345 The High Street,Guildford,GU2 4KJ,01458 288763,30/03/1960,harry.cobbly@somewhere.org.uk
Khan,Jasmine,36 Hever Avenue,Edenbridge,TN34 4FG,01569 276524,28/02/1980,jas.khan@hotmail.com
Vickers,Harriet,45 Sage Gardens,Brighton,BN3 2FG,01675 662554,04/04/1968,harriet.vickers@btinternet.com
答案 0 :(得分:1)
你不能区分什么是有效出生月份(即有意义的出生月份,1到12之间的整数)和BkRdr
中的出生月份(可能是其中的一部分) )。您在try
数据块中有太多内容,并且会告知用户row
中BkRdr
的每个row
他们的输入无效,而后期def input_month():
"""Get a valid birth month from the user."""
while True:
try:
month = int(input("Please enter the birth month in a two digit format e.g. 02: "))
except ValueError:
print("Must be a number")
else:
if month in range(1, 13):
return month
print("Must be in range 1-12")
def DOB_search(BkRdr):
"""Find a valid birth month in BkRdr."""
while True:
search_month = input_month()
for row in BkRdr:
...
if search_month == int(month):
...
return " ".join((firstname, surname))
print("Not found in BkRdr.")
可能实际匹配。< / p>
我会将它分成至少两个函数,使用显式参数而不是依赖于范围:
BkRdr
这将您的代码的两个问题分开:
BkRdr
。我还会重新考虑变量名称 - 无论如何都是{{1}}?
答案 1 :(得分:0)
我认为您的代码中存在两个错误。
首先,您要重复打印第一条错误消息。这是因为print
行位于for
循环内部,用于检查CSV文件中的每一行。每个不匹配的行都会生成错误消息。
要解决此问题,您应该将print
语句上移一个级别,以便在for
循环结束后调用。
第二个问题是你循环的BkRdr
似乎是一个迭代器,而不是你可以重复迭代的序列。这就是为什么第一个之后的每个数字输入都会无声地失败。在这些情况下,for
循环根本不做任何事情!
要解决第二个问题,您可能需要更改未显示的其他代码,以便将CSV文件读入列表,而不是仅读取迭代器。 (或者,您可以回放文件,或关闭并重新打开它。)