car_file = open("car.txt", "r")
count = 0
for car_record in car_file:
car_record = car_record.strip('\n')
value = car_record.split(',')
print((count+1),'.', car_record)
count+=1
car_file.close()
car.txt
I want to only print the line that [7] is available
Since your availability is in the last column, you could use value[-1] to access it. I think you should have a look at if statements first. However, here is some code to help you out:
car_file = open("car.txt", "r")
count = 0
for car_record in car_file:
car_record = car_record.strip('\n')
value = car_record.split(',')
if value[-1] == "AVAILABLE":
print((count+1),'.', car_record)
count+=1
car_file.close()
Check if string is in value:
print(value) if 'AVAILABLE' in value else False
Related
I'm trying to iterate through a csv file, and am getting this error when calling the haversine function to calculate the distance between two locations. I'm confused because the variable seems to be assigned above?
def distance(dep, dest):
depfound = False
arrfound = False
for rowm in csv_reader:
for row in rowm.items():
if depfound == True and arrfound == True:
print ("BREAKING")
break
else:
if row[0] == (dep):
print (row[0])
depcoord = row[11]
print (depcoord)
depfound = True
if row[0] == (dest):
arrcoord = row[11]
print (arrcoord)
arrfound = True
print (haversine(depcoord, arrcoord))
distance("EGKK", "LFMN")
This is because in case your control doesnt come to "else", then the variable is undefined as the print will be executed in all cases.
Following should work
def distance(dep, dest):
depfound = False
arrfound = False
depcoord = None # or any other value as default eg - False
arrfound = None
for rowm in csv_reader:
for row in rowm.items():
if depfound == True and arrfound == True:
print ("BREAKING")
break
else:
if row[0] == (dep):
print (row[0])
depcoord = row[11]
print (depcoord)
depfound = True
if row[0] == (dest):
arrcoord = row[11]
print (arrcoord)
arrfound = True
print (haversine(depcoord, arrcoord))
distance("EGKK", "LFMN")
You call a print with an uninitialized variable. Initialize the variable depcoord = False.
I want to make a program that adds a name in the dictionary if it doesn't exist already and count the times it is given as input. My code works, however, it doesn't add 1 when it iterates.
namelist = {}
def namen():
while True:
word = input('Vul een naam in: ')
if word == '':
break
else:
for name in namelist:
if word == name:
namelist[word] += 1
# else wasn't properly indented earlier
else:
namelist[word] = 1
print(namen())
print(namelist)
You can use the dict.get method instead to provide a default value to a new entry to the dict:
namelist = {}
def namen():
while True:
word = input('Vul een naam in: ')
if word == '':
break
else:
for name in namelist:
if word == name:
namelist[word] = namelist.get(word, 0) + 1
Your check is incorrect, you need if rather than for to see if the key exists, then you can remove the inner if statement
if name in namelist:
namelist[word] += 1
else:
namelist[word] = 1
No one said anything about the has_key method of dictionaries, which is in my opinion the standard way to to this:
namelist = {}
def namen():
while True:
word = input('Vul een naam in: ')
if word == '':
break
else:
if namelist.has_key(word):
namelist[word] += 1
else:
namelist[word] = 1
print(namen())
print(namelist)
try this
namelist = {}
def namen():
while True:
word = input('Vul een naam in: ')
if word == '':
break
else:
try:
namelist[word] += 1
except:
namelist[word] = 1
print(namen())
print(namelist)
My code is to print the average of tuples in a list and to return None if the list is empty. Right now this is my code
def average_vehicles(vehicle_records):
"""Return average of vehicles"""
summ = 0
num = 0
average = 0
if vehicle_records != []:
for value in vehicle_records:
summ += value[1]
num += 1
average = summ / num
else:
average = "None"
return average
I get the correct output for this test code:
some_records = [('2010-01-01',100),
('2010-01-02',200),
('2010-01-03',300)]
avg = average_vehicles(some_records)
print(avg)
However I can't get it to print "OK" for the following test code and I'm not sure why it isn't doing the job when everything else looks right, can someone please help?
some_records = []
avg = average_vehicles(some_records)
if avg is None:
print('OK')
else:
print('The function should return a None value')
you're returning the string "None" instead of the object None
None shouldn't be a string but a None object.
Change the following line average = "None" to average = None and it should work.
None and "None" are not the same thing.
some_records = []
avg = average_vehicles(some_records)
if avg == "None":
print('OK')
else:
print('The function should return a None value')
some_records = []
avg = average_vehicles(some_records)
if avg == 'None':
print('OK')
else:
print('The function should return a None value')
Explanation:
When we print the type of avg it is of type str but if we check avg is None, in this None is of type Nonetype. So we need to check using "None" as avg == 'None'
I'm making a conditional statement in openpyxl Python to check if a cell is empty. Here's my code:
newlist = []
looprow = 1
print ("Highest col",readex.get_highest_column())
getnewhighcolumn = readex.get_highest_column()
for i in range(0, lengthofdict):
prevsymbol = readex.cell(row = looprow,column=getnewhighcolumn).value
if prevsymbol == "None":
pass
else:
newstocks.append(prevsymbol)
looprow += 1
#print (prevsymbol)
print(newlist)
I tried if prevsymbol == "": and if prevsymbol == null: to no avail.
You compare prevsymbol with str "None", not None object. Try
if prevsymbol == None:
Also here
prevsymbol = readex.cell(row = looprow,column=getnewhighcolumn).value
you use looprow as row index. And you increment looprow only if cell.value is not empty. Here
newstocks.append(prevsymbol)
you use newstocks instead of newlist. Try this code
newlist = []
print ("Highest col",readex.get_highest_column())
getnewhighcolumn = readex.get_highest_column()
for i in range(0, lengthofdict):
prevsymbol = readex.cell(row = i+1,column=getnewhighcolumn).value
if prevsymbol is not None:
newlist.append(prevsymbol)
print(newlist)
Take the quotes away from the None.
if prevsymbol is None:
This is the python equivalent of checking if something is equal to null.
def parse_actor_data(actor_data):
while 1:
line = actor_data.readline().strip()
if line.count('-') > 5:
break
actor_movie = {}
values = []
actor_name = ''
running_list = []
movie = []
for line in actor_data:
position = line.find(')')
running = line[:position + 1]
value = running.split('\t')
for k in value:
if k != '':
running_list.append(k)
actor_name_list = value[0].split(',')
actor_name = actor_name_list[0] + actor_name_list[-1]
for i in range(len(running_list)):
if value[0] == running_list[i]:
position2 = i
movie = running_list[position2+1:]
actor_movie[actor_name] = movie
check = actor_movie.keys()
for c in range(len(check)):
if len(check[c]) < 1:
actor_movie.pop(check[c])
return actor_movie
Problem I'm having now is that only the first item of movie is added into the actor_movie anyone can help? i tried so long for this already i seriously have no idea why isn't this working...
Every time you run:
actor_movie[actor_name] = movie
you're overwriting the last movie that was associated with that actor. Try something like this instead where you're storing a list of movies, not just a single value:
try:
actor_movie[actor_name].append(movie)
except KeyError:
actor_movie[actor_name] = [movie]
There are other ways (defaultdict, dict.setdefault, etc.) to do the same thing but that should get you up and running.