Line breaks with lists - python

I have a working script but it does not work the way I want it to:
print('Add as many items to the basket as you want. When you are done, enter "nothing".')
print('What do you want to put into the basket now?')
basket = []
while True:
myInput = input()
if myInput == "nothing":
print('There are ' + str(len(basket)) + ' items in the basket: '+ str(basket))
break
else:
basket.append(myInput)
print('Okay, what else?')
The final line is supposed to look like this:
There are 3 items in the basket:
Item 1: a sandwich
Item 2: two cans of Dr Pepper
Item 3: some napkins
Any suggestions?

Use enumerate with a start index of 1 and str.format:
while True:
myInput = input()
if myInput == "nothing":
print('There are {} items in the basket: '.format(len(basket)))
for ind, item in enumerate(basket,1):
print("Item{}: {} ".format(ind,item))
break
else:
basket.append(myInput)
print('Okay, what else?')
You can also use a list comprehension and iter without needing a while loop, it will keep looping until the user enters the sentinel value "nothing":
print('Add as many items to the basket as you want. When you are done, enter "nothing".')
print('What do you want to put into the basket now?')
basket = [ line for line in iter(lambda:input("Please enter an item to add"), "nothing")]
print('There are {} items in the basket: '.format(len(basket)))
for ind,item in enumerate(basket,1):
print("Item{}: {} ".format(ind,item))

I think its better to separate collecting input and printing the results as follows:
print('Add as many items to the basket as you want. When you are done, enter "nothing".')
print('What do you want to put into the basket now?')
basket = []
while True:
myInput = input()
if myInput == "nothing":
break
else:
basket.append(myInput)
print('Okay, what else?')
print('There are ' + str(len(basket)) + ' items in the basket: ')
for i,item in enumerate(basket):
print("Item {}: {}".format(i+1, item))

An empty string (just a carriage return) will still be considered an item, even though nothing will be there, which will cause an incorrect # of items in your basket and an empty Item line to be printed. Consider catching that and ignoring it, or potentially making it equivalent to "nothing" in the second if statement as part of the break condition.
print('Add as many items to the basket as you want. When you are done, enter "nothing".')
print('What do you want to put into the basket now?')
basket = []
while True:
myInput = input()
if myInput == "":
continue
if myInput == "nothing":
print('There are ' + str(len(basket)) + ' items in the basket:')
for itemno, item in enumerate(basket):
print("Item {0}: {1}".format(itemno+1,item))
break
else:
basket.append(myInput)
print('Okay, what else?')

Related

ValueError: could not convert string to float: '40.0,'

I'm trying to convert string in list into float without using join() map() enumerate() replace() these built-in function as assignment requirement. What else can I use to remove comma after the number?
Create an ordering system for customer to buy something that uploaded by admin.
This is the whole purchasing function that i do:
def place_order():
try:
fileHandler= open('groceries_list.txt','r')
except:
print('File cannot be opened.')
exit()
gro=fileHandler.readlines()
if len(gro) == 0:
print("Sorry! There are no groceries in our store yet.")
else:
repeat = True
while repeat == True:
try:
fo= open('groceries_list.txt')
fr= fo.readlines()
except:
print('File cannot be read.')
order_list=[]
total=0
onp=[]
view_gro()
product= input('Please enter groceries name you want to purchase: ').upper()
for line in fr:
line=line.rstrip()
if not product in line:
continue
print(line)
line=line.split()
print('The price for',product,'is RM',(line[3]))
######################need to convert line[3] in list to float
line[3]=float(line[3])
total=total+line[3]
order_list.append(product)
print('Product successful added to you shopping cart!')
again= input('Do you need anything else? YES for continue or NO for quit.').upper()
if again == 'YES':
continue
elif again == 'NO':
print("Here's your shopping cart item")
print(order_list)
print('Total amount for your purchasing is RM',total)
try:
while True:
pay=int(input('You pay: RM '))
balance= total-pay
if balance == 0:
print('Pay successfully! Thanks for your purchasing')
fw= open('order_list_c.txt','w')
fw.write(order_list)
fw.write('\n')
fw.close()
repeat=False
#break
else:
print('Pay unsuccessfully! Please try again.')
continue
except ValueError:
print('Please enter numeric proper amount.')
continue
else:
print('Please enter YES or NO')
print('==============================')
continue
# else:
# print('Product not in list.')
# continue
#else:
# print('No products found. Try again.')
# continue
fo.close()
fileHandler.close()
This is the part Im talking about.
for line in fr:
line=line.rstrip()
if not product in line:
continue
print(line)
line=line.split()
print('The price for',product,'is RM',(line[3]))
######## need to convert line[3] in list to float but contains comma ######
line[3]=float(line[3])
total=total+line[3]
This is error showed
line[3]=float(line[3])
ValueError: could not convert
string to float: '40.0,'
This is the list:
['FOOD', 'vege', 2022, 40.0, 'fresh']
Assuming you get from the file, a str: "['FOOD', 'vege', 2022, 40.0, 'fresh']"
then when you line=line.split() it will split on the spaces, so your array of strings will look like:
[ "['FOOD',", "'vege',", "2022,", "40.0,", "'fresh']"]
and then float() chokes on the unexpected ,.
Try to split(", "), but keep in mind, your 0th (first) and -1th (last) elements will have an extra [ or ] in their strings.
Use ast.literal_eval() to parse the line, rather than using split() and float().
import ast
for line in fr:
line_list = ast.literal_eval(line)
if product not in line_list:
continue
price = line_list[3]
print('The price for',product,'is RM',price)

