python loop in array adding individual item prices - python

I have the following code mostly working. I just need it to allow the user to input "add-ins" until they enter the sentinel value to exit the loop and have it add the selections up. This is for a class assignment, but this is all I am having difficulties with. Any help would be appreciated.
#start
def main(): #create a module - python function to hold main processing
#declarations
addinArray = ["Whipped Cream", "Cinnamon", "Chocolate sauce", "Amaretto", "Irish whiskey"]
priceArray = [0.89, 0.25, 0.59, 1.50, 1.75] #this array holds the add-in prices
loopFlag = "" #sentinal value for looping
cnt = 0
COFFEECOST = 2 #constant to coffee cost
addinName = ""
totalCost = 0
#input enter add-in name
addinName = input("Enter on Keyboard Coffee Add-in (ex. Whipped Cream, Cinnamon, etc.) or Done to quit")
while (addinName != "Done"): #loop until addinName is Done
while (cnt < len(addinArray)):
if (addinName == addinArray[cnt]) :
totalCost = priceArray[cnt] + totalCost
print("Add-in ", addinName, " with a price of ", priceArray[cnt])
print( "with a total add-in price so far of ", totalCost)
cnt = cnt + 1 #increment counter for next element in array
#end while
addinName = input("Enter on Keyboard Coffee Add-in (ex. Whipped Cream, Cinnamon, etc.) or Done to quit")
#end while
totalCost = totalCost + COFFEECOST
print("Total cost is: ", totalCost)
main()
#stop

I think that cnt = 0 should reset after the first loop:
while (addinName != "Done"): #loop until addinName is Done
cnt = 0
Without this, after the first add-on cnt can reach len(addinArray) and never second while loop is going to be executed for new add-on.

I ran your code locally and I found 2 things.
You need to reset the cnt variable to zero after the nested while loop, otherwise it won't get executed again since the condition cnd>5 will be always true.
The input() call seems to throw an error, so instead I tested raw_input() and seemed to work.
Hope this helps!

Related

How write User Input Data to External Text File?

I would like to be able to take the test scores the user inputs and write to an external text file. Then have the application read off the values from the and calculate the average. However, I am unsure as to how to implement the python syntax within the loop and the functions. I've attempted to utilize my resources to get a better idea of how to do this, but I've been having some trouble understanding how python handles external files. In addition, would using append be better than write in this scenario?
Current Syntax:
def testAvgCalculation():
#Variables
total = 0
total_quiz = 0
while True:
#User Input and Variable to stop loop
inpt = input("Enter score: ")
if inpt.lower()== 'stop':
break
#Data Validation
try:
if int(inpt) in range(1,101):
total += int(inpt)
total_quiz += 1
else:
print("Score too small or Big")
except ValueError:
print("Not a Number")
return total, total_quiz
def displayAverage(total, total_quiz):
average = total / total_quiz
print('The Average score is: ', format(average, '.2f'))
print('You have entered', total_quiz, 'scores')
#Main Function
def main():
total, total_quiz = testAvgCalculation()
displayAverage(total, total_quiz)
#Run Main Function
main()
This is hacky as heck, but I tried to work with what was already there. I split the data validation section of the original function off into a separate function. In main() it returns its value counter, which keeps track of how many values were entered, to calculate_average(), which then reads the file line by line until counter becomes 0, which means it's about to read the word "stop" (which allows EOF recognition via the 'and' in the if statement), performs the calculation and returns its values.
def write_file():
#Variables
counter = 0
file = open("Scores.txt", "w")
while True:
#User Input and Variable to stop loop
inpt = input("Enter score: ")
file.write(inpt + "\n")
if inpt.lower()== 'stop':
file.close()
break
counter += 1
return counter
def calculate_average(counter):
total = 0
total_quiz = counter
scores = open("Scores.txt", "r")
s = ""
try:
while counter > 0 and s != 'stop':
s = int(scores.readline())
if int(s) in range(1,101):
total += int(s)
counter -= 1
else:
print("Invalid data in file.")
except ValueError:
print("Invalid data found")
return total, total_quiz
def displayAverage(total, total_quiz):
average = total / total_quiz
print('The Average score is: ', format(average, '.2f'))
print('You have entered', total_quiz, 'scores')
#Main Function
def main():
total, total_quiz = calculate_average(write_file())
displayAverage(total, total_quiz)
#Run Main Function
main()
NOTE: the file is created initially in write mode which overwrites the file each time so you never need a new one. if you want to keep a record you might like to change it to append, though you'll need to manage extracting the proper lines from among old input.
Not pretty at all, but should give you an idea of how to accomplish what you were going for.

