Debugging a simple Python price code - python

I have this code in Python
def receipt(array):
sum = 0.0
for i in range(len(array)):
sum = sum + array[i]
return sum
array = []
while True:
print("Calculating Price")
n = input("Enter a price: ")
if n == "":
print("Goodbye")
break
array.append(n)
totalCost = receipt(n)
print("The total cost is " + str(totalCost))
And I'm wondering why this code won't work. There seems to be some error in the fourth line
sum = sum + array[i]
But I can't figure out which part of it is wrong. I believe I used the array[i] component correctly. Perhaps it's a string issue?
Question:
Which part of the code doesn't work?
What is my error?
I'm relatively new to computer science in general. Thanks for the help. Anything is appreciated!

I ran your code and got this error:
$ python test.py
Calculating Price
Enter a price: 24
Traceback (most recent call last):
File "test.py", line 14, in <module>
totalCost = receipt(n)
File "test.py", line 4, in receipt
sum = sum + array[i]
TypeError: unsupported operand type(s) for +: 'float' and 'str'
This means that in your sum = sum + array[i] line, the types don't match up. You need to wrap array[i] in a float() function to match array[i] to the type of sum, which is a float since you initialized it to 0.0. The docs say the input() function returns a string, and since you're appending n to array, you are trying to sum a string with a float. The line should look like this:
sum = sum + float(array[i])
Try running it again and the code works. Here is the documentation for input()
Edit: now to fix the issues were were having with the sum.
Here is a version of your code I have revised with corrections to do the addition the way you want.
1 def receipt(sumvar, n):
2 sumvar = sumvar + float(n)
3 return sumvar
4
5 array = []
6 sumvar = 0.0
7
8 while True:
9 print("Calculating Price")
10 n = input("Enter a price: ")
11 if n == "":
12 print("Goodbye")
13 break
14 totalCost = receipt(sumvar, n)
15 sumvar = totalCost
16 print("The total cost is " + str(totalCost))
As mentioned by others, sum isn't a great variable name so I've renamed it sumvar. Notice the sumvar declaration that is outside the function. When you initialize sumvar inside receipt() like you did, you will always be adding n to 0.0. I doubt this is what you want. Instead, you want to keep a running total of the item count, which needs to be passed into the function. I've also eliminated the loop from your function. This loop was actually iterating over the characters in array, not the elements as you expected it to.

First of there are several things wrong. I will explain each and everything.
Here is your complete working code:
def receipt(array):
total = 0.0
for i in array:
total = total + i
return total
array = []
while True:
print("Calculating Price")
n = input("Enter a price: ")
if n=="":
print("Goodbye")
break
array.append(float(n))
totalCost = receipt(array)
print("The total cost is " + str(totalCost))
Your Mistakes:
1)array.append(n) - First one. Pretty common for beginner.
input() in python gets user input as string. So your n is a String.
See there are data types in all languages. And Python is a Strongly typed language while perl is not. How to say if a language is strongly typed or weakly typed ? Simple. Try this in your interpreter.
>>> a=5
>>> b='9'
>>> a+b
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
a+b
TypeError: unsupported operand type(s) for +: 'int' and 'str'
See the error now try this,
>>> a=5
>>> b='9'
>>> a+int(b)
14
Works perfectly fine right. Python doesn't allow just a+b while some languages do example perl. Read more about it. So you can't add them you have to typecast. So change that into
array.append(int(n))
or
array.append(float(n))
If you are going to work with float values.
2) totalCost = receipt(n) See you are passing n to the function. But your function definition has def receipt(array):. What actually happens here is
receipt(n) ----> (calls) ---->def receipt(array):
Where n ------> array So your array is nothing but n. What you should do intead is
totalCost = receipt(array)
3) sum = 0.0 NEVER I said never use built-in or keyword names (ex ample : sum,min,max,int,str etc) as variable names. Read more about naming in PEP 8
So maybe rename sum to sum_ (it's the convention to be followed) However why can't you just rename sum to total much simpler right?
4) And finally
for i in range(len(array)):
sum = sum + array[i]
Why range(len(array)) when you can simply do for i in array:
Can't understand this take a look at this example:
>>> a = [1,2,3]
>>> for i in a:
print(i)
1
2
3
See for item in something would just take each and every item from a group of something ( iterable (list,tuple,set etc..))
So just change those lines to
for i in array:
total = total + i
And voila you got what you wanted,
Output:
Calculating Price
Enter a price: 10
The total cost is 10.0
Calculating Price
Enter a price: 20
The total cost is 30.0
Calculating Price
Enter a price: 15
The total cost is 45.0
Calculating Price
Enter a price:
Goodbye
UPDATE:
As mentioned in comments you need to learn more about indentation. Check out the link in the comments.