NameError: Variable name is not defined

I am having trouble with some undefined variables in my code for a school assignment using nested loops and functions. Also, if you happen to spot any other errors please lmk.
Code:
shopping_lists = [
['toothpaste', 'q-tips', 'milk'],
['milk', 'candy', 'apples'],
['planner', 'pencils', 'q-tips']
]
customer_input = ''
#prints shopping lists
print(shopping_lists)
print ('')
print("Press '1' to update an item, '2' to view an item, or '3' to view a list")
customer_input = input("What do you want to do? ")
if customer_input == '1':
def update_list(List, Item, newItem):
list = int(input('What list would you like to update? Answer using 1, 2, or 3. ')-1)
print (shopping_lists[list])
itm = int(input('What item would you like to view? ')-1)
print (shopping_lists[list][itm])
newItm = input('What would you like to change the item to? ')
shopping_lists[list][itm] = newItm
update_list(list, itm, newItm)
def view_item():
pass
def view_list():
pass
#While loop
while 'stop' not in customer_input:
update_list(list, itm, newItm)
I would rearrange your execution flow as follows.
shopping_lists = [
['toothpaste', 'q-tips', 'milk'],
['milk', 'candy', 'apples'],
['planner', 'pencils', 'q-tips']
]
def handle_action(action):
if action == '1':
update_list()
elif action == '2':
view_item()
elif action == '3':
view_list()
else:
pass
# What if an unrecognized action is used?
def update_list():
list_number = int(input('What list would you like to update? Answer using 1, 2, or 3. ')) - 1
print(shopping_lists[list_number])
itm = int(input('What item would you like to view? ')) - 1
print(shopping_lists[list_number][itm])
newItm = input('What would you like to change the item to? ')
shopping_lists[list_number][itm] = newItm
def view_item():
pass
def view_list():
pass
#While loop
customer_input = ''
while customer_input != 'stop':
print(shopping_lists)
print("Press 1 to update an item, 2 to view an item, or 3 to view a list")
customer_input = input("What do you want to do? ")
handle_action(customer_input)
Notice the difference on the usage of stop as a break word for the loop. And the handle_action function to control a switch of what you are doing.
I also renamed list to list_number because list is a type name in python.

How to do the program will terminate if your user input's first letter of a word is not capitalize?

How do I make this program accepts only a user input that's been typed while following a proper capitalization. Like it won't accept "robin hood" unless it's "Robin Hood". When I run it, it says...
Traceback (most recent call last):
File "C:\Users\AMD-Ryzen\Documents\PY CODEX\3.1.py", line 20, in <module>
if x.isupper() == false:
AttributeError: 'list' object has no attribute 'isupper'
Here's my code:
#List of the movies
lst = ['Spidey', 'Castaway', 'Avengers', 'GI. JOE', 'Shallow']
#The data stored in this list will come from input("Name of movie") using .append
x=[]
print("Enter at least 5 of your favorite movies"+"\n")
#Loop to repeat the same question 5 times
for i in range(5):
x.append(input("Name of movie:"))
#I used the set.intersection method to find the common elements between the two list
lst_as_set = set(lst)
intersection = lst_as_set.intersection(x)
intersection_as_lst = list(intersection)
if x.isupper() == false:
print("It will never work out. Nice meeting you!")
elif len(intersection_as_lst) == 3:
Ques = input("\n"+"Do you love some of his movies?:")
if Ques == "yes":
print("\n"+"You have", len(intersection_as_lst), "common fave movies and they are:")
print(intersection_as_lst)
elif Ques == "no":
print("It will never work out. I dont like")
s = set(x) - set(lst)
print(s)
elif len(intersection_as_lst) == 0:
Ques = input("Do you love some of his movies?:")
if Ques == "yes":
print("It will never work out. Nice meeting you!")
else:
print("It will never work out. Nice meeting you!")
The error occurs because you are trying to apply a string method isupper() to a list. You must use a loop with the parameter:
for c in x:
if not c[0].isupper():
print("It will never work out. Nice meeting you!")
break
First in python it is False and not false.
and as you want to stop the program you can raise an exception
x = list()
print("Enter at least 5 of your favorite movies\n")
for i in range(5):
m_name = input("Name of movie: ")
if m_name[0].islower():
raise 'must start with an uppercase letter'
x.append(m_name)
You are checking if list is isupper .
You'll need to do
output = []
for word in x:
if word[0].isupper() == False:
output.append(word)
print("It will never work out. Nice meeting you!")
def ìs_properly_capitalized(word: str) -> bool:
if not word:
return False
return word[0].isupper() and not any([c.isupper() for c in word[1:]])
results = [ìs_properly_capitalized(word) for word in lst]
if False in results:
print("One or more words not properly capitalized")
sys.exit(1)

