IndexError: list index out of range - python - python

I have the following error:
currency = row[0]
IndexError: list index out of range
Here is the code:
crntAmnt = int(input("Please enter the amount of money to convert: "))
print(currencies)
exRtFile = open ('exchangeRate.csv','r')
exchReader = csv.reader(exRtFile)
crntCurrency = input("Please enter the current currency: ")
validateloop=0
while validateloop == 0:
for row in exchReader:
currency = row[0]
if currency == crntCurrency:
crntRt = row[1]
validateloop=+1
Heres the CSV file:
Japanese Yen,169.948
US Dollar,1.67
Pound Sterling,1
Euro,5.5
Here's an input/Output example:
Please enter the amount of money to convert: 100
['Pound Sterling', 'Euro', 'US Dollar', 'Japanese Yen']
Please enter the current currency: Pound Sterling

You probably have a blank row in your csv file, causing it to produce an empty list
There are a couple solutions
1. Check if there are elements, only proceed if there are:
for row in exchReader:
if len(row): # can also just do if row:
currency = row[0]
if currency == crntCurrency:
2. Short-circuit an and operator to make currency an empty list, which won't match crntCurrency:
for row in exchReader:
currency = row and row[0]
if currency == crntCurrency:

Try printing out the row. The convention for variable names in python are like_this and not likeThis. You might find the break keyword useful:
for row in exch_reader:
currency = row[0]
if currency == crnt_currency:
crnt_rt = row[1]
break
To only index the row when the row actually contains something:
currency = row and row[0]
Here row[0] is only executed if row evaluates to True, which would be when it has at least one element.

Related

How to sum specific values in a csv file in Python?

