What is wrong with this code during enumeration - python

import datetime
with open("fine.txt","r") as f, open("fine1.txt","a") as fine1:
lines = f.read().split("\n")
for i in range(2):
var = input("reg : ") # registration number(reg_num)
enter = input('Time entered camera 1(24hrs)in the format HH:MM:SS: ')
ext = input('Time enterd camera 2 (24hrs)in the format HH:MM:SS : ')
total_time = '%H:%M:%S'
enter_time = datetime.datetime.strptime(enter, total_time)
ext_time = datetime.datetime.strptime(ext, total_time)
if enter_time > ext_time:
ext_time += datetime.timedelta(hours=24)
t_diff = ext_time - enter_time
time = t_diff.total_seconds() / 3600
speed = 1 / time
reg = var[0:1].isalpha() and var[2:3].isdigit() and var[4].isspace() and var[5:7].isalpha() and var.isupper()
if reg == True:
for i, line in enumerate(lines):
if var in line:
num = int("{}".format(i))
var = f.read()
name = (var[num]) #the problem
print(name)
address = (var[num + 0])
if speed > 70:
print("ovrspeeding", (var[num + 0]))
fine1.write(name+address+speed+"\n")
The whole code had to inputted, otherwise you will not understand what i am trying to do.
fine.txt is a file that has already been made and looks like:
reg_num1 aaaaaaaaaaaaaaaaaaa
reg_num2 bbbbbbbbbbbbbbbbbbb
reg_num3 ccccccccccccccccccc
this code takes in inputs of the registration number(e.g. AA01 SSS) and 2 time formats (which will later be used to calculate the speed). i want this code to find the line in fine.txt that have the registration number i inputted and if that vehicle is overspeeding(speed >70mph)the whole line needs to be appended into the file fine1.txt.
the problem is that when i run the code the error massage states that:
name = (var[num])
IndexError: string index out of range
i dont what this means, so can you help me with this.

Related

Python sys.argv indexerror list index out of range

When I use splitter_freqy.py to split my .dat filem I meet the following problem.
line 5 name=str(sys.argv[position+1])
indexerror list index out of range
I use ubuntu and the command is
python3.6 splitter_freq.py abc.dat
This is the splitter_freq.py
import sys
arguments = len(sys.argv) - 1
position = 1
name = str(sys.argv[position+1])
while (arguments > position): # changed >= to > to avoid error
bench_freq_names = []
path0 = "./%s/"%name+sys.argv[position]
position = position+1
print("the input file is ",path0)
c_0 = open(path0,'r')
header=c_0.readline()
l_0 = c_0.readline()
w_0 = l_0.split()
bench_name = w_0[1]
freq_value = w_0[3]
path_out = path0.split("/")
path_out = path_out[-1].split(".")
print("the benchmark name is ",bench_name)
print("the freq value is ",freq_value)
bench_freq_names.append([bench_name,freq_value])
output_file = "./%s/"%name+path_out[0]+"_"+bench_name+"_"+freq_value+".txt"
m = open(output_file,'a')
print(header.rstrip('\n'),file=m)
print(l_0.rstrip('\n'),file=m)
for l_0 in c_0: #read lines one by one
w_0 = l_0.split()
if (w_0[1] == bench_name and w_0[3] == freq_value):
print(l_0.rstrip('\n'),file=m)
else: #new_bench_name or new freq_value
m.close() #close file
bench_name = w_0[1] #update bench
freq_value = w_0[3] #update freq
print("the benchmark name is ",bench_name)
print("the freq value is ",freq_value)
output_file = "./%s/"%name+path_out[0]+"_"+bench_name+"_"+freq_value+".txt"
m = open(output_file,'a')
if [bench_name,freq_value] not in bench_freq_names:
bench_freq_names.append([bench_name,freq_value])
print(header.rstrip('\n'),file=m)
print(l_0.rstrip('\n'),file=m)
c_0.close()
m.close()

I get "TypeError: list indices must be integers or slices, not str". How do I fix it?

