can't add everything together? (stuck on the last code) - python-2.7

*ignore this part, just look at the last few codes. im trying to add all the quanties together but the last code prints every purchase individually? How can i get it to print "Your purchases is" and add the quanties times their price all in one line instead of printing it for every individual
print "Enter a fruit name (or done):",
fruit = raw_input()
fruit_list = []
while fruit != "done":
fruit_list = fruit_list + [fruit]
print "Enter a fruit name (or done):",
fruit = raw_input()
price_list = []
for x in range(0, len(fruit_list)):
print "Enter the price for " + fruit_list[x] + ":",
price = float(raw_input())
price_list = price_list + [price]
# print " Your fruit list is:" + str(fruit_list)
# print "Your price list is:" + str(price_list)
print fruit_list
print price_list
quanity_list = []
for x in range(0, len(fruit_list)):
print str(fruit_list[x]) + str(price_list[x]) + " Quantity:",
quantity = int(raw_input())
print "Your total purchase is:", + price_list[x] * quantity

Try the following code :
Replace your last part of code with;
total = 0
quanity_list = []
for x in range(0, len(fruit_list)):
print str(fruit_list[x]) + str(price_list[x]) + " Quantity:",
quantity = int(raw_input())
total = total + price_list[x] * quantity
print "Your total purchase is:" + total

Related

How do I get my code to repeat itself if the desired input is not entered?

I just started python 2 weeks ago and I don't know how to make my code repeat itself when the input is something like "fox" when that is not one of the three options I'm accepting (horse, oxen, mule). Also if I want to total up the cost of 2 horse and say 3 mules by having it ask "do you want to buy any more animals", how would i do that? Any help would be very appreciated.
zoo = {}
def main():
print ("Animals available to purchase: " + "horse: 50, oxen: 35, mule: 20")
total_money = 1000
print ("You have " + str(total_money) + " to spend")
cost(total_money)
def animal_cost(total_money):
animal_type = raw_input("Please enter an animal:")
print ("Animal Type Entered: " + str(animal_type))
global animal_quantity
animal_quantity = int(raw_input("Please enter quantity of animals:"))
print ("Animal Quantity Entered: " + str(animal_quantity))
if animal_type in zoo:
zoo[animal_type] += animal_quantity
else: zoo[animal_type] = animal_quantity
while True:
if animal_type == 'horse':
return 50 * animal_quantity
if animal_type == 'oxen':
return 35 * animal_quantity
if animal_type == 'mule':
return 20 * animal_quantity
else:
cost(total_money)
def cost(total_money):
costing = animal_cost(total_money)
total_money -= costing
if total_money <= 0:
print ("No money left, resetting money to 1000.")
total_money = 1000
zoo.clear()
print ("Cost of Animals: " + str(costing))
print ("Remaining Balance:" + str(total_money))
choice = raw_input("Do you want to buy any more animals?(Y/N):")
if choice in('Y','y'):
cost(total_money)
elif choice in ('N','n'):
choice_2 = raw_input("Enter 'zoo' to see the animals you have purchased:")
if choice_2 in('zoo','Zoo'):
print zoo
choice_3 = raw_input("is everything correct?(Y/N):")
if choice_3 in ('Y','y'):
print ("Thank you for shopping!")
elif choice in ('N','n'):
print ("Restarting Transaction")
zoo.clear()
cost(total_money)
if __name__ == '__main__':
main()
You may try this enhanced version of your code:
zoo = {} # creating global dictionary for adding all animals into it.
# function to get animal cost
def animal_cost(total_money):
animal_type = raw_input("Please enter an animal:")
print ("Animal Type Entered: " + str(animal_type))
animal_quantity = int(raw_input("Please enter quantity of animals:"))
print ("Animal Quantity Entered: " + str(animal_quantity))
if animal_type in zoo:
zoo[animal_type] += animal_quantity
else: zoo[animal_type] = animal_quantity
if animal_type == 'horse':
return 50 * animal_quantity
if animal_type == 'oxen':
return 35 * animal_quantity
if animal_type == 'mule':
return 20 * animal_quantity
# getting total_money after animal purchase
def cost(total_money):
costing = animal_cost(total_money)
total_money = total_money - costing
if total_money <=0: # condition when money is less than or equal to 0.
print("No Money left, resetting money to 1000.")
total_money = 1000
print ("Cost of Animals:" + str(costing))
print ("Total Money Left:" + str(total_money))
# Recursion for buying more animals:
choice = raw_input("Do you want to buy any more animals?:")
if choice in ('Yes','y','Y','yes','YES'):
cost(total_money)
# you can use this commented elif condition if you want.
else: # elif choice in('no','No','n','N','NO'):
print("thankyou!!")
print("You have total animals: "+str(zoo))
# main function to initiate program
def main():
print ("Animals available to purchase: " + "horse, oxen, mule")
total_money = 1000
print ("You have " + str(total_money) + " to spend")
cost(total_money)
if __name__ == '__main__':
main()
This might help you out.
Have a look into this for last two lines

IndexError: Python list index out of range