I am trying to search through a CSV file for certain criteria, and anything that fits that criteria, to be printed as a sum.
Example data:
| city | state | college | cases |
|Huntsville | Alabama | Alabama A&M University | 42 |
etc, for hundreds of lines. I would like to be able to search the data, for example, the state of Alabama, and sum all cases that are equal to that state.
This is what I have so far:
category = input(What would you like to look up? Please enter 'city', 'state', or 'college': ")
if category == "city":
city = input("Enter a city: ")
for row in reader:
if row[0] == city:
print("The city of", city, "has had a total of", row[3], "cases at", row[2])
print("All cities with the name", city, "have a total of", sum(row[3]), "cases.")
The row numbers entered correspond to the row I need in the original CSV file. All code works, except for my last line, where the sum command for the row clearly does not work. While playing around with different options, it does not like that it is a string variable (even though it's all numbers for the cases). Is there a better way to do this? Thank you.
sum(row[3]), assuming it works at all, is just going to return row[3] (explanation here). You need to change your code as follows.
category = input(What would you like to look up? Please enter 'city', 'state', or 'college': ")
if category == "city":
city = input("Enter a city: ")
sum = 0
for row in reader:
if row[0] == city:
print("The city of", city, "has had a total of", row[3], "cases at", row[2])
sum += int(row[3])
print("All cities with the name", city, "have a total of", sum, "cases.")
You won't know the total for the city until you have read all the rows for city.
You're getting a data structure from csvreader that is either a list or a dictionary. I'll assume it's a list. The easy way is:
total = 0
for line in csvdata:
if line[1] == 'Alabama':
total += int(line[3])
that can be turned into a list comprehension form
total = sum([int(x[3]) for x in csvdata if x[1] == 'Alabama'])
(Update, thanks for the correction. Corrections.)

How can I get the count of name grater than 2 from file using Python programming?

I have a file with id,name,sal. what is the code for it in python to get the name of the employees whose name is repeated two or more than two times?
example data:
101,Ramu,2000
102,Mahesh,3000
103,Anni,4000
104,Ramu,4000
105,Laxmi,5000
106,Mahesh,6000
107,Ramu,7000
Output should be:
101,Ramu,2000
104,Ramu,4000
107,Ramu,7000
106,Mahesh,6000
102,Mahesh,3000
Can you help me on it?
You can use a dictionary to count the number of occurrences per name in one loop.
Then print accordingly in a second loop.
data = [
'101,Ramu,2000',
'102,Mahesh,3000',
'103,Anni,4000',
'104,Ramu,4000',
'105,Laxmi,5000',
'106,Mahesh,6000',
'107,Ramu,7000',
]
counts = {}
for row in data:
name = row.split(',')[1]
if name in counts:
counts[name] += 1
else:
counts[name] = 1
for row in data:
name = row.split(',')[1]
if counts[name] >= 2:
print(row)
Output:
101,Ramu,2000
102,Mahesh,3000
104,Ramu,4000
106,Mahesh,6000
107,Ramu,7000

Print the lowest numeric value from a text file

I have a text file consisting of some stocks and their prices and what not, I am trying to print out the stock which has the lowest value along with the name of the company here is my code.
stocks = open("P:\COM661\stocks.txt")
name_lowest = ""
price_lowest = 0
for line in stocks:
rows = line.split("\t")
price = float(rows[2])
if price>price_lowest:
price_lowest = price
name_lowest = rows[1]
print(name_lowest + "\t" + str(price_lowest))
I'm trying to go through the file and compare each numeric value to the one before it to see if it is higher or lower and then at the end it should have saved the lowest price and print it along with the name of the company.
Instead it prints the value of the last company in the file along with its name.
How can I fix this?
You made 2 mistakes.
First is initialised the initial value to 0
You should initialise the initial value to the max available number in python float.
import sys
price_lowest = sys.float_info.max
Or else you could initialise it to the first element
Second your should if statement should be
if price<price_lowest:
Initialize:
price_lowest = 999999 # start with absurdly high value, or take first one
Plus your if check is the opposite.
Should be:
if price < price_lowest
Others already suggested a solution that fixes your current code. However, using Python you can have a shorter solution:
with open('file') as f:
print min(
[(i.split('\t')[0], float(i.split('\t')[1])) for i in f.readlines()],
key=lambda t: t[1]
)
Your "if" logic is backwards, it should be price<lowest_pre.
Just make a little adjustment start your price_lowest at None then set it to your first encounter and compare from there on
stocks = open("P:\COM661\stocks.txt")
name_lowest = ""
price_lowest = None
for line in stocks:
rows = line.split("\t")
price = float(rows[2])
if price_lowest = None:
price = price_lowest
name_lowest = rows[1]
elif price < price_lowest:
price_lowest = price
name_lowest = rows[1]
print(name_lowest + "\t" + str(price_lowest))

Python: dict and sorting in alphabetical

I require to write a program which accept input year from user and read information from CSV file then export result on the screen. The csv source file has format: year, name, count, gender and export result are boy only with format Name Count in alphabetical order.
Input file:
2010,Ruby,440,Female
2010,Cooper,493,Male
Output:
Please enter the year: 2010
Popular boy names in year 2010 are:
Aidan 112
I have error when run program:
Please enter the year: 2014
Traceback (most recent call last):
File "E:\SIT111\A1\printBoynameTPL.py", line 26, in <module>
year, name, count, gender = row
ValueError: need more than 0 values to unpack
This is my code:
'''
This program accepts a year as input from a user and print boys' information of the year. The output should be sorted by name in alphabetical order.
Steps:
1. Receive a year from a user
2. Read CSV files:
Format: year, name, count, gender
3. Display popular boy names on the screen:
Format: Name Count
'''
import csv
inputYear = raw_input('Please enter the year: ')
inFile = open('output/babyQldAll.csv', 'rU')
cvsFile = csv.reader(inFile, delimiter=',')
dict = {}
for row in cvsFile:
year, name, count, gender = row
if (year == inputYear) and (gender == 'Boy'):
dict[name] = count
print('Popular boy names in year %s are:' % inputYear)
# +++++ You code here ++++
# According to informaiton in 'dict', print (name, count) sorted by 'name' in alphabetical order
sortedName = shorted(dict.keys())
for name in sortedName:
print(name, dict[name])
print("Print boy names... ")
inFile.close()
I edited a bit:
for row in cvsFile:
if row:
year, name, count, gender = row
if (year == inputYear) and (gender == 'Male'):
dict[name] = count
print('Popular boy names in year %s are:' % inputYear)
# +++++ You code here ++++
# According to informaiton in 'dict', print (name, count) sorted by 'name' in alphabetical order
sortedName = sorted(dict.keys())
for name in sortedName:
print(name,dict[name])
print("Print boy names... ")
did i do sth wrong? indents or sth?
result:
>>>
Please enter the year: 2013
Popular boy names in year 2013 are:
Print boy names...
>>>
You seem to be having empty lines in your csv file, which is causing empty row to come you iterate the csv file. You can simply check if row is empty or not, before doing rest of the logic. Example -
for row in cvsFile:
if row:
year, name, count, gender = row
if (year == inputYear) and (gender == 'Boy'):
dict[name] = count
Also, you should not use dict as a variable name, it shadows the built-in function dict() .
Also, you have another typo in your program -
sortedName = shorted(dict.keys())
I am guessing you intended to use sorted() .

Reading Excel file based on 2 conditions in Pythton 3.4

I have a excel file that has 5 columns holding player data.
column A: Player name, Column B: Team:, Column C: points, column D, Cost, Column E: position.
I know how to get the price of the player by entering the player name as follows:
from openpyxl import load_workbook
print ("Going to execute the Player Choices")
total = {}
for player in range(4):
player = input("Enter player name")
wb = load_workbook("LeaguePlayers.xlsx")
ws = wb.active
for cell in ws.columns[0]: # get first column
if cell.value == player:
cost = ws.cell(row=cell.row, column=4).value
position = ws.cell(row=cell.row, column=5).value
print("{0} ({2}) costs {1}".format(player, cost, position))
total[player] = cost
break
print("Total Spend is: ",sum(total.values()),"Million")
print ("End of player choices")
print(total)
What I want to know is how is it possible to get a players price if the player I have searched for is position "Midfielder" from column E. So just to be clear If I want to get a price for a midfielder and I type Rooney it should look in column E and realise this is not a midfielder and prompt me to enter again until I enter a player who is a midfielder and the price is then displayed.
Any pointers much appreciated.
Thanks
To be honest, the best solution to this problem is to take the data from Excel and put it in a database which you can then query. Alternatively, you might want to query the data with Excel using the excellent xlwings.

Categories

Resources