Python vending machine snacks and drinks [closed] - python

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
Hi guys I have been trying to create a working python vending machine for over a month now and it doesn't look like I am making any progress. If somebody could help me that could be great :) Here is my program so far:
print ("Welcome to the Vending Machine\n")
total = 0
dr = 1
sn = 3
money=int(input("How much money do you want to insert"))
print ("Prices: Drinks: £1, Snacks: £3\n")
Drinks = {'Coke','Pepsi','Orange Juice', 'Apple Juice','Water'}
Snacks = {'Chocolate', 'Snickers','Twix','Peanuts','Crisp'}
state = 'subtotal'
while total <= money:
if state != 'total':
print('')
print('')
print ("\nDrinks Menue:")
print(Drinks)
print ("Snacks Menue:")
print(Snacks)
choice = input("\nEnter the item of your choice: ")
if choice in Drinks:
total += dr
elif choice in Snacks:
total += sn
else:
state = 'total'
print("\n\nThat will be a",state,"of £",total)
else:
print("You have exceeded your inserted money good bye")
I'm trying to make the code reject invalid input and stop when the user has gone over his spending limit.

There is only one problem with this when I run this. So, here is the fix with some explanation so you can learn something. It may seem like a simple mistake but we all make them at some point and eventually, indenting will be second nature.
Indents
Unlike some langues, in Python the indentation matters. A lot. Let's look at your first if statement.
if state != 'total':
print('')
print('')
print ("\nDrinks Menue:")
print(Drinks)
print ("Snacks Menue:")
print(Snacks)
choice = input("\nEnter the item of your choice: ")
Can you see the problem? After an if statment, or more precisely, after the :, we need to indent everything else that we want to be carried out by the if statement otherwise Python won't know where to stop! So by making this simple change:
if state != 'total':
print('')
print('')
print ("\nDrinks Menue:")
print(Drinks)
print ("Snacks Menue:")
print(Snacks)
We have no more error and your program now runs. Notice the indents? Just check that they are always right.

Related