Variables not gaining value in subroutines

The total cost wont print or gain value. I've tried running the subroutines separately but that didn't work. It will not print totalcost at all:
#coffee maker program
print("Welcome to the BartSucks Coffee App")
print("We will guide you through the ordering process")
print("And our amazing Barista 'Simpson' will then serve you")
name = input("Please type in your name: ")
print("Would you like small, medium or large?")
size = input("Type s for small\nType m for medium\nType l for large\n")
while size.upper() not in ("S","M","L"):
print("You must enter s, m or l")
size = input("Please try again\n")
print("Would you like zero,one, two or three spoons of sugar?")
sugars = input("Type 0 for none\nType 1 for one\nType 2 for two\nType 3 for three\n")
while sugars not in ("0","1","2","3"):
print("You must enter 0, 1, 2 or 3")
sugars = input("Please try again\n")
print("Would you like no syrup flavouring?")
print ("Or would you like almond, vanilla or butterscotch syrup?")
flavour = input("n = none\na = almond\nv = vanilla\nb = butterscotch\n")
while flavour.upper() not in ("N","A","V","B"):
print("You must enter n, a, v or b")
flavour = input("Please try again\n")
totalcost=0
def CoffeeSize(cs):
cs=cs.upper()
global totalcost
if size =="S" or size=="s":
totalcost+= 2.5
elif size=="M" or size=="m":
totalcost+=3.0
elif size=="L" or size=="l":
totalcost+= 3.5
def SugarAmount(sa):
sa=sa.upper()
global totalcost
if sugars=="0":
totalcost+= 0
elif sugars=="1":
totalcost+= 0.5
elif sugars=="2":
totalcost+= 1.0
elif sugars=="3":
totalcost+= 1.5
def flavour(fl):
fl=fl.upper()
global totalcost
if flavour=="NONE" or flavour=="none":
totalcost+= 0
elif flavour=="BS" or flavour=="bs":
totalcost+= 1.6
elif flavour=="V" or flavour=="v":
totalcost+= 0.75
elif flavour=="A" or flavour=="a":
totalcost+= 1.0
CoffeeSize(cs)
SugarAmount(sa)
flavour(fl)
print(totalcost)
sorry im quite new to this so correct me if im wrong but i think the problem is that you are calling the functions inside a function which isnt being executed?
Also, everything apart from anything under 'if','def'... etc statements should be on the first indentation level
Your code:
totalcost=0
def flavour(fl):
...
...
CoffeeSize(cs)
SugarAmount(sa)
flavour(fl)
print(totalcost)
In Python, indentations are important and define under what statement it runs over.
As you can see, you are calling the functions on the same indentation level as the code underneath the function 'flavour', therefore it wont get executed as there isnt any other place that calls that function. Try and put this at the end of your program instead:
Code:
if __name__ == '__main__':
CoffeeSize(cs)
SugarAmount(sa)
flavour(fl)
print(totalcost)
What this does is checks to see if the program is the main program instead of being imported by something else. If it is the main/'_ main _' program, it will go from the start, ask the users what they want and then check to see if this program is the main one, then executes all the functions that are listed under the if statement.
Sorry if i misinterpreted your problem but i think that's what the problem is from my perspective :)
Thanks!

Python 3 Game Bug: Holding down the enter key

