【问题标题】:validating string while loop logic error [Python] and csv file error验证字符串 while 循环逻辑错误 [Python] 和 csv 文件错误
【发布时间】:2014-04-10 12:53:11
【问题描述】:

我正在尝试验证我的部分代码,如下所示:

loop2 =1
    while loop2==1:
        crntCurrency = input("Please enter the current currency: ")
        if crntCurrency == 'Pound Sterling' or crntCurrency =='Euro' or crntCurrency =='US Dollar' or crntCurrency =='Japanese Yen':                   
            break
        else:
            print("sorry that was invalid, please try agian:")

不过,我在这里又试了一次:

   loop3 = 1
    while loop3 ==1:
        newCurrency = input("Please enter the currency you would like to convert to: ")
        if newCurrency == 'Pound Sterling' or crntCurrency =='Euro' or crntCurrency =='US Dollar' or crntCurrency =='Japanese Yen':                   
            break
        else:
            print("sorry that was invalid, please try agian:")



    exRtFile = open ('exchangeRate.csv')
    exchReader = csv.reader(exRtFile)
    validateloop2 = 0
    while validateloop2 == 0:
        for row in exchReader:
            currency = row and row[0]
            if currency == newCurrency:
                newRt = row[1]
                validateloop2 =+1    
                toPound = crntAmnt/float(crntRt)
                newAmount = int(toPound)*float(newRt)
                print("You have: " ,newAmount, newCurrency,)
                exRtFile.close()

在打印“抱歉无效,请重试:”之后,我陷入了一个永远循环。如果输入正确,我会收到错误消息(我认为这是一个缩进错误):

for row in exchReader:
ValueError: I/O operation on closed file.

【问题讨论】:

    标签: python csv python-3.x


    【解决方案1】:

    您的代码似乎有几个问题,所以让我们看看我们是否可以一次解决一个。

    输入验证错误


    如果您的程序在接受正确值时遇到问题,那么您的第二个循环中至少有一个错误会给您带来麻烦

    if newCurrency == 'Pound Sterling' or crntCurrency =='Euro' or crntCurrency =='US Dollar' or crntCurrency =='Japanese Yen':
    

    您会注意到您检查了 newCurrency 的英镑,并检查了 crntCurrency 的其他值。由于您在 input 中读取为 newCurrency,因此您需要针对所有值与此进行比较。这一行应该是

    if newCurrency== 'Pound Sterling' or newCurrency=='Euro' or newCurrency=='US Dollar' or newCurrency=='Japanese Yen':
    

    并且Jasper 是正确的关于您的代码是非pythonic。

    newCurrency in ['Pound Sterling', 'Euro', 'US Dollar', 'Japanese Yen']
    

    是一种更好的方法。更好的是,在代码的开头定义一个列表,以便您可以在其他地方使用它

    currency = ['Pound Sterling', 'Euro', 'US Dollar', 'Japanese Yen']
    

    然后你就可以使用

    if newCurrency in currency:
    

    然后您就可以在代码中的其他地方重用currency

    I/O 操作错误


    接下来是你的程序在关闭的文件上抛出 I/O 操作的问题

    for row in exchReader:
    ValueError: I/O operation on closed file.
    

    问题来了

    exRtFile = open ('exchangeRate.csv')
        exchReader = csv.reader(exRtFile)
        validateloop2 = 0
        while validateloop2 == 0:
            for row in exchReader:
                    # if something
                            exRtFile.close()
    

    一旦你找到你的条件,你就用exRtFile.close()关闭你的文件,但你的for循环for row in exchReader仍在运行。因此,在 if 语句退出后,它将再次遍历您的循环,并且您的程序将尝试从文件中读取,因为 exchReader 是一个 csv 阅读器,但您已经关闭了该 csv 文件。所以你有两个选择:(1)在你满足你的有效条件并完成迭代之后关闭你的while循环之外的文件,或者(2)一旦你满足你的if条件,你关闭你的文件并输入一个中断命令退出你的 for 循环。

    风格建议


    关于风格的一些其他说明:你为什么使用while validateloop2 == 0?为什么不只设置一个变量valid = False,然后当你得到if 条件时,设置valid = True?然后,当您从 for 循环中 break 时,您的 while 循环将看到 valid = True 并退出。使用像 valid 这样的变量作为布尔值可以使您的代码更具可读性。根据我的评论,您可以使用while not valid: 作为while 条件(假设您最初设置了变量valid = False

    【讨论】:

    • 谢谢你,很好地解释了,但是我的验证第二次仍然无法正常工作,当我在第一次使用“while True”然后提供不正确的输入时,我陷入了一个永远的循环里面什么都没有?
    • 刚刚发现你的编辑谢谢你,工作就像一个魅力,你清楚地知道你在做什么:)
    • 其实第二个循环的所有地方都应该是newCurrency
    • @user3165683,我做了一些编辑来整理我的想法。如果有什么不清楚的地方请告诉我
    • 谢谢@Jasper,只是我的一个错字。
    【解决方案2】:

    您收到错误是因为您关闭文件然后尝试读取新记录。在if 块的末尾,您必须将break 退出for 循环。

    但您的代码中还有其他几个错误和许多非 Python 部分:

    而不是做

    a == "one" or a == "two" or a == "three"
    

    你应该这样做

    a in ["one", "two", "three"]
    

    不要为了获得无限循环而引入设置为1的额外变量,使用

    while True:
      ...
    

    if **new**Currency == 'Pound Sterling' or **crnt**Currency =='Euro' or **crnt**Currency =='US Dollar' or **crnt*Currency =='Japanese Yen':
    

    我不认为这是故意的,但这将通过第一点来解决。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-26
      • 1970-01-01
      • 2014-04-18
      • 1970-01-01
      相关资源
      最近更新 更多