hopefully there is a simple answer for this. How can I take user input from a while loop and print all of the input (without using lists when writing this)? Is there a way to output this information when the number of executions from the user is unknown? I am only a beginner so if there is a simple way to do this just using basics please let me know!
Here is an example of what I am trying to ask:
Say I am asking the user for the name and price of an item. They have the option to enter more items, or stop the execution. Then the output would list the name of the items, the prices, and their total amount purchased. I would like to print out all of these items that they have inputted.
Output formatted something like this:
Item Name Item Price
Soap $ 3.98
Detergent $ 6.99
Chips $ 2.50
....
....
Your Total: $xx.xx
I know how to do everything else, just having issues displaying all of their given input after they stop the execution. Just needing some guidance in this area. Please let me know if there is anything I can clarify. Thanks in advance!
I am using Python 3.
So I hope this matches what you were asking for.
I used nested dictionries, incase you want more info per item, but I mean you can also use tuples if you want.
prompts = ["Item name", "Item price"]
flag = True
items = {}
indx = 0
while flag:
inp = input("Type 'new' to register a new item or 'exit' to exit ")
if inp == "new":
output = {}
for p in prompts:
inp = input(p)
output[p] = inp
indx += 1
items[indx] = output
if inp == "exit":
flag = False
This is fairly simple, but to explain the steps;
Typing new allows you to start entering a new item.
It asks the prompts that are listed in the prompts list.
(It also uses these prompts to name the values in the output dict)
Once all the data is in, it'll be indexed and added into the items dict.
Then the loop begins again. You can add the new item, or type exit to stop entering items.
Edit:
Also I decided to use a flag instead of breaks so you can modify if you want more stop conditions.
I didn't understand so well but I think you can use:
bill = ''
total_price = 0
while True:
item = input('(If Done Write Exit) Item Name: ')
if item == "exit":
break
price = input("price: ")
bill = bill + "Item: "+item + '\nPrice: ' + price + '\n\n'
total_price += int(price)
print('\n'*4)
print(bill+'\n\nTotal Price:',total_price)
Related
I am trying to use a while loop to keep asking which item to remove from a list until the user enters an existing index in python. Basically when the user is asked, "What item would you like to remove?" the user should be able to enter a number starting from 1 instead of zero, and up to whatever number of items, there are. For example, if there are ten items, the user should be able to enter 1 -10, not 0 - 9. I have already converted the user input to a zero-based index. Now I need to be able to keep asking "What item would you like to remove?" until the user inputs an existing index.
Here is the code that I am getting stuck on:
items = []
prices = []
quantities = []
item = input("\nWhat item would you like to remove? ").strip()
while item != range(0, len(items)):
print("\nSorry, that is not a valid number.")
item = input("\nWhat item would you like to remove? ").strip()
item_remove = items[int(item) - 1]
items.pop(int(item) - 1)
prices.pop(int(item) - 1)
quantities.pop(int(item) - 1)
print(item_remove + " removed.")
break
I shortened the code so you wouldn't have to read as much, but here is what is happening. When I put in an existing index it displays the print statement "Sorry, that is not a valid number." and then asks for the input "What item would you like to remove?" a second time then after you enter an existing index again it removes the item and goes back to the main menu option that I am using in my code. However, if you enter an index that does not exist, it displays the print statement "Sorry, that is not a valid number." then asks "What item would you like to remove?", but the second time that I enter an index that does not exist the code crashes saying list index out of range. Is there any way that I could get this code to keep asking "What item would you like to remove?" followed by the print statement "Sorry, that is not a valid number." until I enter an existing index? If you need more code let me know, and I greatly appreciate any help or feedback.
In my tutorial book, the writer formate this program as shown in code no.2. while my intuitive tells me to write the program like shown in code no.1. Both programs get the job done for me, but is there a difference between these two codes? If there is, which way is better, in your opinion?
#1
total = 0
count = 0
while (True):
inp = input('Enter a number: ')
if inp == 'done':
break
else:
value = float(inp)
total = total + value
count = count + 1
average = total / count
print('Average:', average)
#end of 1
#2
total = 0
count = 0
while (True):
inp = input('Enter a number: ')
if inp == 'done': break
value = float(inp)
total = total + value
count = count + 1
average = total / count
print('Average:', average)
#end of 2
There isn't any difference in how the code runs, sometimes it might be nicer to use a one line if statement. One way isn't objectively better, it comes down to context and personal preference. So choose the way you prefer. If you are ever in any doubt about Python Syntax and its style check out the official Python Style Guide.
One of the key takes from the style guide is that readability counts, so try to pick the most readable option.
I think your way is more readable, but the extra tab on the if statement as well as the else statement is not necessary. I prefere the first option because of the readability
If you are more comfortable using the first syntax, then you can use it without any problem.
However, let me explain the differences between the two code:
Using 'break' means that whenever inp == 'done' is true, then you will exit the current loop and continue. Hence, using an 'else' is not mandatory, because it either reaches or do not reach what you wrote in your 'else' statement, it cannot go in both the if and the else statement.
Otherwise, that is pretty much it, both codes will give you the same thing :D!
My question is about getting a user to pull and item from a list. If the item from the list isn't pulled from the list I want to tell the user that he is incorrect. So my code looks like this:
Body_Type = ['Large', 'Medium', 'Small']
print('Create a Character-')
print('Body Type Choices: ' + str(Body_Type))
bt = input('Enter your Body Type: ')
while bt != Body_Type:
if bt == Body_Type[0:]:
print('Your Body Type is: ' + bt)
else:
print('Invalid Body Type')
What I'm trying to do is make my user create a character. This is just the first part of my first simple project. I want to have him pull from one of the items on the list, being "Large, Medium, Small" respectively. I want it to repeat until the user chooses one of the three. I tried to use or but it seems to feel unorganized and I'd have to break up the list and assign each individual variable.
Thanks in advance!
Several errors here like comparing a string to a list, or random slicing hoping that it would work. And the fact that your input statement is before the loop creates an infinite loop because you're comparing 2 variables of a different type again and again (bt != Body_Type is always True regardless of the content of bt since left hand is a string, right hand is a list).
But it shouldn't be so complex to write some working code.
I would create an infinite loop and break only if choice is in the list:
while True:
bt = input('Enter your Body Type: ')
if bt in Body_Type:
print('Your Body Type is: ' + bt)
break
else:
print('Invalid Body Type')
simpler and clearer (and repeats input if fails). The infinite loop (with an always true condition) allows to avoid double input call & test. Just loop, input the string, and break from the loop if matches.
The key statement you were looking for was bt in Body_Type which tests if the string is within the list.
I'm very new at coding, and I'm trying to create a shop list with items and prices on it.
That is, once typed in all the items, the function should calculate the sum and stop the moment you exceed the budget.
So I wrote something like:
def shoplist():
list={"apple":30, "orange":20, "milk":60......}
buy=str(input("What do you want to purchase?")
If buy in list:
While sum<=budget:
sum=sum+??
shoplist ()
I really don't know how to match the input of an item with the price in the list...
My first thought is to use 'if', but it's kinda impractical when you have more than 10 items on the list and random inputs.
I'm in desperate need of help....So any suggestions would be nice!! (or if you have a better solution and think me writing it this way is complete garbage... PLEASE let me know what those better solutions areðŸ˜ðŸ˜ðŸ˜
The code you post will not run in python. list is a builtin and should not be used for a variable name, and is doubly confusing since it refers to a dict object here. input() already returns a str so the cast has no effect. if and while should be lowercase, and there is no indentation, so we have no way of knowing the limits of those statements.
There are so many things wrong, take a look at this:
def shoplist(budget):
prices = {"apple":30, "orange":20, "milk":60}
# Initialise sum
sum = 0
while sum <= budget:
buy = input("What do you want to purchase?")
# Break out of the loop if the user hts <RETURN>
if not buy: break
if buy in prices:
sum += prices[buy] # This gets the price
else:
print("Invalid item", buy)
shoplist(142)
So what have I changed? The budget has to come from somewhere, so I pass it in as a parameter (142, I made that up). I initialise the sum to zero, and I moved the while loop to the outside.
Notice as well lots of whitespace - it makes the code easier to read and has no effect on performance.
Lots of improvements to make. The user should be shown a list of possible items and prices and also how much budget there is left for each purchase. Note as well that it is possible to go over budget since we might only have 30 in the budget but we can still buy milk (which is 60) - we need another check (if statement) in there!
I'll leave the improvements to you. Have fun!
Take a look at this as an example:
# this is a dictionary not a list
# be careful not using python reserved names as variable names
groceries = {
"apple":30,
"orange":20,
"milk":60
}
expenses = 0
budget = 100
cart = []
# while statements, as well as if statements are in lower letter
while expenses < budget:
# input always returns str, no need to cast
user_input = input("What do you want to purchase?")
if user_input not in groceries.keys():
print(f'{user_input} is not available!')
continue
if groceries[user_input] > budget - expenses:
print('You do not have enough budget to buy this')
user_input = input("Are you done shopping?Type 'y' if you are.")
if user_input == 'y':
break
continue
cart.append(user_input)
# this is how you add a number to anotherone
expenses += groceries[user_input]
print("Shopping cart full. You bought {} items and have {} left in your budget.".format(len(cart), budget-expenses))
I've made some changes to your code to make it work, with explanation including using comments indicated by the # symbol.
The two most important things are that all parentheses need to be closed:
fun((x, y) # broken
fun((x, y)) # not broken
and keywords in Python are all lowercase:
if, while, for, not # will work
If, While, For, Not # won't work
You might be confused by True and False, which probably should be lowercase. They've been that way so long that it's too late to change them now.
budget = 100 # You need to initialize variables before using them.
def shoplist():
prices = { # I re-named the price list from list to prices
'apple' : 30, # because list is a reserved keyword. You should only
'orange' : 20, # use the list keyword to initialize list objects.
'milk' : 60, # This type of object is called a dictionary.
} # The dots .... would have caused an error.
# In most programming languages, you need to close all braces ().
# I've renamed buy to item to make it clearer what that variable represents.
item = input('What do you want to purchase? ')
# Also, you don't need to cast the value of input to str;
# it's already a str.
if item in prices:
# If you need an int, you do have to cast from string to int.
count = int(input('How many? '))
cost = count*prices[item] # Access dictionary items using [].
if cost > budget:
print('You can\'t afford that many!')
else:
# You can put data into strings using the % symbol like so:
print('That\'ll be %i.' % cost) # Here %i indicates an int.
else:
print('We don\'t have %s in stock.' % item) # Here %s means str.
shoplist()
A lot of beginners post broken code on StackOverflow without saying that they're getting errors or what those errors are. It's always helpful to post the error messages. Let me know if you have more questions.
I am trying to create a python array that can hold as many strings as the user enters. I am trying to implement it in a loop, like this :
(Loop:)
Enter the string:
array[1] = (string entered by user)
Enter the next string:
array[2] = (second string entered by user)
....
Enter the nth string:
array[n] = (nth string entered by user)
How can I achieve this? I have heard of dynamic arrays and lists and stuff, but I can't figure them out.
Thank you in advance.
The default lists in Python are dynamic arrays. You can simply initialize it with:
data = []
and use:
data.append(item)
to add an element at the end.
For example:
data = []
while True:
print('Enter the string:')
data.append(input())
This will go on until all the memory of your machine is exhausted.
You can also for instance specify a way to stop asking the user for more data. For instance if the user enters '-1', you can say the loop should stop:
data = []
while True:
print('Enter the string:')
the_input = input()
if the_input == '-1':
break
data.append(the_input)
#do something with the collected data
Now if you for instance run this code: the code will query for input until you enter -1 (I think it is rather obvious how you can change the stopword). Then data contains all data entered before and you can process it somehow.
Try this:
all_the_things = list()
for x in items:
all_the_things.append(x)
For more reading: Python Data Structures
If you want to add to a list, use append
data = []
data.append('whatever')
You haven't asked about how to get the input, so I assume you can do that.
Do bear in mind your computer will not have infinite storage - at some point you will run out of memory if you do this in a loop for ever.