You have some problems, I will comment one by one:
First, you had some indentation problems, be careful with that.
The rest are comments in the code
update
def receipt(array):
sum = 0.0
for i in range(len(array)):
sum = sum + array[i]
return sum
array = []
while True:
print("Calculating Price")
n = input("Enter a price: ") #If you convert the str into float here it will cause an error in the if
if n == "": #here, when you hit enter, it sends the "" (empty string)
print("Goodbye")
break
array.append(float(n)) #So an option is transform the string here
totalCost = receipt(array) #and here, you gave to receipt() function the wrong param, you gave "n" and it was waiting for an array
print("The total cost is " + str(totalCost))

You shouldn't use sum as a variable, since it's a built-in in Python, besides, convert your array[i] to a float type when adding it to another float, also notice you never use your initialized array, you are missing that when calculating totalCost:
def receipt(array):
summ = 0.0
for i in range(len(array)):
summ = summ + float(array[i])
return summ
array = []
while True:
print("Calculating Price")
n = input("Enter a price: ")
if n == "":
print("Goodbye")
break
array.append(n)
totalCost = receipt(array)
print("The total cost is " + str(totalCost))

I have corrected what is causing your issue, you are in fact passing in 'n' into receipt instead of 'array'.
def receipt(array):
sum = 0.0
for i in range(len(array)):
sum = sum + array[i]
return sum
array = []
while True:
print('Calculating Price')
n = input("Enter a price: ")
if n == "":
print("Goodbye")
break
array.append(n)
totalCost = receipt(array) #receipt takes a list as a parameter (what you call array)
print("The total cost is " + str(totalCost))
Additional issues are:
indentation (I suspect that was just copy paste)
input will also give you errors the way you are using it, take a look at this to solve that issue
Consider also making your loop based on the value of n as while true is generally unsafe
or at least changing your if statement to be 'not n' as point out here is more pythonic. Also in the future make sure to note the version of python you are using.

Dont use sum as a variable name, it is a Python built-in.
Fixed:
def receipt(array):
total = 0.00 # avoiding 'sum'
for price in array:
total += float(price) # equivalent to 'total = total + float(price)'
return total
array = []
print ("Calculating Price...") # outside 'while' to not reprint each time!
while True:
price = input("Enter a price: ")
if not price: # equivalent to 'if price is False, or 0 in CompSci speak
print ("Goodbye!")
break
array.append(price)
total = receipt(array)
print("The current total cost is", total) # no need to convert to str()
Some words of advice:
When writing a function, its better to be explicit rather than
implicit. So use variables that make sense!
We can use the same variable names because Python uses the LEBG
rule
for variable scope.
When calculating a price (which we know usually ends in 2 decimals)
its better to use integers rather than floats as you will run into
the [problem](
Limiting floats to two decimal points)
with floating point numbers.

Related

Using a function calculate and display the average of all numbers from 1 to the number entered by the user in python

