-1
students = [
    {'name': 'Mike', 'age': 20, 'height': 182, 'weight': 77},
    {'name': 'Tom', 'age': 21, 'height': 177,  'weight': 72},
    {'name': 'Alice', 'age': 19, 'height': 167,  'weight': 52},
    {'name': 'Left', 'age': 23, 'height': 184, 'weight': 82},
]

for i in range(len(students)-1):
    name = students[i]['name']
    age = students[i]['age']
    height = students[i]['height']
    weight = students[i]['weight']

    next_name = students[i+1]['name']
    next_age = students[i+1]['age']
    next_height = students[i+1]['height']
    next_weight = students[i+1]['weight']
 
    difference_height = height - next_height
    difference_weight = weight - next_weight

    print("{} and {} are {}, {} and the difference in height and weight are {}cm an 
{}kg".format(name, next_name, age, next_age, difference_height, difference_weight))

This is the result:

Mike and Tom are 20, 21 and the difference in height and weight are 5cm and -5kg
Tom and Alice are 21, 19 and the difference in height and weight are 10cm and -20kg
Alice and Left are 19, 23 and the difference in height and weight are -17cm and 30kg

How can I convert -17 and -30 to 17 and 30?

I know it has to be something with:

difference_height = height - next_height
difference_weight = weight - next_weight

But I don't know how to modify it.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Frank Kim
  • 3
  • 1

3 Answers3

1

You can use the abs built-in function:

difference_height = abs(height - next_height)
difference_weight = abs(weight - next_weight)
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
0

Use abs() when you want to have absolute values.

a = -5
b = 6
abs(a)
# 5
abs(b)
# 6

Also, you can use f-strings instead of format, I find it easier to read:

 print(f"{name} and {next_name} are {age}, {next_age} and the difference in height and weight are {abs(difference_height)}cm and {abs(difference_weight)}kg")
Jonas Palačionis
  • 4,591
  • 4
  • 22
  • 55
0

You can use the abs() built-in function. abs() returns the absolute value of the given number.

print("{} and {} are {}, {} and the difference in height and weight are {}cm an: {}kg".format(name, next_name, age, next_age, abs(difference_height), abs(difference_weight)))

I added abs() to the difference_ variables

sitWolf
  • 930
  • 10
  • 16