Search code examples
pythonpython-3.xdry

How can I DRY a code which takes in several inputs, executes the same function for each input, and gives all for outputs at once?


I'm writing a code that can calculate and display the crosswind component for 4 runways at the same time.Between the inputs(selected runways) and output(crosswind component), I have 4 blocks of code that uses the same calculation for each runway. For the sake of simplicity I wrote a replex:

first_runway = int(input("Enter the 1st runway"))
second_runway = int(input("Enter the 2nd runway"))
third_runway = int(input("Enter the 3rd runway"))
fourth_runway = int(input("Enter the 4th runway"))

crosswind1 = first_runway * 2

crosswind2 = second_runway * 2

crosswind3 = third_runway * 2

crosswind4 = fourth_runway * 2

print(crosswind1, crosswind2, crosswind3, crosswind4)

Is there a way to to use "*2" just once?


Solution

  • It's simple Python. You can do something like this:

    value = []
    
    for i in range(1, 5):
        runway = int(input("Enter the {}st runway".format(i)))
        crosswind = runway * 2
        value.append(crosswind)
    
    print(value)