简体   繁体   中英

How to label the outputs of a looping function in alphabetical order in python

I am creating a small program that will first ask how many items you are using, and then let you convert each items weight in grams to pounds. my function currently works but I would like each time it loops to assign the outputs to variables so I can use them in a later function. Here is my current code

repeat = int(input("How many Items:"))

for i in range(repeat):
    weight = float(input("What is the weight? "))
    unit = ("pounds")
    pounds = 0.00220462
    converted_weight = float(weight * pounds)
    formatted_float = "{:.2f}".format(converted_weight)

    print(converted_weight)
    print(unit)

You can use a list which allows you to store a collection of answers.

repeat = int(input("How many Items: "))

item_weights = []

for i in range(repeat):
    weight = float(input("What is the weight? "))
    unit = "pounds"
    pounds = 0.00220462
    converted_weight = float(weight * pounds)
    formatted_float = "{:.2f}".format(converted_weight)
    print(formatted_float + ' ' + unit)
    item_weights.append(converted_weight)

# Example of iterating through a list
weight_sum = 0
for weight in item_weights:
    weight_sum += weight

print("Total weight: " + str(weight_sum))

for weight in item_weights:
    # your rest of your code here
    print(weight)

I have created a manual version of what I am trying to accomplish and I will open a new discussion requesting assistance with code that can better get my question across @JRose

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