How to use for loop with string format method

I have list :

[/codebyte]
[[‘Marina Allison’, ‘27’, ‘31.1’, ‘$7010.0’], [‘Markus Valdez’, ‘30’, ‘22.4’, ‘$4050.0’], [‘Connie Ballard’, ‘43’, ‘25.3’, ‘$12060.0’], [‘Darnell Weber’, ‘35’, ‘20.6’, ‘$7500.0’], [‘Sylvie Charles’, ‘22’, ‘22.1’, ‘$3022.0’], [‘Vinay Padilla’, ‘24’, ‘26.9’, ‘$4620.0’], [‘Meredith Santiago’, ‘51’, ‘29.3’, ‘$16330.0’], [‘Andre Mccarty’, ‘19’, ‘22.7’, ‘$2900.0’], [‘Lorena Hodson’, ‘65’, ‘33.1’, ‘$19370.0’], [‘Isaac Vu’, ‘34’, ‘24.8’, ‘$7045.0’]]

The values are name,age,bmi and insurance cost respectively.

I need to use for loop and .format string method to print like this “Marina Allison is 27 years old with a BMI of 31.1 and an insurance cost of $7010.0.” for all the names

print('Hello world!')

[/codebyte]
def details(name,age,bmi,insurance_cost):

for record in medical_records_clean:

ind_records = "{name} is {age} year olds with a BMI of {bmi} and an insurance cost of {insurance_cost}.".format(name = name, age = age, bmi = bmi, insurance_cost = insurance_cost)

name = record[0]

age = record[1]

bmi = record[2]

insurance_cost = record[3]

return ind_record

print(details(name,age,bmi,insurance_cost))

What am I missing here. Can someone please help.

Link to the project - https://www.codecademy.com/paths/data-science/tracks/dscp-python-fundamentals/modules/dscp-python-strings/projects/ds-python-strings-project

Did you mean to have an s in that spelling? Check the return statement. Should they match?

Also, should that line be after the values are extracted from the record?

Hi,

Thank you replying back to my query. I made some changes to code. But I am getting the output for only one user - “Lorena Hodson is 65 years old with a BMI of 33.1 and an insurance cost of $19370.0.” I have posted my entire code.

Here is my code:

medical_data = \ """Marina Allison ,27 , 31.1 , #7010.0 ;Markus Valdez , 30, 22.4, #4050.0 ;Connie Ballard ,43 , 25.3 , #12060.0 ;Darnell Weber , 35 , 20.6 , #7500.0; Sylvie Charles ,22, 22.1 ,#3022.0 ; Vinay Padilla,24, 26.9 ,#4620.0 ;Meredith Santiago, 51 , 29.3 ,#16330.0; Andre Mccarty, 19,22.7 , #2900.0 ; Lorena Hodson ,65, 33.1 , #19370.0; Isaac Vu ,34, 24.8, #7045.0""" # Add your code here #print(medical_data) updated_medical_data = medical_data.replace('#','$') #print(updated_medical_data) num_records = 0 for i in updated_medical_data: if i == '$': num_records += 1 #print("There are " + str(num_records) + " medical records in the data") medical_data_split = updated_medical_data.split(';') #print(medical_data_split) medical_records = [] for m_data in medical_data_split: medical_records.append(m_data.split(',')) #print(medical_records) medical_records_clean = [] for record in medical_records: record_clean = [] for item in record: record_clean.append(item.strip()) medical_records_clean.append(record_clean) print(medical_records_clean) #for record in medical_records_clean: #print(record[0].upper()) names = [] ages = [] bmis = [] insurance_costs = [] for record in medical_records_clean: names.append(record[0]) ages.append([record[1]]) bmis.append(record[2]) insurance_costs.append(record[3]) #print(names,ages,bmis,insurance_costs) total_bmi = 0 for bmi in bmis: total_bmi += float(bmi) average_bmi = (total_bmi)/(len(bmis)) #print("Average BMI: " + str(average_bmi)) total_insurance_costs = 0 for cost in insurance_costs: cost_without_dollar = cost.strip('$') total_insurance_costs += float(cost_without_dollar) average_insurance_cost = (total_insurance_costs)/(len(insurance_costs)) #print("Average Insurance Cost: " + str(average_insurance_cost)) def details(name,age,bmi,insurance_cost): for record in medical_records_clean: ind_records = "{name} is {age} years old with a BMI of {bmi} and an insurance cost of {insurance_cost}.".format(name = name, age = age, bmi = bmi, insurance_cost = insurance_cost) name = record[0] age = record[1] bmi = record[2] insurance_cost = record[3] return ind_records print(details(name = record[0],age = record[1],bmi = record[2],insurance_cost = record[3]))

