Debugging simple Python pricing code
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 is 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 have used the [i] component correctly. Perhaps this is a string issue?
Question:
- Which part of the code doesn't work?
- What's my error?
I am relatively new to computer science in general. Thanks for the help. Everything is appreciated!
source to share
You have some problems, I will comment one by one:
You had problems with indenting at first, be careful with that. Other 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))
source to share
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 your string sum = sum + array[i]
does not have the same types. You need to wrap array[i]
in a function float()
to match the array[i]
type sum
, which is floating point since you initialized it before 0.0
. The docs say that the function input()
returns a string, and since you are adding n
in array
, you are trying to sum the string with a float. The line should look like this:
sum = sum + float(array[i])
Try to run it again and the code works. Here is the documentation forinput()
Edit: now to fix the problems were with the sum.
Here is a version of your code that I revisited with fixes to make the addition the way you want it.
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, is sum
not a large variable name, so I renamed it sumvar
. Notice the declaration sumvar
outside the function. When you initialize sumvar
inside receipt()
, like you do, you always add n
to 0.0
. I doubt this is what you want. Instead, you want to store the total number of item counts that need to be passed to the function. I have also removed the loop from your function. This loop was actually repeating the characters in array
, not the elements you expected from it.
source to share
First, there are a few bugs. I will explain everything 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. Quite often for beginners.
input()
in python gets user input as string . So yours n
is a String .
See, there are data types in all languages. And Python is a strongly typed language , and Perl is not . How to tell if a language is strongly typed or weakly typed? Just. 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'
Look at the error, try this,
>>> a=5
>>> b='9'
>>> a+int(b)
14
Works great. Python doesn't allow it to be easy a+b
, while some languages ββuse the perl example. Find out more about this. Therefore you cannot add them, you must typecast . So change this to
array.append(int(n))
or
array.append(float(n))
If you are going to work with float values.
2) totalCost = receipt(n)
See how you pass the function n
. But your function definition does def receipt(array):
. What's really going on here:
receipt(n) ----> (calls) ---->def receipt(array):
Where n ------> array
So, yours array
is nothing but n
. What you have to do is
totalCost = receipt(array)
3) sum = 0.0
NEVER have I used inline or keyword names (like sum, min, max, int, str, etc.) as variable names. More on naming in PEP 8
So, rename sum
to sum_
(this is a convention to be followed). But why can not you just rename sum
in total
much easier?
4) Finally
for i in range(len(array)):
sum = sum + array[i]
Why range(len(array))
when you can just dofor i in array:
Can't figure it out, look at this example:
>>> a = [1,2,3]
>>> for i in a:
print(i)
1
2
3
See for item in something
simply will take each element from the group of something (iterable (list, tuple, set, etc.))
So, just change these 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 the comments, you need to know more about indentation . Check out the link in the comments.
source to share
You shouldn't use sum
as a variable as it is built in Python, besides converts yours array[i]
to float when you add it to another float, also note that you never use your initialized one 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))
source to share
Don't use it sum
as a variable name, it's 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()
A few tips:
- When writing a function, it is 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 the price (which we know usually ends in 2 decimal places) it is better to use integers rather than float as you run into the problem of] ( Limiting floats to two decimal places ) with floating point numbers.
source to share
I fixed what is causing your problem, you are actually passing "n" to the 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 problems:
- indentation (I suspect it was only a copy)
- the input will also give you errors as you use it, have a look at this one to fix this.
- Consider also that your loop is based on the value of n, since while being true is generally unsafe
- or at least changing your if statement to "not n" as stated here is more pythonic. Also in the future, be sure to pay attention to the version of the python you are using.
source to share