I am working on some code that will take the data from OpenWeatherMap.org and displays the weather. Here's what I have so far:
import requests, json
apikey = "7cb9becaea566cc27d69991c345fa129"
base = "http://api.openweathermap.org/data/2.5/onecall?"
lat = "censored"
lon = "censored"
compbase = f"{base}lat={lat}&lon={lon}&exclude=current,minutely,hourly&appid={apikey}"
print(compbase)
resp = requests.get(compbase)
x = resp.json()
daily = x["daily"]
temp = daily["temp"]
des = daily["weather"]
currtemp = temp["morn"]
currtemp = str(round(float(1.8)*(currtemp - 273) + 32, 1))
currpres = day["pressure"]
currpres = str(round(currpres/3386, 1))
currhum = day["humidity"]
feelslike = day["feels_like"]
feelslike = str(round(float(1.8)*(feelslike - 273) + 32, 1))
winds = str(round(float(y["wind_speed"]), 1))
weatherdes = str(des["description"])
if "alerts" in x:
alerts = x["alerts"]
aldes = alerts["description"]
print()
print("ALERT!!!!")
print()
print(f"Your WeatherWatcher program has been interuppted by {alerts['sender_name']}. Please pay attention closely.")
print()
print(str(aldes))
print()
print(f"It is currently {currtemp} degrees Fahrenheit outside.")
print()
print(f"It feels like {feelslike} degrees Fahrenheit outside.")
print()
print(f"The wind is blowing at {winds} MPH.")
print()
print(f"The pressure is at {currpres} inhg.")
print()
print(f"The humidity is at %{currhum}.")
print()
print(f"OpenWeatherMap describes this weather as {weatherdes}.")
print()
print("This data was brought to you by WeatherWatcher.")
(Sorry, kinda long.)
But when I run it, I get this:
Traceback (most recent call last):
File "C:\Users\ron83\OneDrive\Documents\weather.py", line 12, in <module>
temp = daily["temp"]
TypeError: list indices must be integers or slices, not str
What did I do wrong? I know I didn't make it a string.
Your main problem is: API returns values for 8 days and you have to use index [0] to get value for today (or [1] for tomorrow, [2] for day after tomorrow, etc.)
day = daily[0]
temp = day["temp"]
des = day["weather"]
currpres = day["pressure"]
currhum = day["humidity"]
feelslike = day["feels_like"]
instead of
day = daily["temp"]
Becasause data are more complex so there are other mistakes
It needs [0] in `weather
des = day["weather"][0]
it needs ['day'] in feels_like
feelslike = day["feels_like"]
Simply use print() to see what you have in variables
Working code:
import requests, json
apikey = "7cb9becaea566cc27d69991c345fa129"
base = "http://api.openweathermap.org/data/2.5/onecall?"
lat = "52"
lon = "10"
compbase = f"{base}lat={lat}&lon={lon}&exclude=current,minutely,hourly&appid={apikey}"
print(compbase)
resp = requests.get(compbase)
data = resp.json()
daily = data["daily"]
#print("[DEGUB] daily:", daily)
#print("[DEGUB] len(daily):", len(daily))
day = daily[0] # needs [0]
temp = day["temp"]
#print('[DEGUB] day["weather"]:', day["weather"])
des = day["weather"][0] # needs [0]
currtemp = temp["morn"]
currtemp = str(round(float(1.8)*(currtemp - 273) + 32, 1))
currpres = day["pressure"]
currpres = str(round(currpres/3386, 1))
currhum = day["humidity"]
#print('[DEGUB] day["feels_like"]:', day["feels_like"])
feelslike = day["feels_like"]['day'] # needs ["day"]
feelslike = str(round(float(1.8)*(feelslike - 273) + 32, 1))
winds = str(round(float(day["wind_speed"]), 1))
weatherdes = des["description"]
if "alerts" in data:
#print('[DEGUB] data["alerts"]:', data["alerts"])
alerts = data["alerts"][0] # needs [0]
aldes = alerts["description"]
print()
print("ALERT!!!!")
print()
print(f"Your WeatherWatcher program has been interuppted by {alerts['sender_name']}. Please pay attention closely.")
print()
print(str(aldes))
print()
print(f"It is currently {currtemp} degrees Fahrenheit outside.")
print()
print(f"It feels like {feelslike} degrees Fahrenheit outside.")
print()
print(f"The wind is blowing at {winds} MPH.")
print()
print(f"The pressure is at {currpres} inhg.")
print()
print(f"The humidity is at %{currhum}.")
print()
print(f"OpenWeatherMap describes this weather as {weatherdes}.")
print()
print("This data was brought to you by WeatherWatcher.")

Looping over a text file list with python

EDIT: Have updated post for better clarity, no answers have yet to help!
Alright, so my assignment is to take a text file, that would have 4 entries per line, those being firstName, lastName, hours, payRate. I'm to do some calculations and throw all this information in a formatted table in python. Now, I've got the code to enter the data into the table, but it only works for the first entry in the text file, and I can't quite make it loop. I honestly feel like an idiot, and that this is just a simple fix.
My output is supposed to look like this:
http://i.imgur.com/bIOBqye.png
Could really use some pointers on making this loop through and print the data from each line of the text file. Here's how my current code looks:
heading1 = "{0:15s}{1:15s}{2:10s}{3:15s}{4:20s}{5:15s}".format("First Name", "Last Name", "Hours", "Payrate", "Overtime Hours", "Gross Pay")
heading2= "=============================================================================================================="
print(heading1)
print(heading2)
if os.path.isfile(fileQuestion) == True:
file = open('emps', 'r')
data = file.readlines()
for tmp in data:
data2= [word.rstrip("\n") for word in data]
first = data2[0].split()
lastName = first[0]
firstName = first[1]
first[2]=(int(first[2]))
first[3]=(int(first[3]))
initialHours = first[2]
payRate = first[3]
if initialHours > 40:
overHours = initialHours - 40
regHours = 40
regPay = payRate * regHours
otPay = overHours * (payRate * 1.5)
grossPay = regPay + otPay
else:
regHours = first[2]
grossPay = initialHours * payRate
overHours = 0
heading3= "{0:15s}{1:15s}{2:2d}{3:10d}{4:14d} {5:24.2f}".format(firstName, lastName, regHours, payRate, overHours, grossPay)
heading4= "{0:15s}{1:21.2f}".format("Total Gross Pay", grossPay)
heading5= "{0:15s}{1:19.2f}".format("Average Gross Pay", grossPay)
heading6= "{0:15s}{1:16d}".format("Total Overtime Hours", 33)
spaceHeading = " "
print(heading3)
print(spaceHeading)
print(heading4)
print(heading5)
print(heading6)
Please let me know if I haven't done this correctly or anything, first time here. Thanks.
I found the duplicate, and think some people treat rude ;/ Just not focus on pragmatic problems of programmers but on good rules of Stack in bad way :(
Here is my complete answer for your problem:
1)
First of all, you must remember that ident is used against code block's brackets known from another landuages.
I reformatted your code remember that all of lines should have extra spaces at the beginning when you pase it here ;)
2) like it was said:
first = word.split()
fix "not changing" of lines in loop.
3) Total overtime hours have hardcoded number:
heading6= "{0:15s}{1:16d}".format("Total Overtime Hours", overHours)
Also, overHours(All?) should be not "zeroed" in 'else' block in loop. You must initialize it before loop.
I change some other places i.e. some hardcoded ints, maybe it not ideal and in your style, but you have code with my fixes below...
Best, if you use GitHub or Bitbucket or another repo accesible by web, because you help to contribute if you want it, and also - yourself, to find all the changes which was done. And then, just ask here to help in extremely unknown problems. In the begging of learning it is always hard to find out, but later - you could achieve more!
Here is code after my changes:
from os.path import isfile as isFileExsist
import sys
filePath = input("What is the name of your file?: ")
while isFileExsist(filePath) == False:
pos = ['y', 'Y', 'yes', 'Yes']
neg = ['n', 'N', 'no', 'No']
answer = input("File not found! Do you want to start again? (y-yes/n-no)")
if answer in neg:
exit("Bye!")
elif answer in pos:
filePath = input("What is the name of your file?: ")
continue
else:
print("Not sure what is the answer. Try again!")
continue
file = open(filePath, 'r')
data = file.readlines()
print("{0:15s}{1:15s}{2:10s}{3:15s}{4:20s}{5:15s}".format("First Name", "Last Name", "Hours", "Payrate", "Overtime Hours", "Gross Pay"))
print("==============================================================================================================")
overHoursAll = 0
grossPayAll = 0
count = 0
for line in data:
words = line.split()
lastName = words[0]
firstName = words[1]
initialHours=(int(words[2]))
payRate =(int(words[3]))
if initialHours > 40:
regHours = 40
overHours = initialHours - 40
regPay = payRate * regHours
otPay = overHours * (payRate * 1.5)
grossPay = regPay + otPay
else:
regHours = initialHours
overHours = 0
grossPay = initialHours * payRate
grossPayAll += grossPay
overHoursAll += overHours
# heading3
print("{0:15s}{1:15s}{2:2d}{3:10d}{4:14d}{5:24.2f}".format(firstName, lastName, regHours, payRate, overHours, grossPay))
# space heading
print(" ")
# overall stats
print("{0:15s}{1:21.2f}".format("Total Gross Pay", grossPayAll))
print("{0:15s}{1:19.2f}".format("Average Gross Pay", grossPayAll / len(data)))
print("{0:15s}{1:16d}".format("Total Overtime Hours", overHoursAll))
Best regards, I am sorry for my English.
Well, I think, you probably want data2 = [word.rstrip("\n") for word in tmp], but without seeing sample input and desired output it's hard to tell.
Also,
first[2]=(int(first[2]))
first[3]=(int(first[3]))
initialHours = first[2]
payRate = first[3]
Could be:
initialHours = int(first[2])
payRate = int(first[3])
But you'd also need to change other references to first[2]
Finally, I'd change
if os.path.isfile(fileQuestion) == True:
file = open('emps', 'r')
data = file.readlines()
for tmp in data:
to:
if os.path.isfile(fileQuestion) == True:
with open('emps', 'r') as myfile:
for tmp in myfile:
This ensures that the file gets closed properly (your code doesn't close it), and iterates directly through the file, rather than using readlines() which needlessly reads the entire file to memory before doing enything else. Note that file is a python builtin, so a bad choice of variable name.
You are using these lines:
data = file.readlines()
for tmp in data:
which already splits your data into lines, and iterates through them. That means that this line [data2= [word.rstrip("\n") for word in data]] is setting data2 to be the first line EVERY TIME, which renders the original for loop useless.
Try instead:
tmp = tmp.split()
which will split each line as you iterate, you can now call tmp as a list, like you called first except it will reflect the values for each line.
You could also change your original for loop to:
for tmp in file:
since file objects in python are generators that yield each line (this saves you some memory space)
try these changes:
totothrs = 0
totgross = 0.0
employees = 0
for tmp in data:
employees += 1
fname, lname, rate, hrs = tm.split()
hrs = int(hrs)
rate = float(rate)
othrs = 0
if hrs > 40:
othrs = hrs - 40
hrs = hrs - othrs
totothrs += othrs
gross = rate * hrs + (1.5*rate)*othrs
totgross += gross
heading3= "{0:15s}{1:15s}{2:2d}{3:10d}{4:14d} {5:24.2f}".format(firstName, lastName, hrs, rate, othrs, gross)
print heading3
spaceHeading = " "
heading4= "{0:15s}{1:21.2f}".format("Total Gross Pay", totgross)
heading5= "{0:15s}{1:19.2f}".format("Average Gross Pay", (totgross/employees)
heading6= "{0:15s}{1:16d}".format("Total Overtime Hours", totothrs)
print heading4
print heading5
print heading6
Note: you dontneed to define the "headingN"'s you can just print them
import os.path
import sys
#fileQuestion = input("What is the name of your file?: ")
fileQuestion = "Testfile.txt"
heading1 = "{0:15s}{1:15s}{2:10s}{3:15s}{4:20s}{5:15s}".format("First Name", "Last Name", "Hours", "Payrate", "Overtime Hours", "Gross Pay")
heading2= "=============================================================================================================="
print(heading1)
print(heading2)
if os.path.isfile(fileQuestion) == True:
file_handle = open(fileQuestion, 'r')
#file = open('emps', 'r')
#data = file.readlines() I would't go for readline here
#file_handle2 = open('outupt.txt')
total_gross_pay = 0
number_of_employees = 0
average_gross_pay = 0
total_overtime = 0
standard_working_hours = 40
for i in file_handle:
data = i.rstrip().lstrip().split()
#print (data)
first_name, last_name, hours, payrate = data
hours = int(hours)
payrate = int(payrate)
basic_pay = hours * payrate
if(hours > standard_working_hours):
overtime = hours - standard_working_hours
overtime_premium = overtime * payrate
gross_pay = overtime_premium + basic_pay
else:
overtime = 0
gross_pay = basic_pay
total_overtime += overtime
total_gross_pay += gross_pay
number_of_employees += 1
print("{0:15s}{1:15s}{2:10s}{3:15s}{4:20s}{5:15s}".format(first_name, last_name, str(hours), str(payrate), str(overtime), str(gross_pay)))
print('\n')
print("Total Gross Pay: ",total_gross_pay)
print("Average Gross Pay: ",total_gross_pay/number_of_employees)
print("Total overtime: ",total_overtime)

(beginner) Python program functions when completely only when functions are run separately. Tournament tracking program:

All of this code functions perfectly when run alone. However, when i choose the standings option after i have run the new and fixture option the code throws an error. Any assistance on this matter would be greatly appreciated.
main():
print ("Welcome to Tournament Tracker")
print ("would you like to begin a new tournament (new), input the results of a fixture (fixture) or view the tournament standings(standings)")
#allows the user to choose from several options including accesing an old tournament or creating a new one.
response = input()
#defines a variable "response" which will be checked against predefined, suggested responses using a slection statement
if response == "new":
#selection statment checks if variable "response" is = "new" and, if true, executes the following code
print ("enter in the name of the tournament")
tournamentName = input()
#creates variable tournamentName and sets it to user input
with open(tournamentName + ".txt",mode="w",encoding = "utf-8") as tournamentfile:
pass
#creates file "tournamentName + ".txt""
print ("enter in the number of teams in the tournament")
numberOfTeams = int(input())
allPoints = int(0)
awayPoints = int(0)
#initalises the two variables "allPoints" and "awayPoints" to be written to text file
counter = int(0)
#initialises temporary variable counter to be used for iteration
while counter < numberOfTeams:
# while loop executes the following code unless the condition "counter" < "number of teams"
counter = counter +1
#one is added to the counter to ensure that the condition "counter" < "number of teams" will be met
print ("enter in the name of team {0}".format(counter))
teamName = input()
#asks the user for the name of each team linked to variable counter
print ("Team {0} is {1}".format(counter,teamName))
with open(teamName + "Points.txt", mode="w",encoding="utf-8") as allPointsfile:
allPointsfile.write(str(allPoints))
#creates a txt file based on the variable "teamName", with "Points.txt" appended to it,
#inputted by the user and writes the variable "allPoints" to it
with open(teamName + "AwayPoints.txt", mode = "w",encoding = "utf-8") as awayPointsfile:
awayPointsfile.write(str(awayPoints))
#creates a txt file based on the variable "teamName", with "AwayPoints.txt" appended to it,
#inputted by the user and writes the variable "awayPoints" to it
with open(tournamentName + ".txt", mode="a",encoding="utf-8") as tournamentfile:
tournamentfile.write(teamName +"\n")
tournamentfile.write(str(allPoints) + "\n")
tournamentfile.write(str(awayPoints) + "\n")
#creates a txt file based on the variable "tournamentName", with ".txt" appended to it,
#inputted by the user and writes the variables "teamName", "allPoints" and "awayPoints" to it,
#each on a new line
print("You may now add the results of fixtures")
main()
#informs the user that the next recommended option should be to input the results of a fixture
#and then calls the main function to give the user access to the all the options again
elif response == "fixture":
#selection statment checks if variable "response" is = "fixture" and, if true,then executes the following code
print ("enter in the name of the tournament")
tournamentName = input()
print ("enter in the name of the first (home) team")
teamOne = str(input())
print ("enter in the name of the second (away) team")
teamTwo = str(input())
print ("enter in the number of goals scored by the first team in their home fixture")
teamOneScore = input()
print("enter in the number of goals scored by the second team in the same fixture")
teamTwoScore = input()
#initialises variables "tournamentName", "teamOne", "teamOne", "teamOneScore" and "teamTwoScore"
if teamOneScore > teamTwoScore:
#selection statment checks if the variable "teamOneScore" > "teamTwoScore" and if true, executes the following code
with open(teamOne + "Points.txt", mode="r",encoding="utf-8") as allTeamOnePointsfile:
allTeamOnePoints = allTeamOnePointsfile.read()
if allTeamOnePoints == '':
allTeamOnePoints = 0
allTeamOnePoints = int(allTeamOnePoints) + int(3)
#opens the file " teamOne (variable) + "Points.txt"" in read mode and reads the file. If statement checks if the file is empty
#and sets the value read, defined as "allTeamOnePoints" to 0 to avoid an error. Then adds 3 to "allTeamOnePoints"
with open(teamOne + "Points.txt", mode="w",encoding="utf-8") as allTeamOnePointsfile:
allTeamOnePointsfile.write(str(allTeamOnePoints))
#opens the file " teamOne (variable) + "Points.txt"" in write mode and writes the variable "allTeamOnePoints" to the file.
print("{0} now has {1} points".format(teamOne,allTeamOnePoints))
#outputs the team name and the total number of points that team has
with open(teamTwo + "Points.txt", mode="r",encoding="utf-8") as allTeamTwoPointsfile:
allTeamTwoPoints = allTeamTwoPointsfile.read()
if allTeamTwoPoints == '':
allTeamTwoPoints = 0
#opens the file " teamTwo (variable) + "Points.txt"" in read mode and reads the file. If statement checks if the file is empty
#and sets the value read, defined as "allTeamTwoPoints" to 0 to avoid an error.
print("{0} now has {1} points".format(teamTwo,allTeamTwoPoints))
#outputs the total points for teamTwo
with open(tournamentName + ".txt", mode = "r", encoding = "utf-8") as tournamentFile:
tournamentList1 = tournamentFile.readlines()
tournamentList = [elem.strip("\n")for elem in tournamentList1]
#open the file "tournamentName (variable) + ".txt"" and reads it, with each line defined as a different element of an array
#then strips the ""\n"" from the end of each element and defines the variable "tournamentList"
index = 0
#initialises temporary variable "index"
noOfTeams = int(len(tournamentList))
#initialises variable "noOfTeams" as the length of the arrray "tournamentList"
while index < noOfTeams:
#while loop checks if temporary variable "index" < "noOfTeams"
if teamOne == tournamentList[index]:
tournamentList[index]= teamOne
tournamentList[index+1] = allTeamOnePoints
index = index +1
#selection statement checks if the variable "teamOne" is equal to the index'th element of the array "tournamentList"
#sets variable "teamOne" to the index'th element of array "tournamentList" if the previous condition is true
#sets variable "allTeamOnePoints" to the index'th element of array "tournamentList" if the previous condition is true
#adds 1 to index to allow for iteration
elif teamOne != tournamentList[index]:
index = index +1
#selection statement checks if the variable "teamOne" is equal to the index'th element of the array "tournamentList"
#adds 1 to index to allow for iteration
index2 = 0
#initialises temporary variable "index"
while index2 < noOfTeams:
if teamTwo == tournamentList[index2]:
tournamentList[index2] = teamTwo
tournamentList[index2+1] = allTeamTwoPoints
index2 = index2 +1
#selection statement checks if the variable "teamTwo" is equal to the index2'th element of the array "tournamentList"
#sets variable "teamTwo" to the index'th element of array "tournamentList" if the previous condition is true
#sets variable "allTeamTwoPoints" to the index'th element of array "tournamentList" if the previous condition is true
#adds 1 to index2 to allow for iteration
elif teamTwo != tournamentList[index2]:
index2 = index2 +1
#selection statement checks if the variable "teamTwo" is equal to the index'th element of the array "tournamentList"
#adds 1 to index2 to allow for iteration
with open(tournamentName + ".txt", mode = "w", encoding = "utf-8") as tournamentFile:
for counter in range (len(tournamentList)):
#for loop executes the following code the once for each element in array "tournamentList"
tournamentFile.write(str(tournamentList[counter]) + "\n")
#writes variable "tournamentList" to "tournamentName + ".txt"" using for loop
main()
#calls back the function "main()"
elif teamOneScore == teamTwoScore:
#the following code is very similar to the above code. Please see above code for documentation.
with open(teamOne + "Points.txt", mode="r",encoding="utf-8") as allTeamOnePointsfile:
allTeamOnePoints = allTeamOnePointsfile.read()
if allTeamOnePoints == '':
allTeamOnePoints = 0
allTeamOnePoints = int(allTeamOnePoints) + int(1)
with open(teamOne + "Points.txt", mode="w",encoding="utf-8") as allTeamOnePointsfile:
allTeamOnePointsfile.write(str(allTeamOnePoints))
print("{0} now has {1} points".format(teamOne,allTeamOnePoints))
with open(teamTwo + "Points.txt", mode="r",encoding="utf-8") as allTeamTwoPointsfile:
allTeamTwoPoints = allTeamTwoPointsfile.read()
if allTeamTwoPoints == '':
allTeamTwoPoints = 0
allTeamTwoPoints = int(allTeamTwoPoints) + int(1)
with open(teamTwo + "Points.txt", mode="w",encoding="utf-8") as allTeamTwoPointsfile:
allTeamTwoPointsfile.write(str(allTeamTwoPoints))
print("{0} now has {1} points".format(teamTwo,allTeamTwoPoints))
with open(teamTwo + "AwayPoints.txt",mode = "r",encoding="utf-8") as awayPointsfile:
awayPoints = awayPointsfile.read()
if awayPoints == '':
awayPoints = 0
awayPoints = int(awayPoints) + int(1)
with open(teamTwo + "AwayPoints.txt",mode = "w",encoding="utf-8") as awayPointsfile:
awayPointsfile.write(str(awayPoints))
with open(tournamentName + ".txt", mode = "r", encoding = "utf-8") as tournamentFile:
tournamentList1 = tournamentFile.readlines()
tournamentList = [elem.strip("\n")for elem in tournamentList1]
index = 0
noOfTeams = int(len(tournamentList))
while index < noOfTeams:
if teamOne == tournamentList[index]:
tournamentList[index]= teamOne
tournamentList[index+1] = allTeamOnePoints
index = index+1
elif teamOne != tournamentList[index]:
index = index +1
index2 = 0
while index2 < noOfTeams:
if teamTwo == tournamentList[index2]:
tournamentList[index2] = teamTwo
tournamentList[index2+1] = allTeamTwoPoints
tournamentList[index2+2] = awayPoints
index2 = index2+1
elif teamTwo != tournamentList[index]:
index2 = index2 +1
with open(tournamentName + ".txt", mode = "w", encoding = "utf-8") as tournamentFile:
for counter in range (len(tournamentList)):
tournamentFile.write(str(tournamentList[counter]) + "\n")
print (tournamentList)
main()
elif teamOneScore < teamTwoScore:
#the following code is very similar to the above code. Please see above code for documentation.
with open(teamTwo + "Points.txt", mode="r",encoding="utf-8") as allTeamTwoPointsfile:
allTeamTwoPoints = allTeamTwoPointsfile.read()
if allTeamTwoPoints == '':
allTeamTwoPoints = 0
allTeamTwoPoints = int(allTeamTwoPoints) + int(3)
with open(teamTwo + "Points.txt", mode="w",encoding="utf-8") as allTeamTwoPointsfile:
allTeamTwoPointsfile.write(str(allTeamTwoPoints))
print("{0} now has {1} points".format(teamTwo,allTeamTwoPoints))
with open(teamTwo + "AwayPoints.txt",mode = "r",encoding="utf-8") as awayPointsfile:
awayPoints = awayPointsfile.read()
if awayPoints == '':
awayPoints = 0
awayPoints = int(awayPoints) + int(3)
with open(teamTwo + "AwayPoints.txt",mode = "w",encoding="utf-8") as awayPointsfile:
awayPointsfile.write(str(awayPoints))
with open(teamOne + "Points.txt", mode="r",encoding="utf-8") as allTeamOnePointsfile:
allTeamOnePoints = allTeamOnePointsfile.read()
if allTeamOnePoints == '':
allTeamOnePoints = 0
print("{0} now has {1} points".format(teamOne,allTeamOnePoints))
with open(tournamentName + ".txt", mode = "r", encoding = "utf-8") as tournamentFile:
tournamentList1 = tournamentFile.readlines()
tournamentList = [elem.strip("\n")for elem in tournamentList1]
index = 0
noOfTeams = int(len(tournamentList))
while index < noOfTeams:
if teamOne == tournamentList[index]:
tournamentList[index]= teamOne
tournamentList[index+1] = allTeamOnePoints
index = index+1
elif teamOne != tournamentList[index]:
index = index +1
index2 = 0
while index2 < noOfTeams:
if teamTwo == tournamentList[index2]:
tournamentList[index2] = teamTwo
tournamentList[index2+1] = allTeamTwoPoints
tournamentList[index2+2] = awayPoints
index2 = index2 + 1
elif teamTwo != tournamentList[index2]:
index2 = index2 +1
with open(tournamentName + ".txt", mode = "w", encoding = "utf-8") as tournamentFile:
for counter in range (len(tournamentList)):
tournamentFile.write(str(tournamentList[counter]) + "\n")
print (tournamentList)
main()
elif response == "standings":
#selection statment checks if variable "response" is = "fixture" and, if true,then executes the following code
results()
def results():
print ("enter in the name of the tournament you would like to access")
tournamentName1 = input()
#creates variable "tournamentName" and sets it equal to user input
with open (tournamentName1 + ".txt", mode = "r", encoding = "utf-8") as tournamentFile:
tournamentTeam1 = tournamentFile.readlines()[::3]
tournamentTeams1 = [elem.strip("\n")for elem in tournamentTeam1]
#opens the file "tournamentName + ".txt"" and reads every third line into a list. Then strips ""\n"" from every element
#defines the variable "tournamentTeams" as an array of al teams in the tournament
with open (tournamentName1 + ".txt", mode = "r", encoding = "utf-8") as tournamentFile:
tournamentPoint1 = tournamentFile.readlines()[1::3]
tournamentPoints1 = [elem.strip("\n")for elem in tournamentPoint1]
#opens the file "tournamentName + ".txt"" and reads every third line starting from the second element
#into a list. Then strips ""\n"" from every element
#defines the variable "tournamentPoints" as an array with all the total points for each team
with open (tournamentName1 + ".txt", mode = "r", encoding = "utf-8") as tournamentFile:
tournamentAwayPoint1 = tournamentFile.readlines()[2::3]
tournamentAwayPoints1 = [elem.strip("\n")for elem in tournamentAwayPoint1]
#opens the file "tournamentName + ".txt"" and reads every third line starting from the third element
#into a list. Then strips ""\n"" from every element
#defines the variable "tournamentAwayPoints" as an array with all the total away points for each team
order = []
#defines temporary array order as an empty array
pos = 0
#defines temporary variable "pos" as equal to 0
for count in range(len(tournamentTeams1)):
order.append(count)
#creates an array of indexes of the teams
for count in range(len(tournamentTeams1)-1):
if (tournamentPoints1[order[pos]] < tournamentPoints1[order[pos+1]]):
#compares the scores of two consecutive teams and switches them
temp = order[pos]
#temporary variable stores the index of the team
order[pos] = order[pos+1]
order[pos+1] = temp
#switches the order of the teams
elif (tournamentPoints1[order[pos]] == tournamentPoints1[order[pos+1]] and tournamentAwayPoints1[order[pos]] <tournamentAwayPoints1[order[pos+1]]):
#if the score is equal, we compare the away score
temp = order[pos]
order[pos] = order[pos+1]
order[pos+1] = temp
#same logic as prior
pos = pos +1
#adds 1 to variable "pos" in order to allow for iteration
index3 = 0
#defines temporary variable index as equal to 0
print()
for count in range(len(order)):
index3 = index3 + 1
print('{0}: {1} (score {2}) (away score {3})'.format(index3,tournamentTeams1[order[count]],tournamentPoints1[order[count]],tournamentAwayPoints1[order[count]]))
print("Congratulations to team {0} for winning the tournament!".format(tournamentTeams1[order[pos]]))
#print outs the winning team of the tournament
the exact error message:
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
main()
File "/Users/MunshiMuhammed/Desktop/Coursework Coding Folder/Actually done coursework m8 (2).py", line 47, in main
main()
File "/Users/MunshiMuhammed/Desktop/Coursework Coding Folder/Actually done coursework m8 (2).py", line 129, in main
main()
File "/Users/MunshiMuhammed/Desktop/Coursework Coding Folder/Actually done coursework m8 (2).py", line 244, in main
results()
File "/Users/MunshiMuhammed/Desktop/Coursework Coding Folder/Actually done coursework m8 (2).py", line 296, in results
print("Congratulations to team {0} for winning the tournament!".format(tournamentTeams1[order[pos]]))
IndexError: list index out of range
The text file that is being read from in the results function:
(the first line the team name, the second is the home points and the third is the away points. the next line is the next team)
3
0
0
4
3
0
These are the print statements asked for (tournamentTeams1, order and pos)
['3', '4']
[1, 0]
1
1: 4 (score 3) (away score 0)
['3', '4']
[1, 0]
1
2: 3 (score 0) (away score 0)
Congratulations to team 3 for winning the tournament!
Once again, this function only works if it is accessed after a restart of the idle.
As mentioned in the comments, that's a lot of code to wade through.
To get better responses MCVE is key. Take a look at the error message, and you see that it's occurring in the results function. So you should try to replicate the error with just that function, plus some minimal data. If you can't, you need to check what inputs are going into the function (which is what inserting the print statements were about). Then figure out what bits of your code was producing those weird inputs, and try to isolate that bit of the code. Repeat the process until you've narrowed down the area of code where the problem is likely to lie. Then post the bit of the code, along with the inputs and outputs. Welcome to the wonderful world of debugging!
All that said, I did go through the code, and I think I know what's going wrong.
When you call main() recursively, you are actually calling it without closing the tournamentName file, and then you are trying to access that same file in the results() function. Below is the problematic recursive call to main(), in the 'fixtures' part of your code.
with open(tournamentName + ".txt", mode = "w", encoding = "utf-8") as tournamentFile:
for counter in range (len(tournamentList)):
#for loop executes the following code the once for each element in array "tournamentList"
tournamentFile.write(str(tournamentList[counter]) + "\n")
#writes variable "tournamentList" to "tournamentName + ".txt"" using for loop
main() #Notice the indentation!
The indentation means the tournamentName.txt file is going to already be accessed in write mode, so you are getting an empty file when you try accessing it from the results() function. Your results() function throws an IndexError at the final line if the tournamentName.txt file is empty.
The immediate solution is to take the recursive call to main() outside of the with open(...), i.e. it should look like:
with open(tournamentName + ".txt", mode = "w", encoding = "utf-8") as tournamentFile:
#Your for loop remains here
main() #At this point tournamentName.txt is closed, available for results() to access
You need to update it in all three places of your code where this occurs.
On the other hand, as #pm-2ring states, recursive calls to main() is probably not the best idea. I would strongly recommend restructuring your code so that the main function becomes a loop that looks like below.
def main():
print("Welcome to Tournament Tracker")
while True:
response = input("would you like to begin a new tournament (new), input the results of a fixture (fixture) or view the tournament standings(standings)\n")
if response == "new":
create_new_tournament()
elif response == "fixture":
add_fixtures()
elif response == "standings":
print_results()
return
I noticed four other big issues with your code:
Your results() function has a bug where the team with the lowest score ends up at the end of the order list, while it should be the team with the highest score.
Your main() function is way way too long. Splitting it into pieces will help a lot with what I wrote at the start - small functions make it easy to isolate the part of the code that is causing problems, and make it easy to post small code snippets onto stackoverflow.
Your comments describe what the code is doing too literally, and don't give enough details on what the intended effects are. After you write short functions, you should explain what inputs those functions expect, and what output they are supposed to produce. Often, that's all the commenting you need in Python (assuming you're careful with function and variable names!)
Your code has a lot of duplication, especially in the 'fixtures' section. You need to try hard not to copy and paste code, because that makes debugging/updating much harder - you might fix one bit of the code but forget an identical section.

(Python) List index out of range when trying to pull data out of a .CSV?

This program pulls data out of two .CSV files, which are linked here:
https://drive.google.com/folderview?id=0B1SjPejhqNU-bVkzYlVHM2oxdGs&usp=sharing
It's supposed to look for anything after a comma in each of the two files, but my range logic is somehow wrong. I'm running a traceback error to line 101:
"line 101, in calc_corr: sum_smokers_value = sum_smokers_value + float(s_percent_smokers_data[r][1])
IndexError: list index out of range"
I assume it would do the same for the other times [k][1] shows up.
many thanks in advance if there's a way to fix this.
the program so far is:
# this program opens two files containing data and runs a corralation calculation
import math
def main():
try:
print('does smoking directly lead to lung cancer?')
print('''let's find out, shall we?''''')
print('to do so, this program will find correlation between the instances of smokers, and the number of people with lung cancer.')
percent_smokers, percent_cancer = retrieve_csv()
s_percent_smokers_data, c_percent_cancer_data = read_csv(percent_smokers, percent_cancer)
correlation = calc_corr(s_percent_smokers_data, c_percent_cancer_data,)
print('r_value =', corretation)
except IOError as e:
print(str(e))
print('this program has been cancelled. run it again.')
def retrieve_csv():
num_times_failed = 0
percent_smokers_opened = False
percent_cancer_opened = False
while((not percent_smokers_opened) or (not percent_cancer_opened)) and (num_times_failed < 5):
try:
if not percent_smokers_opened:
percent_smokers_input = input('what is the name of the file containing the percentage of smokers per state?')
percent_smokers = open(percent_smokers_input, 'r')
percent_smokers_opened = True
if not percent_cancer_opened:
percent_cancer_input = input('what is the name of the file containing the number of cases of lung cancer contracted?')
percent_cancer = open(percent_cancer_input, 'r')
percent_cancer_opened = True
except IOError:
print('a file was not located. try again.')
num_times_failed = num_times_failed + 1
if not percent_smokers_opened or not percent_cancer_opened:
raise IOError('you have failed too many times.')
else:
return(percent_smokers, percent_cancer)
def read_csv(percent_smokers, percent_cancer):
s_percent_smokers_data = []
c_percent_cancer_data = []
empty_list = ''
percent_smokers.readline()
percent_cancer.readline()
eof = False
while not eof:
smoker_list = percent_smokers.readline()
cancer_list = percent_cancer.readline()
if smoker_list == empty_list and cancer_list == empty_list:
eof = True
elif smoker_list == empty_list:
raise IOError('smokers file error')
elif cancer_list == empty_list:
raise IOError('cancer file error')
else:
s_percent_smokers_data.append(smoker_list.strip().split(','))
c_percent_cancer_data.append(cancer_list.strip().split(','))
return (s_percent_smokers_data, c_percent_cancer_data)
def calc_corr(s_percent_smokers_data, c_percent_cancer_data):
sum_smokers_value = sum_cancer_cases_values = 0
sum_smokers_sq = sum_cancer_cases_sq = 0
sum_value_porducts = 0
numbers = len(s_percent_smokers_data)
for k in range(0, numbers):
sum_smokers_value = sum_smokers_value + float(s_percent_smokers_data[k][1])
sum_cancer_cases_values = sum_cancer_cases_values + float(c_percent_cancer_data[k][1])
sum_smokers_sq = sum_smokers_sq + float(s_percent_smokers_data[k][1]) ** 2
sum_cancer_cases_sq = sum_cancer_cases_sq + float(c_percent_cancer_data[k][1]) ** 2
sum_value_products = sum_value_products + float(percent_smokers[k][1]) ** float(percent_cancer[k][1])
numerator_value = (numbers * sum_value_products) - (sum_smokers_value * sum_cancer_cases_values)
denominator_value = math.sqrt(abs((numbers * sum_smokers_sq) - (sum_smokers_value ** 2)) * ((numbers * sum_cancer_cases_sq) - (sum_cancer_cases_values ** 2)))
return numerator_value / denominator_value
main()
The values in each row of your data files are not comma separated, but rather tab separated. You need to change the ',' delimiter character you're splitting on for '\t'. Or perhaps use the csv module and tell it that your delimiter is '\t'. You can read more about the csv module in the documentation.

Categories

Resources