I have an empty list, (r) and declared first element as r[0] = a
import time, urllib.request,random
def getDictionary():
word_site = "http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain"
response = urllib.request.urlopen(word_site)
txt = response.read()
return txt.splitlines()
def getWordsList(listOfWords, sample):
word = ""
randWords = []
for i in range(0,sample):
while(len(word) <=2):
word = random.choice(listOfWords).decode('utf-8')
randWords.append(word)
word = ""
return randWords
start = True
noOfWords = 25
words = getDictionary()
wordsList = getWordsList(words, noOfWords)
start = True
print ("\nINSTRUCTIONS\nWhen the coundown gets to zero, type the word in lowercase letters!\n That's the only rule!")
name = input("What is your name? ")
name = name.split(" ")
input("Press enter when ready...")
while start == True:
print("Game will start in: ")
print ("3 seconds")
time.sleep(1)
print ("2 seconds")
time.sleep(1)
print ("1 seconds")
time.sleep(1)
times = []
k = list()
r = list()
for i in range(25):
startTime = time.time()
userWord = input(str(i+1) + ". " + wordsList[i].capitalize() + " " )
k.append(wordsList[i].capitalize())
if (userWord.lower() == wordsList[i].lower()):
endTime = time.time()
times.append(endTime - startTime)
r[i] = str(endTime - startTime)
else:
times.append("Wrong Word")
r[i] = ("Wrong Word")
Above is where I am having a problem.
for i in range(25):
startTime = time.time()
print (str(i+1) + ". " + str(k[i]) + ": " + str(times[i]) )
a = 0
for i in range(25):
a = a+i
for i in range(25):
if r[i] == "Wrong Word":
r = r.pop(i)
b = (a/len(r))
c = round(b, 2)
print (c)
start = False
here is my error:
r[i] = "Wrong Word"
IndexError: list assignment index out of range
The pop() method removes an element from the list and returnes it (see an example). What I think is happening is that at some point the condition of the if statment resolves to true. Next, after calling r.pop(i) r is replaced by its i-th element. It's probpably a string so calling its (i+1)-th element later can result in Index out of range error.
In other words, something like this is happening:
r = ["a", "foo", "bar", "baz"]
for i in range(4):
if r[i] == "a": # for i=0 this gives "a" == "a"
r = r.pop(i) # later,this results in r = "a"
next loop iteration with i = 1 will result in "a"[1] which will result in Index out of range.
All in all instead of:
for i in range(25):
if r[i] == "Wrong Word":
r = r.pop(i)
you could just write:
r = [item for item in r if item != "Wrong word"]
which would be also more pythonic solution.

How to avoid duplicate printing of random choiced names from list ( Python)

This program prints duplicate names generated from list please help me get rid of it I added a operator fr it but it's not working
#Subscriber Selector
import random
print "Welcome to Subscriber Picker"
sub_list = ["Ali Abbas","Ansar Abbasi","Hasan Abidi","Saadia Afzaal","Iqbal Ahmad","Iftikhar Ahmad","Khaled Ahmed","Ahmed Tamim","Maulana Mahboob Alam","Malik Barkat Ali"]
def add_list():
input_1 = int(raw_input("How many new users do you want to add? "))
for z in range (0,input_1):
sub_list.append(raw_input ("Enter Name" +" "+ str(z+1) + ":"))
return
add_list()
def generator():
input_2=int(raw_input("How many subscribers to generate? "))
print "-----"
index=0
temp_list = []
ran_name = random.randint(0, len(sub_list)-1)
temp_list.append(sub_list[ran_name])
while len(temp_list) < input_2:
ran_name=random.randint(0,len(sub_list)-1)
temp_list.append(sub_list[ran_name])
if(temp_list[index] == temp_list[index+1]):
temp_list.pop(index)
else:
index = index + 1
for x in temp_list:
print x
print"-----"
return
generator()
Here you go:
temp_list = random.sample( sub_list, input_2 )

Python 2.7 for loop confusion