While loop not working properly when condition is met

I am trying to append items to a list, and when I type the word "quit" the loop should stop, and then print the items I have on my list, but the loop continues and still asks me the second question on the loop, which I think should not be happening.
itemName = ''
itemPrice = '0.0'
while itemName != 'quit'.lower().strip():
itemName = input('What item would you like to add?')
items.append(itemName + ' $' + itemPrice)
itemPrice = input(f'What is the price of {itemName}?')
for item in items[:-1]:
print(item)
I see one problem, you have your .lower().strip on the wrong side.
Also, I would suggest using break so that your code won't ask for a price if quit is inputted.
items=[]
itemName = ''
itemPrice = '0.0'
while True:
itemName = input('What item would you like to add?')
if itemName.lower().strip() == 'quit':
break
items.append(itemName + ' $' + itemPrice)
itemPrice = input(f'What is the price of {itemName}?')
for item in items[:-1]:
print(item)
The code only checks if you wrote quit after it asks both questions. Also, you should put your .lower().strip() after the input() function. Your code always lowercases and strips the string 'quit'. You can put an if statement after the first question with a break to prevent your code from asking you the second question after you typed 'quit' for the first question.
Try to study this.
items = [] # storage
totalPrice = 0.0
while True:
itemName = input('What item would you like to add? ')
if itemName.lower() == 'quit':
break
itemPrice = input(f'What is the price of {itemName}? ') # ask the price before saving the item
if itemPrice.lower() == 'quit':
break
totalPrice += float(itemPrice) # convert str to float
items.append(f'{itemName} $ {itemPrice}') # Save to storage
print('items:')
for item in items:
print(item)
print()
print(f'total price: $ {totalPrice}')
Output
What item would you like to add? shoes
What is the price of shoes? 600.75
What item would you like to add? bag
What is the price of bag? 120.99
What item would you like to add? quit
items:
shoes $ 600.75
bag $ 120.99
total price: $ 721.74

How can you multiply a value from a dictionary with a number to get a real value?

store={'Rice':450,'Beans':200,'Egg':40,'Fish':250,'Spag':250}
bill=()
total=()
print('Welcome!!!we sell:',"\n",[store])
while True:
a=input('What would you like to buy?=')
b=input('how many of each product do you want?=')
if a in store:
bill=store[a]*b
print('bill=',bill)
elif a not in store:
print('Sorry we don\'t have that')
else:
total=bill+total
print('Total=',total)
Your if/elif/else is impossible, because wether a is IN the dict, wether it isn't, there is no way you into the else so put it in the if.
I'd also added a way to stop the loop by entering stop without you won't be able to stop the program and print the final total
move b input into the if, that isn't necessary to ask for quantity if the product isn't available
added int() conversion on b
store = {'Rice': 450, 'Beans': 200, 'Egg': 40, 'Fish': 250, 'Spag': 250}
print('Welcome!!!we sell:', "\n", store)
total, bill = 0, 0
while True:
a = input('What would you like to buy? ("stop" to quit): ')
print(">" + a + "<") # For OP debug purpose only, to be removed
if a == "stop":
break
if a in store:
b = int(input('how many of each product do you want?='))
bill = store[a] * b
total += bill
print(f"Total={total} (+{bill})")
else:
print('Sorry we don\'t have that')
print('Total=', total)

Categories

Resources