Taking user input and appending it to a tuple? Python

Viewed 46

So basically I'm trying to create a list of movies with their budgets, but I don't know how to take the input and place it into a tuple

movie_list = ()
while True:
    title = print("Enter movie: ")
    budget = print("Enter budget: ")
    movie_list.append(title, budget)
    user = input("Would you like to add more movies? (y) or (n)").upper
    if user == 'N':
        break
    if user != 'N' and 'Y':
        print("Invalid entry, please re-enter!\nContinue? (y) or (n)")
print(movie_list)
4 Answers

Tuples don't handle appending well. But lists do:


movie_list = []   # make a list, not a tuple
while True:
    title = print("Enter movie: ")
    budget = print("Enter budget: ")
    movie_list.append( (title, budget) ) # append a 2-tuple to your list, rather than calling `append` with two arguments
    user = input("Would you like to add more movies? (y) or (n)").upper
    if user == 'N':
        break
    if user != 'N' and 'Y':
        print("Invalid entry, please re-enter!\nContinue? (y) or (n)")
print(movie_list)

You can’t add elements to a tuple due to their immutable property. You can’t append for tuples.

Tuples are immutable in Python. You cannot add to a tuple.

A tuple is not a data structure like a list or an array. It's meant to hold a group of values together, not a list of the same kind of values.

I think I get what you want, my guess would be that you want a list of tuples. In that case, just change the first line variable to be a list.

I improved your code so your logic works:

movie_list = []  # movie_list is a list
while True:
    title = input("Enter movie: ")  # Use input() to get user input
    budget = input("Enter budget: ")
    movie_list.append((title, budget))  # Append a tuple to the list

    # movie_list is now a list of tuples

    # Check if the user wants to add another movie
    more = None
    # Loop until the user enters a valid response
    while True:
        more = input("Add another? (Y/N): ").upper()
        if more in ("Y", "N"):
            break
        print("Invalid input")

    # If the user doesn't want to add another movie, break out of the loop
    if more == "N":
        break

    # Else, continue the loop


print(movie_list)

Coding apart, to write any program, first one should know the purpose of the program and its outcome. It would be better, if you can show here what the exact output you want, out of the created or appended list. As far as I understood your requirement, you should go with dictionary concept so that you can store data as pairs, like, movie and its budget.

{"movie":budget}

While taking input of budget, be sure whether you want to restrict the input value to an integer or you want to allow this as a string, like in crores. Hope this will help you.

Related