简体   繁体   中英

How to sum specific integer values of Python List

I'm trying to sum integer values from the list using sum function. Unfortunately, it is adding all the values of the list but not those which I need from the user.

Here is my code:

tourist_attractions = []
distance = []
entry_cost = []

for i in range(3):
    tourist_attractions.append (input("Enter Tourist place: "))


    tourist_distance =(int(input("Enter distance: ")))

    if tourist_distance > 50:
        print("Invalid Entry")
        continue

    if tourist_distance <= 50:
        distance.append(tourist_distance)

    cost = (float(input("Enter cost: ")))

    if cost > 100:
        print("cost must be between 1-100")
        continue

    if cost > 0 or cost <= 100:
        entry_cost.append(cost)

print()

for line in tourist_attractions:
    print("Place:", line)

for line in distance:
    print("Distance:", line)

for line in entry_cost:
    print("Cost:", line)


print()

number_of_places_to_visit = int(input("Total number of places to visit: "))

x = 1

while x <= number_of_places_to_visit:

    select_tourist_place = input("select tourist place, 0-3: ")

    x = x + 1


    if select_tourist_place == "0":
        print(tourist_attractions[0], distance[0], entry_cost[0])

    elif select_tourist_place == "1":
        print(tourist_attractions[1], distance[1], entry_cost[1])

    elif select_tourist_place == "2":
        print(tourist_attractions[2], distance[2], entry_cost[2])

    elif select_tourist_place == "3":
        print(tourist_attractions[3], distance[3], entry_cost[3])

    elif select_tourist_place == "4":
        print(tourist_attractions[4], distance[4], entry_cost[4])



print("total cost: " , sum(entry_cost))

Result I am getting:

Enter Tourist place: London
Enter distance: 25
Enter cost: 15
Enter Tourist place: Manchester
Enter distance: 30
Enter cost: 15
Enter Tourist place: Scotland
Enter distance: 50
Enter cost: 20

Place: London
Place: Manchester
Place: Scotland
Distance: 25
Distance: 30
Distance: 50
Cost: 15.0
Cost: 15.0
Cost: 20.0

Total number of places to visit: 2
select tourist place, 0-3: 0
London 25 15.0
select tourist place, 0-5: 1
Manchester 30 15.0
total cost:  50.0
>>> 

I can understand, at the moment it is summing up all the appended list of entry_cost and giving me the total of 50 which should be 15 from London and 15 from Manchester. Any help?

print("total cost: " , sum(entry_cost))

definitely states your are iterating over ALL entry costs. You would want to store the selected indices and sum over the entries of those indices.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM