def sort_list(x):
N=len(x)
for i in range(N-1):
for j in range(N-1, i, -1):
if x[j] < x[j-1]:
x[j], x[j-1] = x[j-1], x[j]
Name_List = []
#Creates a file with names of soldiers
fout = open('soldiers.txt','w')
for i in range(10):
name = raw_input("Type Soldier name:")
fout.write(name+'\n')
fout.close()
#A Adds the names into a list
fin = open('soldiers.txt', 'r')
for line in fin.readlines():
Name_List.append(line)
fin.close()
#B Sorts the list in an alphabetical order
List_Sorting = sort_list(Name_List)
#Enters the sorted names into a new file
fout = open('soldiersSort.txt','w')
for i in range(len(Name_List)):
fout.writelines(Name_List[i]+'\n')
fout.close()
#G Counts the total amount of soldiers from the 'soldiersSort.txt' file
fin = open('soldiersSort.txt','r')
s=0
for line in fin.readlines():
s = s + int(line)
fin.close()
#A Prints the list of names in alphabetical order
print Name_List
#G Prints the number of sodliers
print 'Number of soldiers:', s
This here is an exercise I worked on and there's just one thing I can't figure out, and that's how to convert string data (in this case the names of soldiers) into integers in order to add them. I will list below some ways I tried and the errors it printed. I'm using python 2.7.10 and recently started using the software called "PyCharm Community Edition" (same python version there). If I didn't include anything important just ask me and I'll try to answer my best.
1#
fin = open('soldiersSort.txt','r')
s=0
for line in fin.readlines():
s = s + int(line)
fin.close() --> Error (ValueError: invalid literal for int() with
base 10:) with a random name from the list after the ':'
2#
fin = open('soldiersSort.txt','r')
s=0
int_line = int(line)
for line in fin.readlines():
s = s + int_line
fin.close() --> Error (same as the above with just a different name
from the list after the ':')
3#
fin = open('soldiersSort.txt','r')
s=0
for line in fin.readlines():
s = s + int(float(line))
fin.close() --> Error (ValueError: could not convert string to
float:'name from the list')