I am gitting stuck here, please help. The code has to promt the user to enter a number, pass the number to a python function and let the function calculate the average of all the numbers from 1 to the number entered by the user.
def SumAverage(n):
sum=0
for idx in range(1,n+1):
average =sum/idx
return average
num =int(input("Enter a number"))
result=SumAverage(num)
print("The average of all numbers from 1 to {} is {}".format(num,result))
The sum of the series 1 + 2 + 3 + ... + n where n is the user inputted number is:
n(n+1)/2 (see wikipedia.org/wiki/1+2+3+4+...)
We have that the average of a set S with n elements is the sum of the elements divided by n. This gives (n(n+1)/2)/n, which simplifies to (n+1)/2.
So the implementation of the average for your application is:
def sum_average(n):
return (n + 1) / 2
This has the added benefit of being O(1).
Your version is not working because the average is always set to the last calculation from the for loop. You should be adding the idx for each iteration and then doing the division after the loop has completed. However, all of that is a waste of time because there is already a function that can do this for you.
Use mean from the statistics module.
from statistics import mean
num = int(input("Enter a number"))
result = mean(list(range(1, num+1)))
print(f'The average of all numbers from 1 to {num} is {result}')
If you are determined to do the logic yourself it would be done as below, if we stick with your intended method. #zr0gravity7 has posted a better method.
def SumAverage(n):
sum=0
for i in range(1,n+1):
sum += i
return round(sum / n, 2)
num = int(input("Enter a number"))
result = SumAverage(num)
print(f'The average of all numbers from 1 to {num} is {result}')
I'm not recommending this, but it might be fun to note that if we abuse a walrus (:=), you can do everything except the final print in one line.
from statistics import mean
result = mean(list(range(1, (num := int(input("Enter a number: ")))+1)))
print(f'The average of all numbers from 1 to {num} is {result}')
I went ahead and wrote a longer version than it needs to be, and used some list comprehension that would slow it down only to give some more visibility in what is going on in the logic.
def SumAverage(n):
sum=0
l = [] # initialize an empty list to fill
n = abs(n) # incase someone enters a negative
# lets fill that list
while n >= 1:
l.append(n)
print('added {} to the list'.format(n), 'list is now: ', l)
n = n - 1 # don't forget to subtract 1 or the loop will never end!
# because its enumerate, I like to use both idx and n to indicate that there is an index and a value 'n' at that index
for idx, n in enumerate(l):
sum = sum + n
# printing it so you can see what is going on here
print('length of list: ', len(l))
print('sum: ', sum)
return sum/len(l)
num =int(input("Enter a number: "))
result=SumAverage(num)
print("The average of all numbers from 1 to {} is {}".format(num,result))
Try this:
def SumAverage(n):
sum=0
for i in range(1,n+1):
sum += i
average = sum/n
return average
[its the better plz see this.
(short description):- user enter the list through functions then that list is converted into int. And the average is calculated all is done through functions thanx
]1

Practice Makes Perfect factorial

