I'm pulling in a text file as a multidimensional array and giving the user a choice to pick one of the items and it is stored in another array. I'm trying to figure out how to find the index of the first array with the elements in the second.
Code:
with open("books.txt") as b:
books = b.readlines()[7:]
books = [x.strip() for x in books]
books = [x.split(",") for x in books]
def welcome():
print("Welcome to the Bookstore")
global name
name = input("What is your name? ")
print("Our current list of books are: ")
inventory()
def choice():
select = input("Which books would you like? (ID):\n")
global chosen
chosen = []
flag = "y"
while flag == "y":
chosen.append(select)
flag = input("Would you like to add more books to your cart? (y/n): ")
print(chosen)
for chosen in books:
books.index(chosen[0])
def inventory():
length = len(books)
for i in range(length):
print(books[i][0], books[i][1].strip(), ("$" + books[i][2]).replace(" ", ""))
choice()
def receipt():
print("Thank you", name)
welcome()
Text File:
To add books to your store please have a new book on each line,
and use the format ItemNumber,BookName,BookPrice an example would be as follows:
B142, Prelude to Programing, 5.25
Please start entering books under the heading Books Available.
Thank You
Books Available:
B12, Prelude to Programing, 5.25
B13, Lazy Python, 10.25
B14, Coding for Dummys, 19.25
I have tried
for chosen in books:
books.index(chosen[0])
If i select B12, I want the result to be 0 0 for the index numbers.
Issues:
You are overwriting chosen in the line for chosen in books:.
Loop prompting for more books just appends last selected book id when y is entered for more.
The word select colors in my editor as a module select exists. You may want to change the name.
Replace choice() with this change.
def choice():
global chosen
chosen = []
while True:
select = input("Which books would you like? (ID):\n")
chosen.append(select)
flag = input("Would you like to add more books to your cart? (y/n): ")
if flag != 'y':
break
print(chosen)
index = []
for item in chosen:
for idx, book in enumerate(books):
if item == book[0]:
index.append([idx, 0])
print('index:', index)
The index list contains i.e. [[2, 0], ...]
The 2 being the index to find the book in books.
The 0 being the index of the book id.
If the result not exactly what you want, you can make the any changes needed.
Storing the book ID means searching later. You could store the index of the book instead.
i.e.
def choice():
global chosen
chosen = []
while True:
select = input("Which books would you like? (ID):\n")
# Get the index of the selected book in books.
for idx, book in enumerate(books):
if select == book[0]:
chosen.append(idx)
break
flag = input("Would you like to add more books to your cart? (y/n): ")
if flag != 'y':
break
print(chosen)
# [[0, 0], ...]
result = [[idx, 0] for idx in chosen]
print(result)
This function is storing the index of the book chosen rather than the ID of the book ID as it is more convenient to use the index later as the use of list comprehension shows at the end.
Related
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.
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.
The question I need help with is:
Write a program that stores the names of ten countries in column1 and their capitals in column2. The program should then pick a random country and ask the user for the capital.
Display an appropriate message to the user to show whether they are right or wrong.
So far I have
column1 = []
column2 = []
listoflist = [(column1)(column2)]
maxlength = 10
while len (column1) < maxlength:
country = input("please enter a country: ")
capital = input("please enter the capital of the country entered: ")
column1.append(country)
column2.append(capital)
for item in done:
print (item[0],item[1])
if anyone can help please.
I believe your list of list setup is a little off for what you intend. Try something like this:
from random import shuffle
data = []
maxlength = 10
while len (data) < maxlength:
country = input("please enter a country: ")
capital = input("please enter the capital of the country entered: ")
# for this scenario, probably better to keep rows together instead of columns.
data.append((country, capital)) # using a tuple here. It's like an array, but immutable.
# this will make them come out in a random order!
shuffle(data)
for i in range(maxlength):
country = data[i][0]
capital = data[i][1]
print("Capital for the country {0}?".format(country))
user_said_capital_was = input("What do you think?")
if user_said_capital_was == capital:
print("Correct!")
else:
print("Incorrect!")
You should write this as:
listoflist = [column1, column2]
In your code you're not correctly defining the list of lists and that leads to an error.
import random
dict1 ={"Turkey":"Istanbul","Canada":"Ottawa","China":"Beijing"}
list1=[key for key in dict1.keys()]
try:
q=random.choice(list1)
except:
print ("We are out of countries, sorry!")
while True:
user=input("What is the capital city of {} ?: ".format(q))
if user == dict1[q]:
print ("Correct")
list1.remove(q) #removing first choice so same country never asking again
try:
q=random.choice(list1)
except:
print ("We are out of countries,sorry!")
break
else:
print ("Not correct")
Using dict and key-value system and list comprehension.
A list of lists can work, but a dictionary with key, value pairs works great for this.
In keeping with your original theme of user input, the logic works out well and you can use the random.choice function to pick your country while keeping track.
import random
data = {}
maxlength = 10
for _ in range(maxlength):
country = input("please enter a country: ")
capital = input("please enter the capital of the country entered: ")
# using a dict, keeps things simple
data[country] = capital
countries = list(data.keys())
picked = []
while len(picked) < maxlength:
country = random.choice(countries)
if country in picked:
continue
print("Capital for the country {0}?".format(country))
user_said_capital_was = input("What do you think? ")
if user_said_capital_was == data[country]:
print("Correct!")
picked.append(country)
else:
print("Incorrect!")