Codebytes are only useful if the code fits in the window, use 3 backticks before and after your posted code for things like this.

The details function’s for loop does not do anything with ind_records before it starts the next loop, which overwrites it with new records. Once the for loop is done, it reaches the return and sends the last iteration of the for loop.

1 Like

LIne 68 should be outdented.

For the last step, rather than using a function, just revert back to the medical_records_clean list and iterate over that.

for x in medical_records_clean:
  a, b, c, d = x
  print (f"{a} is {b} years old with a BMI of {c} and an insurance cost of {d}.")

Which will output,

MARINA ALLISON is 27 years old with a BMI of 31.1 and an insurance cost of $7010.0.
MARKUS VALDEZ is 30 years old with a BMI of 22.4 and an insurance cost of $4050.0.
CONNIE BALLARD is 43 years old with a BMI of 25.3 and an insurance cost of $12060.0.
DARNELL WEBER is 35 years old with a BMI of 20.6 and an insurance cost of $7500.0.
SYLVIE CHARLES is 22 years old with a BMI of 22.1 and an insurance cost of $3022.0.
VINAY PADILLA is 24 years old with a BMI of 26.9 and an insurance cost of $4620.0.
MEREDITH SANTIAGO is 51 years old with a BMI of 29.3 and an insurance cost of $16330.0.
ANDRE MCCARTY is 19 years old with a BMI of 22.7 and an insurance cost of $2900.0.
LORENA HODSON is 65 years old with a BMI of 33.1 and an insurance cost of $19370.0.
ISAAC VU is 34 years old with a BMI of 24.8 and an insurance cost of $7045.0.
3 Likes

Hi,

Thank you for your response. The solution worked. I have a small query why we are writing this line of code - a, b, c, d = x. I can guess it. But I did not understand it fully. If you could tell me the logic, that will be helpful.

TBH, the aim was to elicit this very question, an assurance the answer is meaningful.

Python treats all comma separated values as a sequence.

>>> x = ['Mel Black', '43', '27.6', '4450.0']
>>> a, b, c, d = x
>>> a
'Mel Black'
>>> b
'43'
>>> c
'27.6'
>>> d
'4450.0'
>>> print (f"{a} is {b} years old with a BMI of {c} and an insurance cost of ${float(d):.2f}.")
Mel Black is 43 years old with a BMI of 27.6 and an insurance cost of $4450.00.
>>> 

The list (iterable) on the right has four elements. There are four variables on the left side of the assignment operator. Python has no problem unpacking the x object if there are the correct number of assignments to accommodate it, else it will raise an exception.

3 Likes

Hi,

Thank you for explaining this. This was a new learning for me. :slight_smile:

Here is an odd question.
What does the f do in the print statement?
I’m guessing is a short hand version of the .format() methid, but I just want to be sure

Yes, put the f before the quotes and you can add variables to your string.
print(f"here is my {variable}")

2 Likes

As you can see from the example given by @bavarcarus , the variable goes right into the placeholder, not as a keyword, but the actual variable itself.

If you are familiar with the .format() directives, they work pretty much the same in f-strings as they do in the previous iteration. The difference being, the variable name is placed before the colon. Well, maybe no difference, at all. One suspects keywords would have worked the same way. Need to check that.

from math import pi as PI print (f"The shortened form of PI is, {PI:.4f}")
2 Likes

F-string are not just a drop-in replacement for the .format method. The are actually expressions that evaluate to strings (if you’re unfamiliar with exactly what that means the only thing you really need to know is that the whole string is generated in one go and it tends to be quite fast, relative to the other options).

Format is a method that acts on an existing string using certain replacement fields.

a_str = "This is an x {x} and this is a y {y}"
# we don't need the values pre-defined
print(a_str.format(x=3, y=5))
b_str = "{} + {} is {}"
print(b_str.format(1, 3, 1+3))

There isn’t a route to pre-define an f-string (though you could easily wrap it in a function call or something similar). But because it’s an expression you can put almost any valid Python expression inside the f-string.

print(f"{2 ** 100} and {[x for x in range(10)]}")

If you’re on 3.8+ then these expressions got some neat syntax changes so that they can even be made self-referential so things like print(f"{2 ** 100 = }") lead to outputs of 2 ** 100 = 1267650600228229401496703205376.

3 Likes