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)
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
I am making a quiz editor in Python. Inside the section of code where the user is able to remove questions from their quiz, I am given:
ValueError: list.remove(x): x not in list
Here is my code where the error is given:
# Allows the user to remove a question from the quiz
doubleCheck = ""
amountOfQuestions = 0
if choice == "3": # this is where the section of code starts where the user can remove questions
amountOfQuestions = []
print("\nQuestion List")
counter = 1
for count in range(0, len(quiz)): # gets all the questions and prints them
parts = quiz[count].split(",")
amountOfQuestions = amountOfQuestions + 1 # meanwhile this tracks how many questions there are
print("Question ", counter, " :", parts[0])
counter = counter + 1
choice = input(
str("\nChoose question number to remove (type Quit to cancel): ")) # user chooses the question they want to remove
if int(choice) <= amountOfQuestions and int(choice) > 0:
print("Question selected")
doubleCheck = input(
str("Are you sure you want to remove the quesiton? (y/n): ")) # double checks the user wants to remove the question
if doubleCheck == "y":
quiz.remove(choice) # when I choose "y", the error in the question on StackOverflow shows up here
print("Question removed")
quizEditor(quiz) # goes back to the main menu
else:
print("Operation Cancelled")
quizEditor(quiz)
elif choice == "Quit":
print("Operation cancelled - check")
quizEditor(quiz)
else:
print("invalid input")
The format of the list "Quiz" where all the questions are stored looks like this:
["The Question, The correct answer, IncorrectAnswer1,
IncorrectAnswer2, IncorrectAnswer3,"]
One question and its answers and incorrect answers are stored inside 1 element in the list and split when they are needed by referring to its index and using the .split() function.
list.remove() excepts a value to remove from the list, choice is a string with a number, for example '3', not the actual question.
If you want to remove from the quiz list by index you need to convert choice to an int and use del or pop ('pop' will return the deleted value if you need it)
index = int(choice)
del quiz[index]
# or
quiz.pop(index)
The remove() method is used to remove a matching element from the list. Assuming that you're providing the value of choice to be the index to be deleted, you can use the pop() method.
quiz.pop(choice)
What you are doing within the quiz.remove(choice)-line is calling an operation that expects exact string matching in your case.
That means whenever choice is not an actual element in the list, this fails. You could catch the error in pythonic fashion via
try:
quiz.remove(choice)
except ValueError:
# do whatever
or make sure to check if the var is present in the list via adding it to the if-clause:
if choice in quiz:
#...
As said by Guy in the answers thread, I have to use del quiz[index], where index is entered by the user, to remove a question.
However you must take away 1 from "index" otherwise the wrong question will be removed or it will return a "out of range error"
I am not getting it right and I can't find how to do it.
Get the user input and create a thematic list of strings. The program should ask for a specific input theme.
The user should enter strings for the list until a condition is met such as entering a specific word or character.
There should not be hard coded list size.?
Each user input should be one list element.
MyList = []
for _ in range(5):
planets = str(input("Enter 5 planets: "))
if planets == str(planets):
if planets not in MyList:
MyList.append(planets)
else:
print("Input not valid")
print("That's your planets: ")
print(str(MyList))
I don't quite understand. To validate if something is a string should be isinstance(something, str). But input always returns a string. There is no need to do extra validation.
By the way, if you only want to eliminate duplicated items, I suggest using a set instead of a list. Call str() for print() is also redundant because print() will do the conversion itself. So:
print("Enter 5 planets: ")
result = {input(f"{i}) ") for i in range(1, 6)}
print("That's your planets:", ", ".join(result))
MyList = []
for _ in range(5):
planets = input("Enter 5 planets: ")
if type(planets) == str:
if planets not in MyList:
MyList.append(planets)
else:
print("Input not valid")
print("That's your planets: ")
print(",".join(MyList))
Actually any variable defined with the input() function will always be a str data type, because even if it's a number, it would still be the string representation of that number. Even if the user did not input any values at all, it would still be an empty string "".
I'm not sure what kind of verification you are trying to do exactly on that input but if you want to verify that it's not a number you can use theisdigit() string method.
Here is a simple example:
planets = []
while True:
planet = input("Insert the name of a planet: ")
if planet == 'quit':
break
if not planet.isdigit() and not planet in planets:
planets.append(planet)
print("Here is your list of planets:")
for planet in planets:
print(planet)
This block of code continually prompts the user to enter a planet name until the keyword quit is entered. If the input is not a number and is not already in the planets list, it is added. Finally, the complete list of planets is shown.
It must be said that on a conceptual level this implementation does not make much sense. It would be more logical to have a list of all known planets and check if the entered input matches any of the entries in the list. In that case, checking if the string represents a number becomes rather pointless.
Books = {"1":"Percy Jackson", "2":"Harry Potter","3":"Eragon","4":"Science for Dummies", "5":
"Encyclopedia of Knowledge"}
for choice in Books:
choices = []
choices2 = []
picking = input("Please take a book.Please pick the book number: ")
picking = int(picking)
question = input("Do you want to continue: ")
if 6 > picking:
picking = str(picking)
print(Books[picking])
choices.append(Books[picking])
choices2.append(choices[:])
else:
print("Error")
if question == "yes":
continue
else:
print("Checkout")
print(choices)
print(choices2)
break
I am new so the formatting might be off. The whole point of this was to make a "Library" and have 5 types of books. I then have to make the code add a thing at the bottom that says, what books the person got. The problem is that the .append keeps destroying the one before it in the for loop. Can anybody help me fix this?
Move the
choices = []
choices2= []
outside the for loop or it will keep making new empty lists.
I am trying to create a program on python to do with manipulating lists/arrays. I am having trouble with an error:
lowercase = names.lower
AttributeError: 'list' object has no attribute 'lower'
I really need some help to fix this!
names = [] #Declares an array
print("Type menu(), to begin")
def menu():
print("----------------------------MENU-----------------------------")
print("Type: main() for core functions")
print("Type: delete() to delete a name")
print("Type: save() to save the code")
print("Type: load() to load the saved array")
print("Type: lower() to make all items in the list lower case")
print("-------------------------------------------------------------")
def main():
times = int(input("How many names do you want in the array? ")) #Asks the user how many names they want in the array
for i in range(times):
names.append(input("Enter a name ")) #Creates a for loop that runs for the amount of times the user requested, it asks the user to enter the names
choice = input("Would you like the array printed backwards? ") #asks the user whether they want the array backwards
if choice == "Yes":
names.reverse() #If the user says yes, the array is reversed then printed backwards
print(names)
else:
print(names) #Otherwise, the array is printed normally
number = int(input("Which item would you like to print out? "))
number = number - 1
print(names[number])
start = int(input("What is the first position of the range of items to print out? "))
start = start - 1
end = int(input("What is the last position of the range of items to print out? "))
print(names[start:end])
def delete():
takeAway = input("Which name would you like to remove? ")
names.remove(takeAway)
print(names)
def save():
saving1 = open("Save.txt", 'w')
ifsave = input("Would you like to save the array? ")
if ifsave == "Yes":
for name in names:
saving1.write("%s\n" % name)
saving1.close
else:
menu()
def load():
loadquestion = input("Would you like to load a list of names? ")
if loadquestion == "Yes":
saving1 = open('Save.txt', 'r')
print(saving1.read())
saving1.close()
else:
menu()
def lower():
lowerq = input("Would you like to make the array lowercase? ")
if lowerq == "Yes":
lowercase = names.lower
print(lowercase)
else:
menu()
The variable names is a list. You can't use the .lower() method on a list.
pp_ provided the solution:
lowercase = [x.lower() for x in names]
While not exactly equivalent to the previous example, this may read better to you and has, effectively, the same result:
lowercase=[]
for name in names:
lowercase.append(name.lower())
Alternate solution that may fit your needs:
print (str(names).lower())
Like the error message says, you can't use .lower() on lists, only on strings. That means you'll have to iterate over the list and use .lower() on every list item:
lowercase = [x.lower() for x in names]
I'm trying to delete a tuple from my list, I've tried everything people have said but still no luck. I tried two methods, one time it removes the record even if it's not the name I want to remove, and the second doesn't remove at all.
record=[]
newrecord=[]
full_time=""
choice = ""
while (choice != "x"):
print()
print("a. Add a new employee")
print("b. Display all employees")
print("c. Search for an employee record")
print("d. Delete an employee record")
elif choice == "d":
delete = str(input("Enter the name of the employee you would like to remove from the record: "))
for d in record:
if d == delete:
record.remove(delete)
This doesn't remove anything.
If I change it to:
elif choice == "d":
delete = str(input("Enter the name of the employee you would like to remove from the record: "))
record = [n for n in record if delete in record]
It removes all if I do it this way.
Heres how i add to the list
choice = input("Choose an option (a to f) or x to Exit: ")
if choice == "a":
full_name = str(input("Enter your name: ")).title()
job_title = str(input("Enter your job title: ")).title()
while full_time.capitalize() != "Y" or full_time.capitalize() != "N":
full_time=input("Do you work full time (Y/N): ").upper()
if full_time.capitalize() == "Y":
break
elif full_time.capitalize() == "N":
break
break
hourly_rate = float(input("Enter your hourly rate: £"))
number_years = int(input("Enter the number of full years service: "))
record.append((full_name, job_title, full_time, "%.2f" % hourly_rate, number_years))
Given that the name is the first element in the record any checks against the name must be done against the first element of the tuple.
Previously you had:
record = [n for n in record if delete in record]
The first problem here is that you have to check against n and not record in your condition:
record = [n for n in record if delete in n]
The next issue is that this will only add a record to the list if delete is found within it.
It seems as though you want the inverse of this:
record = [n for n in record if delete not in n]
^^^
Now that in itself will not work because delete is a string and n is a tuple here, so we must combine this with the first fix. We then get:
record = [n for n in record if delete not in n[0]]
One thing I would note however is that if you are only using employee names as indexes it's probably much cleaner/easier to just use a dictionary with the employee name as keys and the other information as values. Given that a dictionary is an associative mapping between keys and values and your problem is exactly that I'd recommend changing your data structures.