I am new to Python and I am taking Codecademy lessons required by my teacher. The instructions read, Define a function factorial that takes an integer x as input.
Calculate and return the factorial of that number.
For my code, I put,
def factorial(x):
if x == 1:
return factorial('n' - 1)
When I clicked save and submit code, it gave me this error message,
unsupported operand type(s) for -: 'str' and 'int'
I tried looking at the codecademy Q and A forum, but I didn't find anything feasible. I even went on this site and looked up what the error message meant. I looked at the hint provided by codecademy and it just made me more confused! Please help. Any feedback/ advice is always helpful. Thanks!
You are trying to subtract the number 1 from the letter n. Instead you should subtract 1 from the number you were given.
As far as I can tell, you are trying to make a factorial function using recursion. Your code has a few problems:
def factorial(x):
if x == 1:
return factorial('n' - 1)
First of all, on line 3 you are trying to subtract 'n' (a String) from 1 (an Integer). Remove the quotes to fix this.
Secondly, (if my previous statement was correct) your function takes input as x, not n. You are probably trying to do:
def factorial(x):
if x == 1:
return factorial(x - 1)
You are passing a string 'n' in to your factorial method. There are two problems with this:
1) You cannot perform a subtraction operation by trying to do 'n' - 1 (string type - int type).
2) You most likely meant to pass x instead of 'n'.
Next, your recursive algorithm for checking a factorial is incorrect.
You need to take the number, multiplied by the return of calling the factorial method again, but passing the number subtracted by 1. But then you need your "exit" condition, which is when the number reaches a value below 1:
def factorial(x):
if x < 1:
return 1
else:
return x * factorial(x - 1)
The error shows that you are trying to manipulate two things of different types, integer and string. Ans also it seems that your function "factorial" will only work if you give it an integer number 1. You can simply do this with while loop; (keep in mind the TYPES of things you want to manipulate).
def factorial(x):
n=1
total = x
last_int = x
while n < total:
x = x * (last_int-1)
n += 1
last_int -= 1
return x
if __name__ == "__main__":
while 1:
number = raw_input("enter number: ")
result = factorial(int(number))
print 'factorial number for ' + str(number) + ' is ' + str(result)
There's also another way to fix the task. You can use range with a negative step -1 and multiply from x to 1:
def factorial (x):
total = 1
if x < 1:
return total
else:
for i in range(x, 0, -1):
total *= i
return total

Why isn't my program showing the correct results?

