Why does my code keep printing the first data in the array? - python

i = 0
one_adult = [20.00,30.00]
one_child = [12.00,18.00]
one_senior = [16.00,24.00]
family_ticket = [60.00,90.00]
groups_of_six = [15.00,22.50]
lion_feeding = 2.50
penguin_feeding = 2.00
evening_barbecue = 5.00
Ticket_Type = ["one_adult",one_adult[i],"one_child",one_child[i],"one_senior",one_senior[i],"family_ticket",family_ticket[i],"groups_of_six",groups_of_six[i]]
Attractions_1day = ["lion_feeding",lion_feeding,"penguin_feeding",penguin_feeding]
Attractions_2day = ["lion_feeding",lion_feeding,"penguin_feeding",penguin_feeding,"evening_barbecue",evening_barbecue]
option = input("are you buying tickets for one day? (yes or no)")
if option == "yes" :
print()
print("These are ticket types available for one day tickets and their prices $")
print()
print(Ticket_Type)
print()
print("These are the attractions available for one day tickets and their prices $")
print()
print(Attractions_1day)
elif option == "no" :
i = i + 1
print()
print("These are ticket types available for two day tickets and their prices $")
print()
print(Ticket_Type)
print()
print("These are the attractions available for two day tickets and their prices $")
print()
print(Attractions_2day)
Why does it keep printing the data when i = 0 and not the data when i = 1?
It is supposed to print one_adult, 30 not one_adult 20 etc
The program is supposed to display the options available for people to buy tickets (1 day / 2 day)

Move the line:
Ticket_Type = ["one_adult",one_adult[i],"one_child",one_child[i],"one_senior",one_senior[i],"family_ticket",family_ticket[i],"groups_of_six",groups_of_six[i]]
to if and elif clause
if option == "yes" :
//Here
Ticket_Type = ["one_adult",one_adult[i],"one_child",one_child[i],"one_senior",one_senior[i],"family_ticket",family_ticket[i],"groups_of_six",groups_of_six[i]]
print()
print("These are ticket types available for one day tickets and their prices $")
print()
print(Ticket_Type)
print()
print("These are the attractions available for one day tickets and their prices $")
print()
print(Attractions_1day)
elif option == "no" :
i = i + 1
//And here.
Ticket_Type = ["one_adult",one_adult[i],"one_child",one_child[i],"one_senior",one_senior[i],"family_ticket",family_ticket[i],"groups_of_six",groups_of_six[i]]
print()
print("These are ticket types available for two day tickets and their prices $")
print()
print(Ticket_Type)
print()
print("These are the attractions available for two day tickets and their prices $")
print()
print(Attractions_2day)

Check your code properly, You have specified i=0 and and in every place in the Ticket_type array you have put one_adult[i] which is just the first element of the array i.e "20".
You haven't increased the value of i after every iteration. like you have to put loops to increase the value so that other elements of the array is printed.
To solve your problem do this
["one_adult",one_adult[0],"one_child",one_child[1],"one_senior",one_senior[2],"family_ticket",family_ticket[3],"groups_of_six",groups_of_six[4]]
Reply if this was helpful or you want better explanation.

Related

I want to make a nested loop that makes user enter a number that does not make the input variable have a negative output. How with changing variable?

This is Python in Visual Studio Code. I'm making a program for school that essentially is an robotic restaurant waitress. I have to do it the way the assignment outline says which is why it might be a little weird. Then I have to personalize it and make it creative. It asks how much the price of an adult meal and a child meal. Then it asks how many children and adults there are. Then it asks what the sales tax rate is. The assignment only needs me to be able to calculate all that and get the subtotal and total and then give change. I've already done that and I'm making it fancy. I made a loop that asks if they have a lucky draw coupon that generates a random monetary value between $1.00-$5.00. Then If they say yes it will bring them to the first part of the loop that gives them the total with the coupon and then asks for payment. If they say no, then it just asks them for the payment.
I want to go the extra mile and put a loop in a loop, which I think is called a nested loop (This is my first week of Python.) I want it to recognize if the amount they pay is less then the total, then ask for the user to try again until they put an amount more than the total. Pretty much I just want it to know that the payment isn't enough.
My problem is I've never used nested loops and this is the first time I've even used a loop period. I also don't know how to make a loop based on a variable that's not constant because it's based on what the user inputs when prompted. I could do it if I could put the parameters in a fixed range, but the range will always be different based on what they enter in the beginning.
How do I make a nested loop recognize a variable that is never the same?
How do I make it recognize the payment is not enough to cover the total?
This is the loop I have. And I want to put two nested loops in the loop. One for if and one for elif so that it works for both "options".
Here is my snippet:
while True:
coup = input("Do you have a lucky draw coupon? 1 for YES 2 for NO: ")
if coup =="1":
#calling the random function and also rounding it so that it comes out as two decimal places
coupon = round(random.uniform(1.00,5.00),2)
print()
print("---------------------")
#tells the user how much they save and the :.2f is making sure it has two decimal places
print(f"You will save ${coupon:.2f}!")
print("---------------------")
print()
newtotal = total - coupon
print(f"Your new total is: ${newtotal:.2f}")
print()
payment = float(input("Please enter your payment amount: "))
change2 = payment - total + coupon
change2 = round(change2, 2)
print(f"Change: ${change2:.2f}")
print()
print("---------------------------------------------------------------------")
print("Thank you party of", capitalized_string, "for choosing Erin's Cafe! Have a great day!")
print("---------------------------------------------------------------------")
print()
#break stops the loop from looping again
break
elif coup == "2":
print()
print("That's ok! Maybe next time!")
print()
payment = float(input("Please enter your payment amount: "))
change = payment - total
change = round(change, 2)
print(f"Change: ${change:.2f}")
print()
print("---------------------------------------------------------------------")
print("Thank you party of", capitalized_string, "for choosing Erin's Cafe! Have a great day!")
print("---------------------------------------------------------------------")
print()
break
else:
print()
print("Invalid response. Please type 1 for YES and 2 for NO: ")
Any suggestions? I've searched all over Stackoverflow and google and cannot find anything specific to my situation.
Your approach is good for implementing this. Looping while asking for payment and validating that it is correct before allowing the loop to break will do the job. For your first if block, this is how that would look:
while True:
coup = input("Do you have a lucky draw coupon? 1 for YES 2 for NO: ")
if coup =="1":
#calling the random function and also rounding it so that it comes out as two decimal places
coupon = round(random.uniform(1.00,5.00),2)
print()
print("---------------------")
#tells the user how much they save and the :.2f is making sure it has two decimal places
print(f"You will save ${coupon:.2f}!")
print("---------------------")
print()
newtotal = total - coupon
print(f"Your new total is: ${newtotal:.2f}")
print()
#Ask for the payment inside of the new loop
while True:
payment = float(input("Please enter your payment amount: "))
if payment - total + coupon > 0:
print("That's not enough money to pay your bill. Try again")
else:
break
change2 = payment - total + coupon
change2 = round(change2, 2)
print(f"Change: ${change2:.2f}")
print()
print("---------------------------------------------------------------------")
print("Thank you party of", capitalized_string, "for choosing Erin's Cafe! Have a great day!")
print("---------------------------------------------------------------------")
print()
#break stops the loop from looping again
break
elif coup == "2":
print()
print("That's ok! Maybe next time!")
print()
payment = float(input("Please enter your payment amount: "))
change = payment - total
change = round(change, 2)
print(f"Change: ${change:.2f}")
print()
print("---------------------------------------------------------------------")
print("Thank you party of", capitalized_string, "for choosing Erin's Cafe! Have a great day!")
print("---------------------------------------------------------------------")
print()
break
else:
print()
print("Invalid response. Please type 1 for YES and 2 for NO: ")

how to assign/put a value to an index in a list in python

I'm creating this program in python that calculates you total cost according to how much you choose.
so the program is pizza delivery, and the user has to choose their choice of pizza out of the menu.
what I cant figure out is that how to tell python that whatever the users first,second and third choice is, the cost will be 3 dollars and the rest would be 5 dollars.
what I mean in more dept would be that how do i tell python that the users 1st,2nd,3rd choice/input = $3.
I tried writing: menu[0:3] = 3 but that just changes the food in the array/list.
this is a sample of my code(not the full code)
Code :
i = 1
total_cost = 0
while(True):
choice = input("Please Enter Your Choice:")
if(i<4):
price = 3
total_cost = total_cost + price
else:
price = 5
total_cost = total_cost + price
i = i + 1
check = input("Do you want to enter another choice? (y/n)")
if(check=="N" or check="n" or check=="No" or check=="no"):
break
print("Total Cost : $",total_cost)
Output :
Please Enter Your Choice:tea
Do you want to enter another choice? (y/n)y
Please Enter Your Choice:coffe
Do you want to enter another choice? (y/n)y
Please Enter Your Choice:apple
Do you want to enter another choice? (y/n)n
Total Cost : $ 9
Try this function:
def price(choice):
if choice <= 3:
cost = 3
else:
cost = 5
return cost
price(4)
> 5
You can create a counter variable for tracking inputs, increment it after taking each input. And then in the price section of your code, use an if statement to set price to 3 if counter < 4, else set price to 5.
# Create counter variable
counter = 0
# Taking user input code here
counter = counter + 1
# Later when setting price in code
if counter < 4:
price = 3
else:
price = 5
Hope this gives you some ideas, feel free to comment and ask for more clarification if you need to!
You should do something like this:
for i in range(1, number_of_pizza+1):
if i < 4:
total_cost += 3
if i >= 4:
total_cost += 5
According to my understanding of your question, you would want to have the menu items separated in the list as :
menu = ['Cheese', 'Vege delight', 'pineapple', 'pepperoni','meat lovers', 'butter chicken', 'spicy corn delight', 'veg slingshot']
and not in the way in which you had shown it in your image.

Recurring line disappearance, issue with while loop

*I'm new to python, so be gentle...
Overall issue: I have had an issue in multiple codes I've written lately where lines get skipped and it is obviously an error on my part. I know I must be messing up ordering of something, but I'm just not seeing it. My most recent issue can be found here: Is there any reason Python would skip a line?
Now, I want to write an application to pre-sell a limited number of tickets. Here are the conditions:
"Each buyer can buy as many as 4 tickets. There are a total of 15 tickets that are available to pre-sell. The program should prompt the user for the amount of tickets they want to purchase and then display the number of remaining tickets. Repeat until all tickets have been sold, and then display the total number of buyers."
A similar problem is occurring.
buy = int()
ticket_num = 15
buyers = 0
while ticket_num > 0:
buy = int(input("How many tickets would you like to purchase? "))
if buy > 4:
print("You cannot buy that many (4 max).")
buy = input("How many tickets would you like to purchase? ")
else:
ticket_num = ticket_num - buy
print("There are currently", ticket_num, "remaining.")
buyers = buyers + 1
print()
print("The total number of buyers was:", buyers)
It appears that the print line in the 'else' structure is not being read and I don't quite understand why...
Can anyone lend me any insight into what my overall misunderstanding is..?
I figured it out. I had a couple of things incorrect with this problem:
I did not have enough conditional statements (elif) to cover the requirements
I did not need to have the buy variable gather input again in the if statement because the while loop would already cause the program to prompt for input again.
I did not need to have the buy variable outside the while loop at all, I just had to initialize it before using it in the 'if' statement.
The solution is as follows:
tickets = 15
buyers = 0
print("There are currently", tickets, "tickets available.")
while tickets > 0 :
buy = int(input("How many tickets would you like to purchase? "))
if buy <= 4 and tickets - buy >= 0:
tickets = tickets - buy
buyers = buyers + 1
print("There are", tickets, "tickets remaining.")
elif buy > 4:
print("You cannot buy that many (4 max).")
elif tickets - buy < 0:
print("You can only buy what remains. Please see previous 'remaining' message.")
print()
print("There was a total of", buyers, "buyers.")
buy = int()
ticket_num = 15
buyers = 0
while ticket_num > 0:
buy = int(input("How many tickets would you like to purchase? "))
if buy > 4:
print("You cannot buy that many (4 max).")
#buy = input("How many tickets would you like to purchase? ")
else:
if ticket_num - buy>=0:
ticket_num = ticket_num - buy
print("There are currently", ticket_num, "remaining.")
buyers = buyers + 1
else:
print("There are currently", ticket_num, "remaining. You can buy up to", ticket_num, "tickets")
print()
print("The total number of buyers was:", buyers)
Here is the solution. Problem was you were getting input two times. Firstly below the while. Secondly below at the if statement.

Why cant i get the total from a While true loop

I cant seem to get the total from my while true loop. I am trying to write a code . That will get the total value for all the seats a waiter enters. But I keep getting the total like this Total:$ q I had set q to break if the user input it for a seats. Can you help me please. Here is my syntax.
while True:
seats = raw_input("Enter the value of the seat [q to quit]:")
if seats == 'q':
break
print "Total: $", seats
total = 0
while True:
seats = raw_input("Enter the value of the seat [q to quit]:")
if seats == 'q':
break
total += int(seats)
print "Total: $", str(total)
If you want it to show the total after each loop just push the print statement inside the loop.
You need to sum variable seats with your input value, not reassigning value.
You were wrong in choosing operator, you need to use +=, not =.
Replace your code with this:
while True:
input = raw_input("Enter the value of the seat [q to quit]:")
if input == 'q':
break
seats += input
print "Total: $", seats
After that, read this question and answers:
What exactly does += do in python?

