gpt4 book ai didi

python - 搜索 CSV 文件 python

转载 作者:太空宇宙 更新时间:2023-11-04 10:38:18 24 4
gpt4 key购买 nike

我已经编写了一个程序来调用文件中的汇率,但它打印了到达行的输出,存在逻辑错误,但我找不到它。

import csv
exRtFile = open ('exchangeRate.csv')
exchReader = csv.reader(exRtFile)
newCurrency = raw_input("Please enter the currency you would like to convert to: ")
for row in exchReader:
currency = row[0]
if currency == newCurrency:
newRt = row[1]
print(newRt)
break

print("Sorry, that is not a valid currency")

文件:

Pound Sterling,1
Euro,1.22
US Dollar,1.67
Japanese Yen,169.948

最佳答案

如果我正确理解您的问题,问题是它打印 "Sorry..." 行,即使它在文件中找到了货币。为防止这种情况,您可以 add an else to the for loop .

for row in exchReader:
currency = row[0]
if currency == newCurrency:
newRt = row[1]
print(newRt)
break
else:
print("Sorry, that is not a valid currency")

这样,else block 只会在循环正常退出时执行,即没有 break

关于python - 搜索 CSV 文件 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22249818/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com