My program is designed to let the user type in temperatures for a whole month. Then I've created functions that are supposed to let the user know a certain temperature for a day by typing in a requested date to see waht temperature he/she typed in for that day. Then there's funktions written to show an average temoerature, the lowest and the highest temperature (by finding these values from a list, where the user typed in the temperatures).
The programming isn't working that well, it answers the user without crashing but it doesn't show the right results. It "skips" to show the requested date, and prints out the whole list when the user asks for highest/lowest temperatures. When I try to get the average value, it crashes with the messange:
Traceback (most recent call last):
File "C:\Users\Linnea\Documents\Studier\HT 2014\Introduktion till programmering\Linnea_Andersson.py", line 58, in <module>
main ()
File "C:\Users\Linnea\Documents\Studier\HT 2014\Introduktion till programmering\Linnea_Andersson.py", line 9, in main
functions(temp_list)
File "C:\Users\Linnea\Documents\Studier\HT 2014\Introduktion till programmering\Linnea_Andersson.py", line 53, in functions
print("Average temperature was: " + str(sum(temp_list)/float(len(temp_list), str(round(total,2)))))
TypeError: unsupported operand type(s) for +: 'int' and 'list'
This is my code:
def main ():
temp_list = create_temp_list()
search()
functions(temp_list)
def create_temp_list ():
NUM_DAYS = 31
temp_list = [];
temperatur = [0] * NUM_DAYS
index = 0
print("Hi! Type in a temperature for each day in december!: ")
while index < NUM_DAYS:
print(index + 1, "/12", ": ", sep="", end="")
temperatur[index] = float(input())
index +=1
temp_list.append(temperatur)
return temp_list
def search():
temp_list = [1-31]
index = int(input("Vänligen skriv in en dag då du vill se temperaturen för: "))
while (index >= 1 and index < len(temp_list)):
print("The temperature this day was : ",(temp_list([index - 1])))
else:
print ("Ok")
x = [1,2,3]
try:
x[10]
except IndexError:
print("What are you trying to pull?")
def functions(temp_list):
svar1 =(input("To see the highest value, print 'ja': "))
if svar1 == "ja":
print("The highest temperature was: ", str(max(temp_list)))
else:
print ("This date wasn't found! You are now going to the next function.")
svar2 = (input("Too see the lowest temperature, print 'ja': "))
if svar2 == "ja":
print("Lowest temperature: ", str(min(temp_list)))
else:
print("This date wasn't found! You are now going to the next function.")
nyfiken = (input("To get the average temperature, print 'ja': "))
if nyfiken == "ja":
print("Average temperature was: " + str(sum(temp_list)/float(len(temp_list), str(round(total,2)))))
else:
print("This date wasn't found! The program is now closing.")
#Funktionen skriver ut medelsnittsvärdet
main ()
Could anybody help me??
> TypeError: unsupported operand type(s) for +: 'int' and 'list'*`
You trying to summation between int and list. Make a for loop on lists first, access the every element of them, then you can make summation.
if nyfiken == "ja":
print("Average temperature was: " + str(sum(temp_list)/float(len(temp_list),str(round(total,2)))))
Problem is here, as I said make a for loop on temp_list and access every element, then make summation.
Also you converting them to string, I dont think you can make summation with strings. You will get an output like :
>>> a=10
>>> b=20
>>> str(a)+str(b)
'1020'
>>>
Besides you can sum values by following this way:
sum1=0
timer=0
y=int(input("How much values do you want to sum?: "))
while True:
x=int(input("Entry values: "))
timer+=1
sum1+=x #sum1=0, we summing every value with eachother. 0 is ineffective value in summation.
if timer==y:
print ("Summation of your values: ",sum1)
break
You have a number of problems; we will approach them in order:
create_temp_list is supposed to return a list of float - but because of the way you use temp_list and temperatur and the way Python handles object assignment, it is actually returning a list of references to a list of float, ie temp_list[0] == temp_list[1] == temp_list[2] ... == temperatur. Instead, try
NUM_DAYS = 31
def get_float(prompt):
while True:
try:
return float(input(prompt))
except ValueError:
pass
def create_temp_list():
print("Hi! Type in a temperature for each day in december!: ")
make_prompt = "{}/12: ".format
return [get_float(make_prompt(day)) for day in range(1, NUM_DAYS+1)]
You never pass temp_list to search(); your program should look more like
def main():
temp_list = create_temp_list()
search(temp_list) # <= pass the data to search!
functions(temp_list)
def search(temp_list):
...
Because of (2), temp_list is not in scope (you cannot see that variable in search). To fix this, you tried to make test data like temp_list = [1-31]. This doesn't do what you think; it makes a one-item list containing the value -30. Then len(temp_list) is always 1, and index >= 1 and index < len(temp_list) is always False - which is good, because otherwise you would be stuck in an endless while loop! (It should be if ... else, not while ... else).
Hope that helps.

Puzzled about why I can't add strings together

I am trying to write a program that gets user information and adds it to a list and then I want to total how many user inputs there were, but I can't do it. I have tried running an accumulator, but I get TypeError: unsupported operand type(s) for +: 'int' and 'str'.
def main():
#total = 0
cel_list = []
another_celeb = 'y'
while another_celeb == 'y' or another_celeb == 'Y':
celeb = input('Enter a favorite celebrity: ')
cel_list.append(celeb)
print('Would you like to add another celebrity?')
another_celeb = input('y = yes, done = no: ')
print()
print('These are the celebrities you added to the list:')
for celeb in cel_list:
print(celeb)
#total = total + celeb
#print('The number of celebrities you have added is:', total)
main()
Here is the output as desired without the accumulator, but I still need to add the input together. I have commented out the accumulator.
Enter a favorite celebrity: Brad Pitt
Would you like to add another celebrity?
y = yes, done = no: y
Enter a favorite celebrity: Jennifer Anniston
Would you like to add another celebrity?
y = yes, done = no: done
These are the celebrities you added to the list:
Brad Pitt
Jennifer Anniston
>>>
Thanks in advance for any suggestions.
Total is an integer ( declared earlier on as )
total = 0
As the error code suggest, you are trying to join an integer with a string. That is not allowed. To get pass this error, you may :
## convert total from int to str
output = str(total) + celeb
print(" the number of celebrities you have added is', output)
or even better you can try using string formatting
##output = str(total) + celeb
## using string formatting instead
print(" the number of celebrities you have added is %s %s', % (total, celeb))
I hope this will work for you
Python is a dynamically typed language. So, when you type total = 0, the variable total becomes an integer i.e Python assigns a type to a variable depending on the value it contains.
You can check the type of any variable in python using type(variable_name).
len(object) returns integer value.
for celeb in cel_list:
print(celeb)
#end of for loop
total = 0
total = total + len(cel_list) # int + int
print('The number of celebrities you have added is:', total)
You can get the number of entries in a Python list by using the len() function. So, just use the following:
print('These are the celebrities you added to the list:')
for celeb in cel_list:
print(celeb)
total = len(cel_list)
print('The number of celebrities you have added is: ' + str(total))
Note the decreased indentation of the last two lines - you only need to run them once, after you've finished printing out the celeb's names.

TypeError: 'int' object is not subscriptable

I'm trying to create a simple program that tells you your lucky number according to numerology. I keep on getting this error:
File "number.py", line 12, in <module>
sumln = (int(sumall[0])+int(sumall[1]))
TypeError: 'int' object is not subscriptable
My script is:
birthday = raw_input("When is your birthday(mm/dd/yyyy)? ")
summ = (int(birthday[0])+int(birthday[1]))
sumd = (int(birthday[3])+int(birthday[4]))
sumy= (int(birthday[6])+int(birthday[7])+int(birthday[8])+int(birthday[9]))
sumall = summ + sumd + sumy
print "The sum of your numbers is", sumall
sumln = (int(sumall[0])+int(sumall[1]))
print "Your lucky number is", sumln`
The error is exactly what it says it is; you're trying to take sumall[0] when sumall is an int and that doesn't make any sense. What do you believe sumall should be?
If you want to sum the digit of a number, one way to do it is using sum() + a generator expression:
sum(int(i) for i in str(155))
I modified a little your code using sum(), maybe you want to take a look at it:
birthday = raw_input("When is your birthday(mm/dd/yyyy)? ")
summ = sum(int(i) for i in birthday[0:2])
sumd = sum(int(i) for i in birthday[3:5])
sumy = sum(int(i) for i in birthday[6:10])
sumall = summ + sumd + sumy
print "The sum of your numbers is", sumall
sumln = sum(int(c) for c in str(sumall)))
print "Your lucky number is", sumln
Just to be clear, all the answers so far are correct, but the reasoning behind them is not explained very well.
The sumall variable is not yet a string. Parentheticals will not convert to a string (e.g. summ = (int(birthday[0])+int(birthday[1])) still returns an integer. It looks like you most likely intended to type str((int(sumall[0])+int(sumall[1]))), but forgot to. The reason the str() function fixes everything is because it converts anything in it compatible to a string.
sumall = summ + sumd + sumy
Your sumall is an integer. If you want the individual characters from it, convert it to a string first.
You can't do something like that: (int(sumall[0])+int(sumall[1]))
That's because sumall is an int and not a list or dict.
So, summ + sumd will be you're lucky number
Try this instead:
sumall = summ + sumd + sumy
print "The sum of your numbers is", sumall
sumall = str(sumall) # add this line
sumln = (int(sumall[0])+int(sumall[1]))
print "Your lucky number is", sumln
sumall is a number, and you can't access its digits using the subscript notation (sumall[0], sumall[1]). For that to work, you'll need to transform it back to a string.
this code works for summer_69. It looks too simple to be true :)
def summer_69(mylist):
ignore = False
sum = 0
for i in mylist:
if i == 6:
ignore = True
elif not ignore:
sum = sum + i
elif i == 9:
ignore = False
return sum
summer_69([1,2,2,6,3,7,9,3])
I think the statement is self-explanatory.
[TypeError: 'int' object is not subscriptable]
You are trying to do something the computer can't do. The data type "integer" cannot be subscripted. It should be a "string" to do that.
So, convert the integer data type to a string and you will be good to go. (Go back to the lessons on data types and subscription and come back.)
Keep up all the good work!!!

Categories

Resources