How to pass arguments to function, differently different times?

I need to pass two different arguments to the code (cartype and bonus) and set a for loop, so that each time it loops a different kind of car would be displayed & a different bonus amount.
I have looked for several solutions on here, on google & in my textbook without any success. I know it would be easier to do them all seprately but this is what is required.
Any help would be fantasic :) Please find part of my code below.
def main():
#This program uses a while loop, to give the user the option to go again.
while True:
#This displays the heading & instructions.
print ('AUSSIE BEST CAR INCOME AND BONUS CALCULATOR')
print ('*********************************')
print('**Please input data in the following format: 10000 **')
print('**Please be aware that inputs of zero(0) are invalid**')
#The program asks the user to input the total price of the cars, one by one.
kluger_price = float(input('Please enter the selling price of the Toyota Kluger: $'))
patrol_price = float(input('Please enter the selling price of the Nissan Patrol: $'))
territory_price = float(input('Please enter the selling price of the Ford Territory: $'))
#The program asks the user to input the total amount of cars sold, one by one.
kluger_sold = int(input('Please enter the number of Toyota Klugers sold in 2014:'))
patrol_sold = int(input('Please enter the number of Nissan Patrols sold in 2014:'))
territory_sold = int(input('Please enter the number of Ford Territorys sold in 2014:'))
#The program calculates the totals of each of the cars, one by one.
kluger_total = kluger_price*kluger_sold
patrol_total = patrol_price*patrol_sold
territory_total = territory_price*territory_sold
total = kluger_total + patrol_total + territory_total
#The program calculates the total bonus
if total <= 500000:
bonus = 0.001*total
elif total <= 1000000:
bonus = 500 + (total - 500000)*0.002
elif total <= 5000000:
bonus = 1500 + (total -1000000)*0.003
elif total <= 10000000:
bonus = 13500 + (total - 5000000)*0.004
else:
bonus = 33500 + (total - 10000000)*0.005
#The program calculates the bonus contributed by each car
global kluger_bonus
kluger_bonus = kluger_total/total*bonus
global patrol_bonus
patrol_bonus = patrol_total/total*bonus
global territory_bonus
territory_bonus = territory_total/total*bonus
print ('*********************************')
#The program displays the total income made and bonus
print ('The amount made from the Toyota Klugers is $', format(kluger_total,',.2f'))
print ('The amount made from the Nissan Patrols is $', format(patrol_total,',.2f'))
print ('The amount made from the Ford Territorys is $', format(territory_total,',.2f'))
print ('The total amount amount made from all three cars is $', format(total,',.2f'))
print ('The total bonus for 2014 is $', format(bonus,',.2f'))
print ('The bonus contributed through the sale of the Toyota Klugers is $', format(kluger_bonus,',.2f'))
print ('The bonus contributed through the sale of the Nisssan Patrols is $', format(patrol_bonus,',.2f'))
print ('The bonus contributed through the sale of the Ford Territorys is $', format(territory_bonus,',.2f'))
cartype = ['Toyota Kluger', 'Nissan Patrol', 'Ford Territory']
bonus = [kluger_bonus, patrol_bonus, territory_bonus]
[CalculateAdditionalBonus(cartype, bonus) for cartype, bonus in enumerate(3)]
def CalculateAdditionalBonus(cartype,bonus):
rate = input('Please input the value the assessed for the additional bonus of the', cartype')
additional_bonus = rate*bonus
print('The additional bonus for the', cartype' is $', format(additional_bonus,',.2f')
def CalculateTotalBonus():
#This ends the while loop, giving the user the option to go again.
try_again = int(input('This is the end of the calculations.Press 1 to try again, 0 to exit.'))
if try_again == 0:
break
if try_again == 1:
print('===============================================================')
main()
I'm not sure if I understood your question correctly, but I guess you want to pass cartype and bonus into your CalculateAdditionalBonus function. If that's the case, just zip the two lists to combine them into a list of tuples, then iteratively feed into your function.
cartype = ['Toyota Kluger', 'Nissan Patrol', 'Ford Territory']
bonus = [kluger_bonus, patrol_bonus, territory_bonus]
[CalculateAdditionalBonus(cartype, bonus) for cartype, bonus in zip(cartype, bonus)]
The answer is to use an if-elif-else statement.

Categories