Append Values from input to a sublist in Python - python

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)

Related

Stuck at WHILE LOOP when pressing N for escaping from the loop

# Feature to ask the user to type numbers and store them in lists
def asking_numbers_from_users():
active = True
while active:
user_list = []
message = input("\nPlease put number in the list: ")
try:
num = int(message)
user_list.append(message)
except ValueError:
print("Only number is accepted")
continue
# Asking the user if they wish to add more
message_1 = input("Do you want to add more? Y/N: ")
if message_1 == "Y" or "y":
continue
elif message_1 == "N" or "n":
# Length of list must be more or equal to 3
if len(user_list) < 3:
print("Insufficint numbers")
continue
# Escaping WHILE loop when the length of the list is more than 3
else:
active = False
else:
print("Unrecognised character")
print("Merging all the numbers into a list........./n")
print(user_list)
def swap_two_elements(user_list, loc1, loc2):
loc1 = input("Select the first element you want to move: ")
loc1 -= 1
loc2 = input("Select the location you want to fit in: ")
loc2 -= 1
loc1, loc2 = loc2, loc1
return user_list
# Releasing the features of the program
asking_numbers_from_users()
swap_two_elements
I would break this up into more manageable chunks. Each type of user input can be placed in its own method where retries on invalid text can be assessed.
Let's start with the yes-or-no input.
def ask_yes_no(prompt):
while True:
message = input(prompt)
if message in ("Y", "y"):
return True
if message in ("N", "n"):
return False
print("Invalid input, try again")
Note: In your original code you had if message_1 == "Y" or "y". This does not do what you think it does. See here.
Now lets do one for getting a number:
def ask_number(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("Invalid input, try again")
Now we can use these method to create you logic in a much more simplified way
def asking_numbers_from_users():
user_list = []
while True:
number = ask_number("\nPlease put number in the list: ")
user_list.append(number)
if len(user_list) >= 3:
if not ask_yes_no("Do you want to add more? Y/N: ")
break
print("Merging all the numbers into a list........./n")
print(user_list)

How to find the quantity of an item that is in a different list and alter it?

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.

How to stop the list, missing number from user enter

I'm doing this exercise:
In your main function, you need to keep asking user to enter an
integer, then store those integers in a list. Once the user decides to
stop entering, the function should print out all the integers from the
list, and also find the largest number in that list. If the user did
not enter any number, you should print out “Your list is empty”.
I tried to code it but I got stuck on print "Your list is empty". I don't know where to put the statement.
And when the user enters the number, the list will come out missing the first number the user entered.
def main():
user_list = []
user_num = input('Enter an integer or enter x to stop: ')
while user_num != 'x':
user_num = input('Enter an integer or enter x to stop: ')
if user_num != 'x' :
user_list.append(user_num)
if user_list == []:
print('Your List is empty')
exit()
index = 0
while index < len(user_list):
user_list[index] = int(user_list[index])
index += 1
print ('Here is the list of the numberyou entered:')
print (*user_list, sep = '\n')
largest = max(user_list)
print ('The largest number in your listis: ',largest)
main()
Simple, change:
while user_num != 'x':
user_num = input('Enter an integer or enter x to stop: ')
if user_num != 'x' :
user_list.append(user_num)
if user_list == []:
print('Your List is empty')
exit()
To:
while True:
user_num = input('Enter an integer or enter x to stop: ')
if user_num != 'x' and user_num:
user_list.append(user_num)
elif not user_list:
print('Your List is empty')
exit()
else:
break
Here is the optimized code:
def main():
user_list = []
while True:
user_num = input('Enter an integer or enter x to stop: ')
if user_num != 'x' and user_num:
user_list.append(int(user_num))
elif not user_list:
print('Your List is empty')
exit()
else:
break
print ('Here is the list of the numbers you entered:')
print (*user_list, sep = '\n')
largest = max(user_list)
print ('The largest number in your list is: ', largest)
main()
if user_list == []:
print('Your List is empty')
exit()
You should write this portion outside the while loop. Like this
def main():
user_list = []
user_num = input('Enter an integer or enter x to stop: ')
while user_num != 'x':
user_num = input('Enter an integer or enter x to stop: ')
if user_num != 'x' :
user_list.append(user_num)
if user_list == []:
print('Your List is empty')
def main():
user_list = []
while True:
user_num = input('Enter an integer or enter x to stop: ')
if user_num == 'x':
break # exit the "while" loop
user_list.append(user_num)
# this is after the loop:
if user_list == []:
print('Your List is empty')
exit()
# user_list = list(map(int, user_list))
for index in range(len(user_list)): # range is a list-like thing of 0, 1, 2, 3... up to the length of the list
user_list[index] = int(user_list[index])
print ('Here is the list of numbers you entered:')
print (*user_list, sep='\n')
largest = max(user_list)
print ('The largest number in your lists: ', largest)
main()

While loop with multiple IF conditions

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.

How would I stop the loop when after its added the names to the list and other errors

How would I stop my code looping after it has added the amount of names the user has inputted instead of doing this:
Add Name
Show list
Quit
Enter your choice : 1
How many names would you like to enter: 2 # How would I set a max of 10 names here?
Enter name: Bob
Enter name: Jim
How many names would you like to enter: # How would I stop this line from repeating?
Actual code:
names = []
def displayMenu():
print(" 1. Add Name")
print(" 2. Show list")
print(" 3. Quit")
choice = int(input("Enter your choice : "))
while choice >5 or choice <1:
choice = input("Invalid. Re-enter your choice: ")
return choice
def addname():
while True:
number=int(input('How many names would you like to enter: '))
name = [input('Enter name:') for _ in range(number)]
names.append(name)
def displayData():
#name.split(",") how would i correctly user split here
print(names)
option = displayMenu()
while option != 3:
if option == 1:
addname()
elif option == 2:
displayData()
option = displayMenu()
print("Program terminating")
Okay, first off, since you only have three menu options, this line:
while choice >5 or choice <1:
Should look like this:
while 3 < choice < 1:
So your displayMenu function looks like this:
names = []
def displayMenu():
print(" 1. Add Name")
print(" 2. Show list")
print(" 3. Quit")
choice = int(input("Enter your choice : "))
while 3 < choice < 1: # Only accept choices in between 3 and 1
choice = input("Invalid. Re-enter your choice: ")
return choice
You also said that your addname function was looping forever, this is because you have an infinite while loop.
What you need, as #ettanany said, is a for loop:
In your case, for loop would work also:
def addname():
number = int(input('How many names would you like to enter: '))
for i in range(number):
name = input('Enter name: ')
names.append(name)
What this does is ask the user how many names he wants to enter, and then runs the code inside the loop for that amount of times -- so if the user enters the number 9, it will ask for 9 names.
You also said that there should be a maximum of 10 names. We can use a while loop like you did in the displayMenu function to make sure the user enters a number that is 10 or below:
def addname():
number = int(input('How many names would you like to enter: '))
while number > 10: # Don't allow any numbers under 10
number = int(input('Please enter a number under 10: '))
for i in range(number):
name = input('Enter name: ')
names.append(name)
Finally, in your displayData function, you want to 'split' the names and print them out.
Just doing print(names) would give us a result like this:
[ 'Spam', 'Eggs', 'Waheed' ]
If we want it to look nice, we need to use a for loop.
for name in names:
print( name ) # You can change this line to print( name, end=' ' )
# If you want all the names on one line.
This will yield a result like this:
Spam
Eggs
Waheed
Which looks much better than just printing out the list.
Complete (fixed) code:
names = []
def displayMenu():
print(" 1. Add Name")
print(" 2. Show list")
print(" 3. Quit")
choice = int(input("Enter your choice : "))
while 3 < choice < 1: # Only accept choices in between 3 and 1
choice = input("Invalid. Re-enter your choice: ")
return choice
def addname():
number = int(input('How many names would you like to enter: '))
while number > 10: # Don't allow any numbers under 10
number = int(input('Please enter a number under 10: '))
for i in range(number):
name = input('Enter name: ')
names.append(name)
def displayData():
for name in names:
print( name ) # You can change this line to print( name, end=' ' )
# If you want all the names on one line.
option = displayMenu()
while option != 3:
if option == 1:
addname()
elif option == 2:
displayData()
option = displayMenu()
print("Program terminating")
Instead of while True, you need to use while i < number, so your addname() function should be as follows:
def addname():
i = 0
number = int(input('How many names would you like to enter: '))
while i < number:
name = input('Enter name: ') # We ask user to enter names one by one
names.append(name)
i += 1
In your case, for loop would work also:
def addname():
number = int(input('How many names would you like to enter: '))
for i in range(number):
name = input('Enter name: ')
names.append(name)

Categories