I'm trying to build a table from user input to export via Cheetah to fill a template to use as a report. I'm having trouble separating each iteration of the loop
"for j in range(1, numErrors):" and put table row tags at the beginning and end of each concatenation.
table = ""
cells = ""
row = ""
numMeas = int(raw_input("Enter total number of measurements: "))
numMeas = numMeas + 1 #number of measurements compensated for iteration behavior
for i in range(1, numMeas):
typeMeas = raw_input("Enter type of measurement "+str(i)+": ")
numErrors = int(raw_input("Enter number of error sources: "))
numErrors = numErrors + 1
for j in range(1, numErrors): #builds dataSet from number of errors
inputData = []
inputData.append(typeMeas)
description = raw_input("Enter source of uncertainty "+str(j)+": ")
inputData.append(description)
estUncert = raw_input("Enter estimated uncertainty "+str(j)+": ")
estUncert = float(estUncert)
inputData.append(str(estUncert))
for i in inputData:
cell = "<td>"+str(i)+"</td>"
cells += cell
table = "<tr>"+cells+"</tr>"+"\n"
print table
Current output:
<tr><td>mass</td><td>scale</td><td>1.0</td><td>mass</td><td>human</td><td>2.0</td> <td>temp</td><td>room</td><td>3.0</td><td>temp</td><td>therm</td><td>4.0</td></tr>
Desired output:
<tr><td>mass</td><td>scale</td><td>1.0</td></tr>
<tr><td>mass</td><td>human</td><td>2.0</td></tr>
<tr><td>temp</td><td>room</td><td>3.0</td></tr>
<tr><td>temp</td><td>therm</td><td>4.0</td></tr>
I am guessing it probably needs to look like this:
table = ""
cells = ""
row = ""
numMeas = int(raw_input("Enter total number of measurements: "))
numMeas = numMeas + 1 #number of measurements compensated for iteration behavior
for i in range(1, numMeas):
typeMeas = raw_input("Enter type of measurement "+str(i)+": ")
numErrors = int(raw_input("Enter number of error sources: "))
numErrors = numErrors + 1
inputData = []
for j in range(1, numErrors): #builds dataSet from number of errors
inputData.append(typeMeas)
description = raw_input("Enter source of uncertainty "+str(j)+": ")
inputData.append(description)
estUncert = raw_input("Enter estimated uncertainty "+str(j)+": ")
estUncert = float(estUncert)
inputData.append(str(estUncert))
cells = ''
for i in inputData:
cell = "<td>"+str(i)+"</td>"
cells += cell
table += "<tr>"+cells+"</tr>"+"\n"
print table

Random walk code in python [2 dimensions]

Please could you help me by figuring out what is the wrong with my code.
I am trying to write a program that generates random walks in two dimensions and that determines statistics about the position of the walker after 500 steps when the number of walks is 1000, the max step size is 0.9, and the separation between the two positions is 0.001.
import math
import random
import time
print "RANDOM WALKS ANALYSIS IN ONE DIMENSION"
NOFW_ = 1000 #The number of walks
NOFS_= 500 #The number of steps in each walk
MSS_ = 0.9 # The maximum step size[m]
SOFP_ = 0.001 # The separation of positions considered equal[m]
print " Number of walks: %3g"% NOFW_
print " Number of steps in each Walk: %3g"% NOFS_
print " Maximum step size: %3g"% MSS_,"m"
print "Separation of positions considered equal: %3g"% SOFP_,"m"
print
print "Please wait while random walks are generated and analyzed..."
print "Date:" + time.ctime()
print
def initialPosition():
return (0.0, 0.0)
def distance(posA, posB):
"""Calculates the distance between two positions posA and posB"""
distance = math.sqrt((posB[0] - posA[0])**2 + (posB[1] - posA[1])**2)
return distance
def printstats(description, numbers):
minimum_value_ = min(numbers)
numbers.sort()
Tenth_percentile = abs(0.10*len(numbers) + 0.5)
Mean_value_ = (1./float(len(numbers))*sum(numbers))
A = 0
for values in numbers:
B = distance(values, Mean_value_)
B = B**2
A = B + A
Standard_deviation = math.sqrt((1./(len(numbers)-1))*A)
Newposition_ = int(0.90*(len(numbers) + 0.5))
Ninetieth_percentile =numbers[Newposition_]
maximum_value_ = max(numbers)
print "Analysis for"""+ description
print "Minimum value: %9.1f" % minimum_value_
print "10th percentile: %7.1f" % Tenth_percentile
print "Mean value: %12.1f" % Mean_value_
print "Standard deviation: %4.1f" % Standard_deviation
print "90th percentile: %7.1f" % Ninetieth_percentile
print "Maximum value: %9.1f" % maximum_value_
list_1 = [minimum_value_, Tenth_percentile, Mean_value_, Standard_deviation, Ninetieth_percentile,maximum_value_]
return list_1
def takeStep(prevPosition, maxStep):
x = random.random()
y = random.random()
minStep = -maxStep
Z = random.random()*2*math.pi
stepsize_ = random.random()*0.9
Stepx= stepsize_*math.cos(Z)
Stepy= stepsize_*math.sin(Z)
New_positionx = prevPosition[0] + Stepx
New_positiony = prevPosition[1] + Stepy
return (New_positionx, New_positiony)
Step_100 = []
Step_500 = []
count_list = []
for walk in range(NOFW_):
Step1 = []
Position = (0.0,0.0)
count = 0
for step in range(NOFS_):
Next_Step_ = takeStep(Position, MSS_)
for word in Step1:
if distance(Next_Step_, word) <= SOFP_:
count +=1
position = Next_Step_
Step1.append(Next_Step_)
Step_100.append(Step1[-1])
Step_500.append(Step1[-1])
count_list.append(count)
Step_100 = printstats("distance from start at step 100 [m]", Step_100)
Step_500 = printstats("distance from start at step 500 [m]", Step_500)
count_list = printstats("times position revisited", count_list)
Your problem is here
Mean_value_ = (1./float(len(numbers))*sum(numbers))
sum() is supposed to get some numbers but your variable numbers is actually containing some tuples of 2 values
You may want to define your own sum function for tuples of 2 numbers, or to sum the first values and second values separately