I'm a freshman, and I want to make a bill that write out what I bought, quantity and how much total cash it cost.
customer = str(input("Customer's name: "))
print ("Welcome to our store")
print ("This is our products")
print ("orange 0.5$)
print ("Apple 1$)
print ("Grape 0.5$)
print ("Banana 0.5$)
chooseproducts= int(input("What do you want to buy: "))
For output example. Can you guys help me please.
BILL
Orange 5 2.5$
Apple 3 3$
Grape 2 1$
Total: 10 6.5$
First, your str(input(customer's name: )) code needs to be changed. input() calls need a string as the question, and also the apostrophe has Python think that it is the start of a string.
Also, when you are printing the costs, you need another closing quotation mark. When you are asking the user about what they want to buy, I suppose you want them to input the name of the fruit. Since you have the int() in the front, Python cannot turn a string like "orange" or "grape" into an integer. When people want to buy multiple things, however, they might only put one thing in.
I suppose that this isn't all your code, and you have the part where you calculate the cost. If I were to write this code, I would write it like the following:
customer = str(input("Customer's Name:"))
print ("Welcome to our store")
print ("This is our products")
print ("Orange 0.5$")
print ("Apple 1$")
print ("Grape 0.5$")
print ("Banana 0.5$")
prices = {"orange":0.5,"apple":1,"grape":0.5,"banana":0.5}# I added this so we can access the prices later on
#chooseproducts= int(input("What do you want to buy: "))
# The code below this is what I added to calculate the cost.
productnum = input("How many things do you want to buy: ") # This is for finding the number of different fruits the buyer wants
while not productnum.isdigit():
productnum = input("How many different products do you want to buy: ")
productnum = int(productnum)
totalprice = 0
totalfruit = 0
print(' BILL')
for i in range(productnum):
chosenproduct = input("What do you want to buy: ").lower()
while not chosenproduct in ['orange','apple','banana','grape']:
chosenproduct = input("What do you want to buy: ").lower()
fruitnum = input("How many of that do you want to buy: ")
while not fruitnum.isdigit():
fruitnum = input("How many of that do you want to buy: ")
fruitnum = int(fruitnum)
totalfruit += fruitnum
price = fruitnum * prices[chosenproduct]
totalprice += price
startspaces = ' ' * (11 - len(chosenproduct))
endspaces = ' ' * (5 - len(str(fruitnum)))
print(chosenproduct.capitalize() + startspaces + str(fruitnum) + endspaces + str(price) + '$')
print('Total: ' + str(totalfruit) + ' ' * (5 - len(str(totalprice))) + str(totalprice) + '$')
Please make sure you understand the code before copying it, thanks!
Related
food = ["pizza", "tacos", "lasagna", "watermelon", "cookies"]
plate = ""
for dish in food:
print(dish)
fav_dish = input("Is this your favorite dish? Y/N: ")
if fav_dish == "Y" and food[-1]:
plate += dish
elif fav_dish == "Y":
plate += dish + ", "
print("I want " + plate +"!")
I am practicing my coding skills and I want the results to look like this.
I want pizza, tacos, and cake!
The results look like this:
pizza
Is this your favorite dish? Y/N: Y
tacos
Is this your favorite dish? Y/N: Y
lasagna
Is this your favorite dish? Y/N: N
watermelon
Is this your favorite dish? Y/N: N
cookies
Is this your favorite dish? Y/N: Y
I want pizzatacoscookies!
You can create the variable plate as a list where you put the favorite dishes and then use the "".join() function.
You put in the commas the separator you want, and in the parenthesis the list to join. In your case:
print("I want " + ", ".join(plate) + "!")
Make plate a list, and append to it in the loop. In the end, you can use the following, which will output the correct commas and words:
", ".join(plate)
first make a list of selection, then operate on that list. This code ignores the case of an empty selection list and can be left as an exercise.
selected = []
for dish in food:
select = input(f'Is [{dish}] your favorite dish? Y/N: ')
if select == 'Y':
selected.append(dish)
# since the second option ignores the dish, you can dis include it from the list
if len(selected) > 1: # do I need the word and at the end of the list
selected[-1] = f'and {selected[-1]}'
separator = ', ' # define pattern for joining a list
print('I want ', separator.join(selected), '!', sep='') # the `sep` keyword (normally a space) is printed between words
Hi I am a newbiew learning python and i have a very simple question and can't seem to work it out.
I have built this little program and i was just wondering one thing.
print("Hello Sir !!!")
num1 = input("Enter a number: ")
num2 = input("Enter another Number: ")
result = float(num1) + float(num2)
print(result)
num3 = input("Enter your final Number: ")
result = float(num3) / (float(num1) + float(num2))
print("Your final total is:", result)
print("You are now finished")
print("Have an Amazing day!! ")
RESULT =
Hello Sir !!!
Enter a number: 50
Enter another Number: 50
100.0
Enter your final Number: 5
Your final total is: 0.05
You are now finished
Have an Amazing day!!
Process finished with exit code 0
If i wanted to write "Your final total is:0.05" or "Your final total is:
0.05"
How would i move it closer or further away?
Thank you for your help today
If you want to add more whitespaces, you can just added it inside the string. If you want a new line, you can use "\n" in your string, which indicate the start of a new line.
Check this link to find out more about escape characters:
https://www.tutorialspoint.com/escape-characters-in-python
You can do
print("Some string: " + variable) # Add a whitespace at the end of your string
if you have string with variable or
print(variable1 + ' ' + variable2)
If you need space between 2 variables or use \n if you need to make a newline
I have a homework task to basically create a supermarket checkout program. It has to ask the user how many items they are, they then put in the name and cost of the item. This bit I've worked out fine, however I'm having trouble adding the total together.
The final line of code doesn't add the prices together, it just lists them.
Code so far
print "Welcome to the checkout! How many items will you be purchasing?"
number = int (input ())
grocerylist = []
costs = []
for i in range(number):
groceryitem = raw_input ("Please enter the name of product %s:" % (i+1))
grocerylist.append(groceryitem)
itemcost = raw_input ("How much does %s cost?" % groceryitem)
costs.append(itemcost)
print ("The total cost of your items is " + str(costs))
This is for a homework task for an SKE I'm doing however I'm stumped for some reason!
The expected output is that at the end of the program, it will display a total costs of items added into the program with a £ sign.
You have to loop through list to sum the total:
...
total = 0
for i in costs:
total += int(i)
print ("The total cost of your items is " + str(total)) # remove brackets if it is python 2
Alternative (For python 3):
print("Welcome to the checkout! How many items will you be purchasing?")
number = int (input ())
grocerylist = []
costs = 0 # <<
for i in range(number):
groceryitem = input ("Please enter the name of product %s:" % (i+1))
grocerylist.append(groceryitem)
itemcost = input ("How much does %s cost?" % groceryitem)
costs += int(itemcost) # <<
print ("The total cost of your items is " + str(costs))
Output:
Welcome to the checkout! How many items will you be purchasing?
2
Please enter the name of product 1:Item1
How much does Item1 cost?5
Please enter the name of product 2:Item2
How much does Item2 cost?5
The total cost of your items is 10
You need to declare your costs as int and sum them:
print("Welcome to the checkout! How many items will you be purchasing?")
number = int(input ())
grocerylist = []
costs = []
for i in range(number):
groceryitem = input("Please enter the name of product %s:" % (i+1))
grocerylist.append(groceryitem)
itemcost = input("How much does %s cost?" % groceryitem)
costs.append(int(itemcost))
print ("The total cost of your items is " + str(sum(costs)))
There also seems to be a problem with raw_input. I changed it to input.
I want to create a while loop to prompt the user if they would like to enter a living cost. The user would input 'y' for yes and the loop would proceed.
I this loop I would like to add up all the living expense entered and once the loop ends to store to the total amount in total_living.
Example would be
l_cost = input('Enter living cost? y or n ')
while l_cost != 'n' (loop for living cost)
totat_living = (keeps adding until I say all done
l_cost = input('Enter living cost? y or n ')
Other while and for loops for different scenarios
total_exp = total_living + total_credit + total_debt ect ect
I just need a little help with this as to how to add up multiple values and then maintaining the total value for the loop that I am in.
If someone could point me to an example of a function or loop that is similar or tell me where to look that would be great!
You may try using while as below:
flag = input ("wish to enter cost; y or n" )
total=0
While flag != 'n':.
cost = int(input ("enter cost: "))
total = total + cost
flag = input("more ?? Y or n")
print(total)
total_cost = 0.0
prompt = 'Enter a living cost? y or n: '
answer = input(prompt)
while answer.lower() != 'n':
cost = input('Enter your cost: ')
total_cost = total_cost + float(cost)
answer = input(prompt)
print('Total cost is $' + str(total_cost))
def checkout():
total = 0
count = 0
moreItems = True
while moreItems:
price = float(input('Enter price of item (0 when done): '))
if price != 0:
count = count + 1
total = total + price
print('Subtotal: $', total)
else:
moreItems = False
average = total / count
print('Total items:', count)
print('Total $', total)
print('Average price per item: $', average)
checkout()
Note
Try to convert this example to your problem.
I want to input how many victims, and then be able to input name and age for each victims.
But I can't seem to wrap my head around how to make a loop that ask for input for each victim. Right now I make one input and the same input is printed x times.
I can see the logic in how it works now, but I simply can't figure out how to do it without making 5 x separate input for "name" and 5 x separate input for "age".
num_victims = input("How many victims: ")
inc_numbr = 1
v_name = input(str(inc_numbr) + "." + " Victims " + "name: ")
v_age = input(str(inc_numbr) + "." + " Victims " + "age: ")
inc_numbr += 1
v_numbr = 1
v_one = (f"__Victim:__ \n"
f"Name: {v_name}\n"
f"Estimated age: {v_age} years old.\n\n")
v_numbr += 1
v_two = (f"__Victim " + str(v_numbr) + ":__\n"
f"Name: {v_name}\n"
f"Estimated age: {v_age} years old.\n\n")
v_numbr += 1
v_three = (f"__Victim " + str(v_numbr) + ":__\n"
f"Name: {v_name}\n"
f"Estimated age: {v_age} years old.\n\n")
v_numbr += 1
v_four = (f"__Victim " + str(v_numbr) + ":__\n"
f"Name: {v_name}\n"
f"Estimated age: {v_age} years old.\n\n")
v_numbr += 1
v_five = (f"__Victim " + str(v_numbr) + ":__\n"
f"Name: {v_name}\n"
f"Estimated age: {v_age} years old.\n")
v_numbr += 1
Added for output format example:
__Victim:__
Name: xxxxx
Age: xxxx
__Victim 2:__
Name: xxxxx
Age: xxxx
Ect..
You need to wrap it up in a for loop:
number_of_victims = int(input("How many victims? "))
victim_names = []
victim_ages = []
for i in range(1, number_of_victims+1):
victim_names.append(input("Name of victim "+str(i)+": "))
victim_ages.append(input("Age of victim "+str(i)+": "))
print(victim_names, victim_ages)
Note how I have created the victim_names and victim_ages objects outside of the for loop so that they're not overwritten. These objects are lists - they're empty initially, but we append data to them inside the for loop.
You could use a dictionary object for victims instead if you wanted, but as Alex F points out below, if you have two victims with the same name this may result in data being overwritten:
number_of_victims = int(input("How many victims? "))
victims = dict()
for i in range(1, number_of_victims+1):
name = input("Name of victim "+str(i)+": ")
age = input("Age of victim "+str(i)+": ")
victims[name] = int(age)
print(victims)
In the future, when approaching a problem like this, you might find it helpful to write pseudo-code. This is like a plan for what your code will look like without having to worry about the syntax and rules for actually writing it. For example some pseudo-code for this problem might look like:
ask for the number of victims
make an empty object to store the victim information
repeat this as many times as there are victims:
ask for the name of the victim
ask for the age of the victim
add victim information into the object
display the contents of the object
In answer to the question in the comments, how to format the printing, you could do something like this:
for v in range(number_of_victims):
print("Victim ",str(v+1),":")
print("Name:",victim_names[v])
print("Age:",victim_ages[v])
Loop is used for code that needs to be run multiple times, therefore if you need to ask for number of victims once, but then enter multiple name's and age's, you can do it like this:
number_of_victims = int(input("Enter the number of victims: "))
victims = []
for i in range(number_of_victims):
name = input("Victim #{} name: ".format(i+1))
age = input("Victim #{} age: ".format(i+1))
victims.append([name, age])
This way you get a list, where each element is a list of name and age. Now you can access file number i with victims[i-1] (because list indices start with 0).
Another option would be using a dictionary:
number_of_victimes = int(input("..."))
victims = {}
for i in range(number_of_victims):
name = input("...")
age = input("...")
victims[i] = [name, age]
You can access file number i with victims[i-1] (because range starts at 0 as well) but you can change this if you write for i in range(1, int(number_of_victims)+1):. Now each dictionary key is the "human" index (starting from 1), instead of "computer's" index (starting from 0), so you can access the same file number i using victims[i].
Alternatively, you could make a dictionary where each key is the name of the victim, but in case you ever have 2 identical names, the previous key-value pair you have added using that name will get overwritten:
number_of_victimes = int(input("..."))
victims = {}
for i in range(number_of_victims):
name = input("...")
age = input("...")
victims[name] = int(age)