I have another question related to this game, here it is:
https://stackoverflow.com/questions/28545444/python-3-game-bug-message-repeating
I made a game thats a knock off of Cookie Clicker (just for coding practice!). And I ran into a problem where the user can hold down the enter key, and get coins really fast. I'd like to prevent that. here is my code:
coin = 0
keepgoing = True
while keepgoing == True:
print('You have ' + str(coin) + ' cmd-coins' )
response = input('Press enter to get a coin!')
if response == 'q':
keepgoing = False
print('Thanks for playing!')
coin = coin + 1
I wrote a rather "gimmicky" solution to your problem, which works to an extent but definitely isn't flawless. Based on your compiler you may have to change the conditional value for start-end such that it is a value which allows you to static press as fast as humanly possible without breaking but not allow the user to hold the enter key. For me in WingIde, 0.03 is the optimal value.
Were you to import a module such as Pygame you would find this sort of game much easier to make.
import time
coins = 0
keepgoing = True
end = -1
while keepgoing:
print('You have ' + str(coins) + ' cmd-coins' )
response = input('Press enter to get a coin!')
start = time.time()
if start-end < 0.03:
print ("Don't hold down the Enter key you cheater!")
keepgoing = False
if response == 'q':
print('Thanks for Playing!')
keepgoing = False
coins = coins + 1
end = time.time()
NOTE: This solution is for Python 3, for < Python 3 you'll have to substitute raw_input() for input(). Also, I wouldn't advise trying to use it on an online compiler.
G Force dog,
You could change your game a bit by making a few changes till someone or I figure out a good solution(Mom gave orders to go to bed). Till we don't find a solution, use this code which isn't exactly a solution.
coins = 0
real = 0
while real == 0:
if True:
print('You have ' + str(coins) + ' cmd-coins' )
response = input('Press c to get a coin, then press ENTER!')
if response == 'c' or response == 'C':
coins = coins + 1
if response == 'q':
print('Thanks for playing!')
real = 1
And 2 things:-
Nice answer Yeniaul! Good try!
Elizion, nice try but your method isn't working. But it is a good idea.
I have used time too, but it seems that when one presses ENTER key for a long time, it just comes out on the screen all together.
I think I do have somewhat of an idea forming... if we make another while loop, after importing 'time', with a condition which makes the loop active every 2 seconds by assigning a variable 'time.clock()' and when its value is a multiple of 2, it activates!
Got it? I know what to do, but can't seem to put it in code. See if you can, reader(especially Elizion and Yeniaul)
Try using time.sleep(seconds of delay) for slowdown
So you could do
coin = 0
keepgoing = True
while keepgoing == True:
time.sleep(0.25)
print('You have ' + str(coin) + ' cmd-coins' )
response = input('Press enter to get a coin!')
if response == 'q':
keepgoing = False
print('Thanks for playing!')
coin = coin + 1
This would make it a quarter-second delay before they could get another coin.

How can I modify this code so it doesn't go back to the beginning of the function, but a little bit after the beginning?

I'm working on a school project and I have a problem. I have to write code for apothecary where clients can buy medicine. So, I need to make restrictions, which one doesn't go with others and etc. Here is the code:
def prodajLek():
lekovi = Fajl1.UcitavanjeLekova()
lekoviRed = []
brojacZaForPetlju = 1
n = 0
cena = 0
kolicina = []
korpa = []
rednibrojevilekova = []
ukupnacena = 0
print(" Fabricki naziv Genericki naziv Serijski broj Kolicina Cena \n")
for i in lekovi:
x = i.strip().split("|")
lekoviRed.append(x)
if lekoviRed[n][5] == "False":
print(brojacZaForPetlju,"\t {:10} \t {:10} \t\t\t {:3} \t\t\t {:4} \t\t {:5}".format(x[0],x[1],x[2],x[3],x[4]))
brojacZaForPetlju = brojacZaForPetlju + 1
n = n + 1
print("\n\n\n\n")
rednibrleka = input("Izaberite redni broj leka koji zelite da prodate:\n>>\t")
rednibrleka = int(rednibrleka)
rednibrleka = rednibrleka - 1
rednibrojevilekova.append(rednibrleka)
kolicinaZahteva = input("Koju kolicinu zelite da prodate?\n>>\t")
kolicinaZahteva = int(kolicinaZahteva)
if kolicinaZahteva > int(lekoviRed[rednibrleka][3]):
print("Nema toliko na lageru!\n")
Fajl1.LekarMenu()
kolicina.append(kolicinaZahteva)
cena = int(lekoviRed[rednibrleka][4])
korpa.append(cena)
print("Da li zelite da kupite jos lekova?\n1.Da\n2.Ne\n")
nastavakKupovine = input(">>")
if nastavakKupovine == "1":
prodajLek()
elif nastavakKupovine == "2":
Fajl1.LekarMenu()
So, when I get to the nastavakKupovine input, when I press 1, I need to continue shopping and store my row numbers, my price and quantity in arrays rednibrojlekova = [] , korpa = [] and kolicina = []. But I have a problem, because I dont know how to continue this without reseting these arrays to empty.
The standard idiom for what you want to do is a while True loop. Rather than show how to change your (rather long) function, here's a very simple one which hopefully shows the principle in a straightforward way:
def ask():
answers = []
while True:
response = input("What do you have to say? ")
answers.append(response)
check = input("Type 'q' to quit, anything else to repeat: ")
if check == "q":
break
else:
continue
return answers
For this simple function, the else: continue part isn't necessary, because the loop will continue anyway, but I've included it so you can see how to use it.
Here's an example of the function in action:
>>> ask()
What do you have to say? Something
Type 'q' to quit, anything else to repeat:
What do you have to say? Another thing
Type 'q' to quit, anything else to repeat:
What do you have to say? Ok, done
Type 'q' to quit, anything else to repeat: q
['Something', 'Another thing', 'Ok, done']
>>>
You can find out more about while, break and continue by reading the More Control Flow Tools chapter of the official Python tutorial.