Python Invalid Syntax: Print and Elif statements [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I am really new to Python and programming (2 days to be exact). I was messing around in idle trying to come up with a more complicated process than just print "Hello world." I was wondering if any of you could tell me why it is marking my print and elif statements invalid. I am using Python 2.7.10, thanks!
A = raw_input("Do you live in the US or Canada?")
if A == " US" or "Canada":
print "Welcome!"
else:
print "We're sorry, but your country is currently not supported!"
B = int(raw_input("How much is your package?")
if B >= 25
print "Your shipping is $4.00"
elif B >= 50
print "Your shipping is $8.00"
else:
print "Congrats, your shipping is free!"
Probably the first thing you notice about python is that consistent indentation is not just a good idea, it is mandatory. Experienced programmers, whether they write Python or not, always do that anyway so it is no big deal. Use spaces (4 is the norm) and avoid tabs - change your editor to replace a tab with 4 spaces.
It is a bad idea to use float on money amounts because of rounding. Better to use a large type, like Decimal, or store the amount as an int in cents, then insert a decimal point when you display. For simplicity I have stuck with using float, but be warned.
You have a number of logic errors in your code, as well as issues with style. Programming style is not just about what looks nice, it is whether you can understand your code later, when you come back to it.
Style points:
Don't use UPPERCASE for variables. By convention UPPERCASE is reserved for constants
Use meaningful variable names, not A and B
Here is a corrected program, with comments. Please read the comments! :
# This is a comment, it is ignored by python
# This is used later on by sys.exit()
import sys
# Logically the user would enter "Yes" or "No" to this quesion,
# not US or Canada!
ans = raw_input("Do you live in the US or Canada? ") # Notice the space after ?
# Note how the condition has been expanded
if ans == "US" or ans == "Canada":
print "Welcome!"
else:
print "We're sorry, but your country is currently not supported!"
# Now what? Your program just carried on. This will stop it
sys.exit()
# I'm using a floating point number for simplicity
amount = float(raw_input("How much is your package? "))
# I changed this around, since 50 is also >= 25!
# However, this is strange. Usually the more you spend the LESS the shipping!
# You were missing the : after the condition
if amount >= 50:
print "Your shipping is $8.00"
amount += 8 # This adds 8 to the amount
elif amount >= 25:
print "Your shipping is $4.00"
amount += 4 # This adds 4 to the amount
else:
print "Congrats, your shipping is free!"
# print the amount showing 2 decimal places, rounding
print "Amount to pay: $%.2f" % (amount)
You have plenty more to do. Maybe cope with the user entering lower or mixed case letters for the country name - and ask yourself if the question is logical to the user.
Later you might want to have a list of valid countries, and use in to test if the user entered a valid country. Then expand it to use a dictionary, indicating currency symbols, shipping amounts, and currency conversion rates for each country.
Enjoy Python!
Fixed it for you :). Take a look to see what's different, and you will learn, young padawan:
A = raw_input("Do you live in the US or Canada?")
if A == "US" or A == "Canada":
print "Welcome!"
else:
print "We're sorry, but your country is currently not supported!"
B = float(raw_input("How much is your package?"))
if B >= 25:
print "Your shipping is $4.00"
elif B >= 50:
print "Your shipping is $8.00"
else:
print "Congrats, your shipping is free!"

How could I loop a code involving a list [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm fairly new to python and I was wondering if someone was able to help me with looping this block of code and I did looping in the past but this one involves a list element having to change every time 1 through to 10 and I don't know how I could make that change.
print ("Question 1: ")
print (questions[0])
#asks for the answer from the user
ans = int(input())
#compares the users input to the answer
if ans == eval(questions[0]):
print ("Well done, you got it correct")
#if correct grants a point to the overall score
score = score + 1
The closest way to do so while maintaining your code is the following
for index, question in enumerate(questions):
print ("Question {}: ".format(index+1))
print (question)
#asks for the answer from the user
ans = int(input())
#compares the users input to the answer
if ans == eval(question):
print ("Well done, you got it correct")
#if correct grants a point to the overall score
score = score + 1
Note that you should avoid using eval because it is unsafe. Recommended alternatives are to either make a dictionary with pre-baked questions and answers, e.g.
questions = {'What is 5 + 4?' : 9,
'What is 3 - 1?' : 2}
Or programmatically come up with questions and answers.

Write a Python program that repeatedly asks the user to input coin values until the total amount matches a target value [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
However, I realized that I don't actually know how to do this myself without examining every possible combination of coins. There has to be a better way of solving this problem, but I don't know what the generic name for this type of algorithm would be called, and I can't figure out a way to simplify it beyond looking at every solution.
I was wondering if anybody could point me in the right direction, or offer up an algorithm that's more efficient.
You can try something like this:
MaxAmount = 100
TotalAmount = 0
while TotalAmount < MaxAmount:
#Here if you want it to be more precise on decimals change int(raw_input("Amount: ")) to float(raw_input("Amount: "))
EnteredAmount = float(raw_input("Amount: "))
if EnteredAmount > MaxAmount:
print "You can not go over 100"
elif TotalAmount > MaxAmount:
#You can go two ways here either just set TotalAmount to MaxAmount or just cancel the input
print "You can not go over 100"
elif EnteredAmount <= MaxAmount:
TotalAmount = TotalAmount + EnteredAmount
print TotalAmount
print "You have reached the total amount of ", MaxAmount
Could use a loop into an if - elif - else statements
e.g. populate a variable with your amount, then using this for the loop condition keep asking to take away coin amounts until you reach 0

Python 3.3: How to create a loop for a string [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I apologize for the title not being clear, anyways how do I create a loop that will put numbers into a string, what i mean is (this is from the assignment im doing):
Enter number of courses:
Enter grade for course no. 1:
Enter weight for course no. 1:
Enter grade for course no. 2
......
Enter grade for course no. 7
......
Enter weight for course no. 9
So how would i do something like this, i have to create an input statement which has numbers in order (1-infinity but limited by number of courses). Thank you if you need anymore information or for me to clarify let me know.
You can use string formatting:
noc = int(input('Enter number of courses: '))
for i in range(1, noc+1):
grade = input('Enter grade for course no. {}: '.format(i))
weight = input('Enter weight for course no. {}: '.format(i))
#do something with grade and weight here.

Python Help Again [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I am using Python 3.2 Just so you know what I am doing, here is the assignment:
~The function random.randint from the random module can be used to produce an integer from a range of values. For example, random.randint(1,6) produces the values 1 to 6 with equal probability. A simple tutoring program may randomly select two numbers between 0 and 12 and ask a question such as the following: What is 6 times 8? Upon receiving user response, the computer checks to see if the answer is correct and gives encouraging remarks. Write a program that will loop 10 times producing questions of this form and gives a score for the user at the end.
Here is what I have in my program:
print ("Hello. Let's begin")
for i in range (1,10):
from random import randint
x=randint (0,12)
y=randint (0,12)
print (x,"*" y,"=?")
product= int(input ("What is the product?")
if (product==x*y):
print ("Awesome! That is correct!")
else:
print ("Sorry, that is not correct, but let's try another one!")
I have everything working with all of this. It asks the user a random multiplication question and responds ten times. What I do not understand how to do is to give the user a score at the end. I'm brainstorming ideas and not much is really working. I think I would have to do something like:
score=
But I don't know how to tell the program to calculate the number of correct answers... Do I say score=number of if?
And then when I print the score I can just say:
if (score>5) :
print: ("Great job! You scored a",score,"out of ten!")
else:
print: ("Not the best score, but you can try again! You scored a",score,"out of ten.")
Or is there maybe an easier way to do this?
It seems like it would be simplest to just make a new variable ("score" or suchlike) and initialize it as 0 before the loop. Then, when you check if a user was correct, just increment it by one if it was right, and leave it alone if it was wrong.
Hope this helps!
First, set score to 0
score = 0
then in the loop, try something like
if (product==x*y):
print ("Awesome! That is correct!")
score += 1
else:
print ("Sorry, that is not correct, but let's try another one!")
the important part being the score += 1 this increases the score by one when you get a correct answer. You can the put your score > 5 in after the loop.

Categories