I wrote a program that receives from the user one string representing a shopping list. The program asks the user to enter a number between 1 and 9. Depending on the number received, do one of the following:
And after making a user selection, the user returns to the main menu until they select number 9 to exit.
The syntax is correct but the program does not print what is needed. How to fix it?
def shopping_list(my_str):
my_list = my_str.split(",")
i = input("Please choose a number between 1 and 9: ")
while i in range(1, 10):
if i == 1:
print("My shopping list:", my_list)
continue
elif i == 2:
print("The number of items in my shopping list:", len(my_list))
continue
elif i == 3:
product = input("Please enter a product name: ")
if product in my_list:
print("This product is in the shopping list.")
else:
print("This item is not in the shopping list.")
continue
elif i == 4:
product = input("Please enter a product name: ")
print("The item", product, "shows", my_list.count(product), "in the list")
continue
elif i == 5:
product = input("Please enter a product name: ")
new_list = my_list.remove(product)
print("The item", product, "remove from the list. The new list is", new_list)
continue
elif i == 6:
product = input("Please enter a product name: ")
my_list += product
print("The item", product, " add to the list. The new list is", my_list)
continue
elif i == 7:
new_list = []
for product in my_list:
if len(product) < 3 or not(product.isalpha()):
new_list += product
continue
elif i == 8:
print(list(set(my_list)))
continue
else:
break
shopping_list("Milk,Cottage,Tomatoes")
You never ask again the user, so the loop goes infite doing the first choice given by the user.
Also remove the continue statement, you don't need them as all code is in elif also it'll allow you to ask the user a new choice at the end of the loop.
convert the input to int, you won't be able to enter the loop without
def shopping_list(my_str):
my_list = my_str.split(",")
i = int(input("Please choose a number between 1 and 9: "))
while i in range(1, 10):
if i == 1:
print("My shopping list:", my_list)
elif i == 2:
print("The number of items in my shopping list:", len(my_list))
elif i == 3:
# ...
elif i == 8:
print(list(set(my_list)))
else:
break
i = int(input("Please choose a number between 1 and 9: "))
Final Full Code
Now corrections about
mode 5 : what is returned by remove is None, the modification is in-placed so do
elif i == 5:
product = input("Please enter a product name: ")
my_list.remove(product)
print("The item", product, "remove from the list. The new list is", my_list)
mode 6 the operator += does an extend on the list so it'll add all chars, do append instead
elif i == 6:
product = input("Please enter a product name: ")
my_list.append(product)
print("The item", product, " add to the list. The new list is", my_list)
mode 7 creating a new list that is a filter of the main one is useless if you forget it. Also I'd say you remove the items that are smaller than 3 or contains non-alpha, here you keep them. Finally use append
elif i == 7:
new_list = []
for product in my_list:
if len(product) >= 3 and product.isalpha():
new_list.append(product)
my_list = list(new_list)
or just use a list comprehension
elif i == 7:
my_list = [p for p in my_list if len(p) >= 3 and p.isalpha()]
I would do this: (Cut out some elifs due to too much code.)
while True:
i = int(input("Please choose a number between 1 and 9: "))
if i == 1:
print("My shopping list:", my_list)
continue
elif i == 8:
print(list(set(my_list)))
continue
elif i == 9:
break
else:
print("Invalid Number! Try again.")
Is this what you want? I'm not quite getting what you're asking for.
Related
The user can not only add items to the list but also pop items from the list. I seem to be stuck where the user pops items from the list but the output needs to only show the first and last letter of that item that has been popped. for example
["Oranges" , "Apples" , "Mangoes"]
["O-----s" , "Apples" , "Mangoes"]
The code below is what I have so far:
add_item = []
choice = 0
while(True):
choice = int(input('Welcome to your Shopping list! \n 1) Add Item \n 2) Check Off
Item \n 3) Print list \n 4) Exit \n Enter a Choice: '))
if choice == 1:
add = input('What will you add to the list? ')
add_item.append(add)
elif choice == 2:
remove = int(input('Which item will you check off? '))
item_2 = add_item.pop(remove)
elif choice == 3:
for i, item in enumerate(add_item, 1):
print(i,item.title())
elif choice == 4:
print('Goodbye!')
break
Create a function to find the new value for your popped list items.
def popItemFromList(item):
# find new value of item popped
dash_string = ""
if len(item) > 2:
for i in range(0, len(item)-2):
dash_string += "-"
new_value = item[0] + dash_string + item[len(item)-1]
return new_value
add_item = []
popped_list = []
choice = 0
while(True):
print(f'current_list: {add_item }')
print(f'popped_list: {popped_list}')
choice = int(input('Welcome to your Shopping list! \n 1) Add Item \n 2) Check Off Item \n 3) Print list \n 4) Exit \n Enter a Choice: '))
if choice == 1:
add = input('What will you add to the list? ')
add_item.append(add)
elif choice == 2:
remove = int(input('Which item will you check off? '))
item_2 = add_item.pop(remove)
popped_list.append(popItemFromList(item_2))
elif choice == 3:
for i, item in enumerate(add_item, 1):
print(i,item.title())
elif choice == 4:
print('Goodbye!')
break
if you choose to return a book at the start of the program, without checking out any books,
then it won't allow the return (intended). So say the user wants to check out 5/10 copies of
book1. It checks them out and subtracts them from the copies on shelf. They choose to return
3 one day, and 2 another day. (For testing purposes) the day after that, they return another
copy of book1, which is more than they checked out. It appends it to the book1.borrow aka
num of copies. It should not allow the user to return more copies than the original numbr of copies. So this is what I have in my main module. I can add the class LibraryBook if
needed.
from LibraryBook import *
book1 = LibraryBook()
book1.title = "not set"
book1.year = "no se"
book1.author = "set not"
book1.borrow = 10
book2 = LibraryBook()
book2.title = "tes ton"
book2.year = "es on"
book2.author = "ton tes"
book2.borrow = 8
selection = 0
amount = 0
amount1 = 0
while selection != 5:
print("Select an option")
print('1 - Borrow a book')
print('2 - Return a book')
print('3 - See info on available books')
print('4 - Exit')
print()
selection = int(input("What would you like to do? "))
print()
if selection == 1:
print("Book 1 is: ", book1.title)
print("Book 2 is: ", book2.title)
print()
bookNum = int(input("Enter the book number. "))
print()
if bookNum == 1:
print()
amount = int(input("Enter the number of copies you would like to check out. "))
print()
if (amount <= book1.borrow) and (amount > 0):
book1.borrowed(amount)
else:
print("We only have", book1.borrow, "copies available.")
print()
elif bookNum == 2:
print()
amount = int(input("Enter the number of copies you would like to check out. "))
print()
if (amount <= book2.borrow) and (amount > 0):
book2.borrowed(amount)
else:
print("We only have", book2.borrow, "copies available.")
print()
else:
print()
print("That book is not here. Enter 1 or 2. ")
print()
if selection == 2:
print("Book 1 is: ", book1.title)
print("Book 2 is: ", book2.title)
print()
bookNum = int(input("Which book would you like to return? "))
print()
if bookNum == 1:
print()
amount1 = int(input("Enter the amount of copies you would like to return. "))
print()
if amount1 <= amount:
book1.returned(amount1)
print()
elif book1.borrow == book1.borrow:
print("Invalid number of copies. Count the books and try again ")
print()
else:
print("You only checked out", amount)
print()
elif bookNum == 2:
print()
amount1 = int(input("Enter the amount of copies you would like to return. "))
print()
if amount1 <= amount:
book2.returned(amount1)
print()
elif book2.borrow == book2.borrow:
print("You did not check out this book.")
print()
else:
print("You only checked out", amount)
print()
else:
print("Invalid selection. Choose book 1 or book 2.")
print()
if selection == 3:
print()
print("Book 1:")
print(book1.__str__())
print()
print("Book 2:")
print(book2.__str__())
print()
if (selection <= 0) or (selection >= 5):
print("Invalid selection. Enter a number 1-4. ")
print()
if selection == 4:
break
I'm not the best programmer but I think I made and example here
Ofc is not the best I made it larger for you to understand, there are some bugs like when asked for book if u give bigger then 2 will break but I let you fix it ;D
import sys, os, time, re
class LibraryBook(object):
def __init__(self, title, year, author, borrow):
self.title = title
self.year = year
self.author = author
self.borrow = borrow
def borrow_add(self, amount: int):
self.borrow += amount
def left(self):
return self.borrow
def get_title(self):
return self.title
def borrow_sell(self, amount: int):
self.borrow -= amount
def get_book_info(self):
val = f'''
Book Title: {self.title}
Book Year: {self.year}
Book Author: {self.author}
Left in stock: {self.borrow}
'''
return val
book1 = LibraryBook('Prison Break', 2016, 'My House', 8)
book2 = LibraryBook('Hello', 1999, 'NO one', 10)
###########
#That is so you can do book3,4,5 etc.. without write in print all books on hand ;D
books = re.findall('book.', (str(globals().copy())).replace("'", ''))
books_titles = [eval(f'{o}.get_title()') for o in books]
##########
user_lib =[]
#You can use that in a function (def) and call it when you need it
while True:
os.system('cls')
option = int(input('''
Select an option
1 - Borrow a book
2 - Return a book
3 - See info on available books
4 - See my lib
5 - Exit
>>> '''))
if option == 1:
option_2 = input("\n".join(f"Book{o+1}:{i}" for o, i in enumerate(books_titles))+'\nWhat book(ex: 1):')
option_3 = int(input('How much?: '))
if int(eval(f'book{option_2}.left()'))-option_3 >= 0:
if x:=list(filter(lambda book: book['name'] == eval(f'book{option_2}.title'), user_lib)):
user_lib[user_lib.index(x[0])]['amount'] +=option_3
else:
user_lib.append({'name': eval(f'book{option_2}.get_title()'), 'amount': option_3})
print(f'You borrowed {option_3} books')
eval(f'book{option_2}.borrow_sell({option_3})') #Remove from store
else:
print(f'We have {eval(f"book{option_2}.left()")} books left...')
time.sleep(1) # wait 1 second for user to read then reset
elif option == 2:
option_2 = input("\n".join(f"Book{o+1}:{i}" for o, i in enumerate(books_titles))+'\nWhat book(ex: 1):')
if len(x:=list(filter(lambda book: book['name'] == eval(f'book{option_2}.get_title()'), user_lib))) > 0:
option_3 = int(input('How much?: '))
if user_lib[pos:=user_lib.index(x[0])]['amount'] -option_3 >= 0:
user_lib[pos]['amount'] -= option_3
if user_lib[pos]['amount'] == 0:
user_lib.pop(pos)
print(f'You returned {option_3} books')
eval(f'book{option_2}.borrow_add({option_3})') # Add them back to shop
else:
print(f"You don't have enogh books, you have only: {x[0]['amount']}")
time.sleep(1) # wait 1 second for user to read then reset
else:
print("You don't any books of thta kind")
time.sleep(1)
elif option == 3:
option_2 = input("\n".join(f"Book{o+1}:{i}" for o, i in enumerate(books_titles))+'\nWhat book(ex: 1):')
print(eval(f'book{option_2}.get_book_info()'))
input('Press enter to continue...')
elif option == 4:
print("\n".join(f"Book Name:{user_lib[o]['name']}\nAmount I have:{user_lib[o]['amount']}" for o, i in enumerate(user_lib)) if user_lib != [] else "You don't have any books")
elif option == 5:
sys.exit(1)
else:
print('Invalid number')
time.sleep(1) # wait 1 second for user to read then reset
In this program I am trying to make an inventory program. Under option (3) titled "Update Inventory" you type in an item for the list name, then you are prompted to either add to the existing quantity in the list qty or subtract from it.
For example if I have five items in name and the corresponding quantity in qty. How do I find item 3, and update the quantity by adding to or subtracting from the current amount.
Full program code (only looking for help on how to write option 3):
name = []
qty = []
class Foo():
def __init__(self, name, qty):
self.name = name
self.qty = qty
def menuDisplay():
print ('=============================')
print ('= Inventory Management Menu =')
print ('=============================')
print ('(1) Add New Item to Inventory')
print ('(2) Remove Item from Inventory')
print ('(3) Update Inventory')
print ('(4) Search Item in Inventory')
print ('(5) Print Inventory Report')
print ('(99) Quit')
CHOICE = int(input("Enter choice: "))
menuSelection(CHOICE)
def menuSelection(CHOICE):
if CHOICE == 1:
print('Adding Inventory')
print('================')
new_name = input('Enter the name of the item: ')
name.append(new_name)
new_qty = int(input("Enter the quantity of the item: "))
qty.append(new_qty)
CHOICE = int(input('Enter 98 to continue or 99 to exit: '))
if CHOICE == 98:
menuDisplay()
elif CHOICE == 99:
exit()
elif CHOICE == 2:
print('Removing Inventory')
print('==================')
removing = input('Enter the item name to remove from inventory: ')
indexdel = name.index(removing)
name.pop(indexdel)
qty.pop(indexdel)
CHOICE = int(input('Enter 98 to continue or 99 to exit: '))
if CHOICE == 98:
menuDisplay()
elif CHOICE == 99:
exit()
elif CHOICE == 3:
print('Updating Inventory')
print('==================')
item = input('Enter the item to update: ')
update = int(input("Enter the updated quantity. Enter 5 for additional or -5 for less: "))
if update >= 0:
print()
elif update <= -1:
print()
CHOICE = int(input('Enter 98 to continue or 99 to exit: '))
if CHOICE == 98:
menuDisplay()
elif CHOICE == 99:
exit()
I have shortened the code as I believe this is the minimum code as possible to duplicate my issue.
I would not suggest using multiple lists to store related items. A dictionary is probably your best bet, especially when working with an inventory system - in an inventory, every item has a unique attribute. Dictionaries store key/value pairs, which is perfect for something like this. Using two lists can be detrimental; one small bug could derail the entire system. Something like this will illustrate the simplicity of using a dictionary over multiple lists:
inventory = {'apples':0, 'bananas':0, 'oranges':0}
item = input("Enter the item to update: ")
qty = int(input("Enter the updated quantity. Enter 5 for additional or -5 for less: "))
inventory[item] += qty
However, if you are set on using two lists, this will serve your purpose:
name = ['apples', 'bananas', 'oranges']
qty = [0,0,0]
item = input("Enter the item to update: ")
update = int(input("Enter the updated quantity. Enter 5 for additional or -5 for less: "))
qty[name.index(item)] += update
Assuming your lists are associated 100% with each other, the above will use the index position of the item and update that quantity in the other list.
I was doing some homework and I'm kinda stumped. part of my assignment is that I need to have a If statement that checks if a number that was entered is 16 characters long or not, this is the code I have so far:
#the input
CreditCardNum = input("Input a credit card number(no spaces/hyphens): ")
#The if statements
if str(CreditCardNum) != len(16):
print("This is not a valid number, make sure the number is 16 characters.")
elif str(CreditCardNum) == len(16):
if str(CreditCardNum[0:]) == 4:
print("The Card is a Visa")
elif str(CreditCardNum[0:]) == 5:
print("The Card is a Master Card")
elif str(CreditCardNum[0:]) == 6:
print("The Card is a Discover Card.")
else:
print("The brand could not be determined.")
This is the logic I believe you are looking for.
If card length is 16, it checks for the first character to determine which type.
CreditCardNum = input("Input a credit card number(no spaces/hyphens): ")
n = len(CreditCardNum)
if n != 16:
print("This is not a valid number, make sure the number is 16 characters.")
else:
x = CreditCardNum[0]
if x == '4':
print("The Card is a Visa")
elif x == '5':
print("The Card is a Master Card")
elif x == '6':
print("The Card is a Discover Card.")
else:
print("The brand could not be determined.")
Explanation
Use n = len(CreditCardNum) to store in variable n the number of characters in the input string. Likewise first character of the input.
len(16) makes no logical sense. You want to compare n, which is an integer, to another integer.
To extract first letter of a string, simply do mystr[0].
Python don't have switch function so you can either use if elif or dictionary.
Your case definately a dictionary type.
card_dict = {
'4': "Visa",
'5': "Master card",
'6': "Discover card"
}
CreditCardNum = input("Input a credit card number(no
spaces /hyphens): ")
n = len(CreditCardNum)
x = CreditCardNum[0]
if n != 16:
print("This is not a valid number, make sure the number is 16 characters.")
elif x in card_dict:
print("The Card is a {}".format(card_dict[x]))
else:
print("The brand could not be determined")
You can maybe try something like this:
#the input
CreditCardNum = input("Input a credit card number(no spaces/hyphens): ")
#The if statements
if len(str(CreditCardNum)) != 16:
print("This is not a valid number, make sure the number is 16 characters.")
elif len(str(CreditCardNum)) == 16:
if str(CreditCardNum[0]) == '4':
print("The Card is a Visa")
elif str(CreditCardNum[0]) == '5':
print("The Card is a Master Card")
elif str(CreditCardNum[0]) == '6':
print("The Card is a Discover Card.")
else:
print("The brand could not be determined.")
I am not sure what you try to do in conditional statements within the outer elif but I am assuming you are trying to get the first character of your CreditCardNum?
I am trying to append values from an input to sublists in a list.
Each number of Student and name should be in a sublist.
ex:
[[123,John],[124,Andrew]]
Where the outside list would be the number of students, and the sublists , the info of the students..
Here is what my code looks like:
listStudents = [[] for _ in range(3)]
infoStudent = [[]]
while True:
choice = int(input("1- Register Student 0- Exit"))
cont = 0
if choice == 1:
snumber = str(input("Student number: "))
infoStudent[cont].append(str(snumber))
name = str(input("Name : "))
infoStudent[cont].append(str(name))
cont+=1
listStudents.append(infoStudent)
if choice == 0:
print("END")
break
print(listStudents)
print(infoStudent)
If I put on the first loop, snumber = 123 , name = john , and snumber = 124, name = andrew on the second time it will show me : [[123,john,124,andrew]] instead of [[123,john], [124,andrew]].
Your code can be greatly simplified:
You don't need to pre-allocate the lists and sublists. Just have one list, and append the sublists as you receive inputs.
You don't need to cast user input from input to strings, as they are strings already.
Here's the modified code:
listStudents = []
while True:
choice = int(input('1- Register Student 0- Exit'))
if choice == 1:
snumber = input('Student number: ')
name = input('Name : ')
listStudents.append([snumber, name])
if choice == 0:
print('END')
break
print(listStudents)
Your code can be more pythonic and can make use of some basic error handling as well. Create the inner list inside the while loop and simply append to the outer student list. This should work.
students = []
while True:
try:
choice = int(input("1- Register Student 0- Exit"))
except ValueError:
print("Invalid Option Entered")
continue
if choice not in (1, 9):
print("Invalid Option Entered")
continue
if choice == 1:
snumber = str(input("Student number: "))
name = str(input("Name : "))
students.append([snumber, name])
elif choice == 0:
print("END")
break
print(students)