Search code examples
pythonpython-3.xmergesortedlist

Python: How to alternate between two questions to retrieve user inputs for two different lists?


I'm writing a program where I get user input to fill in two lists with 3 integers each (6 in total) and to print the two sorted lists and merge it. How can I get my program to alternate between the lists and ask the user for an integer? This is how it's supposed to work:

Please enter a value for listone:
Please enter a value for listtwo: # instead I have listone displayed 3 times
Please enter a value for listone:
Please enter a value for listtwo: 

This is my code so far:

def user_input():

    listone = []
    listtwo = []

    listone_value = int(input("Please enter a value for listone: "))
    for i in range (2):
        listone_value = int(input("Please enter a value for listone: "))


    listtwo_value = int(input("Please enter a value for listtwo: "))
    for i in range(2):
        listtwo_value = int(input("Please enter a value for listtwo: "))



def merge_lists(listone, listtwo):
    list = []                  
    while listone and listtwo:        
        L.append( listone.pop(0) if listone[0] < listtwo[0] else listtwo.pop(0) )
    L.extend(listone if listone else listtwo)
    return list

I just don't know how to get the questions to alternate as I am still relatively new to the program.


Solution

  • If you know exactly how many inputs you want, just use a for loop

    def user_input():
        list_one = []
        list_two = []
        for i in range(3):
            list_one.append(int(input('Please enter a value for listone: ')))
            list_two.append(int(input('Please enter a value for listtwo: ')))
    
        return list_one, list_two