Python custom modules - error with example code

I am reading the book "Python Programming for the Absolute Beginner (3rd edition)". I am in the chapter introducing custom modules and I believe this may be an error in the coding in the book, because I have checked it 5 or 6 times and matched it exactly.
First we have a custom module games.py
class Player(object):
""" A player for a game. """
def __init__(self, name, score = 0):
self.name = name
self.score = score
def __str__(self):
rep = self.name + ":\t" + str(self.score)
return rep
def ask_yes_no(question):
""" Ask a yes or no question. """
response = None
while response not in ("y", "n"):
response = input(question).lower()
return response
def ask_number(question, low, high):
""" Ask for a number within a range """
response = None
while response not in range (low, high):
response = int(input(question))
return response
if __name__ == "__main__":
print("You ran this module directly (and did not 'import' it).")
input("\n\nPress the enter key to exit.")
And now the SimpleGame.py
import games, random
print("Welcome to the world's simplest game!\n")
again = None
while again != "n":
players = []
num = games.ask_number(question = "How many players? (2 - 5): ", low = 2, high = 5)
for i in range(num):
name = input("Player name: ")
score = random.randrange(100) + 1
player = games.Player(name, score)
players.append(player)
print("\nHere are the game results:")
for player in players:
print(player)
again = games.ask_yes_no("\nDo you want to play again? (y/n): ")
input("\n\nPress the enter key to exit.")
So this is exactly how the code appears in the book. When I run the program I get the error IndentationError at for i in range(num):. I expected this would happen so I changed it and removed 1 tab or 4 spaces in front of each line from for i in range(num) to again = games.ask_yes_no("\nDo you want to play again? (y/n): ").
After this the output is "Welcome to the world's simplest game!" and that's it.
I was wondering if someone could let me know why this is happening?
Also, the import games module, is recognized in Eclipse after I added the path to PYTHONPATH.
I actually have this book myself. And yes, it is a typo. Here is how to fix it:
# SimpleGame.py
import games, random
print("Welcome to the world's simplest game!\n")
again = None
while again != "n":
players = []
num = games.ask_number(question = "How many players? (2 - 5): ", low = 2, high = 5)
for i in range(num):
name = input("Player name: ")
score = random.randrange(100) + 1
player = games.Player(name, score)
players.append(player)
print("\nHere are the game results:")
for player in players:
print(player)
again = games.ask_yes_no("\nDo you want to play again? (y/n): ")
input("\n\nPress the enter key to exit.")
All I did was indent num 4 spaces and lined it up with the first for-loop.
You have an infinite loop here:
again = None
while again != "n":
players = []
If this is exactly the way it's printed in the book, the book does have an error.
You've got these two lines:
num = games.ask_number(question = "How many players? (2 - 5): ", low = 2, high = 5)
for i in range(num):
The second one is more indented than the first. That's only legal if the first one is a block-introducer like a for or while or if. Since it's not, this is an IndentationError. And that's exactly what Python is telling you.
(It's possible that you've copied things wrong. It's also possible that you're mixing tabs and spaces, so it actually looks right in your editor, but it looks wrong to Python. But if neither of those is true, the book is wrong.)
So, you attempted to fix it by dedenting everything from that for loop on.
But when you do that, only one line is still left under the while loop:
while again != "n":
players = []
There's nothing that can possibly change again to "n", so this will just spin forever, doing nothing, and not moving on to the rest of the program.
So, what you probably want to do is to indent the num = … line to the same level as the for i… line, so both of them (and all the stuff after) ends up inside the while loop.

Categories