3

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:

  1. Which part of the code doesn't work?
  2. What is my error?

I'm relatively new to computer science in general. Thanks for the help. Anything is appreciated!

developer_hatch
  • 15,898
  • 3
  • 42
  • 75
Crescendo
  • 105
  • 1
  • 10
  • 1
    For starters, your indentation on your `def` is wrong. Cannot tell what belongs to what here. – pstatix Jul 01 '17 at 04:01
  • Make sure your indentation is correct, because Python is sensitive to how things are indented. After the first line, you need to indent everything that's part of the `receipt` function. – McGlothlin Jul 01 '17 at 04:03
  • @McGlothlin Oops, in my program, I had it all indented correctly. I'll go ahead and edit that in regardless though. – Crescendo Jul 01 '17 at 04:06
  • @Crescendo I hope you are learning python, but your solution is kind of inefficient for long arrays. you are passing the entire array in the function and performing sum over its elements. You can use the technique of memoization so that you add only new element to the result rather than recomputing the entire result – Yaman Jain Jul 01 '17 at 08:43
  • @YamanJain Yes, I'm learning Python. What is this "memorization" technique that you said? – Crescendo Jul 01 '17 at 13:46

6 Answers6

3

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.

McGlothlin
  • 2,059
  • 1
  • 15
  • 28
3

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.

void
  • 2,571
  • 2
  • 20
  • 35
2

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))
developer_hatch
  • 15,898
  • 3
  • 42
  • 75
  • @I tried that, and Python said that it could not transform string to float. Any ideas on what is wrong still? I made the changes. – Crescendo Jul 01 '17 at 04:10
  • @Crescendo that's odd, it worked for me, which python are you using? – developer_hatch Jul 01 '17 at 04:12
  • @Crescendo try change to `n = float(eval(input("Enter a price: ")))` – developer_hatch Jul 01 '17 at 04:13
  • I have the latest version available. Python 3.6 I believe. If I add the eval(), I get "unexpected EOF while parsing" error. – Crescendo Jul 01 '17 at 04:13
  • @DamianLattenero Probably when OP ends the input, hitting Enter, it will return an error like that, in the `if` condition. – Vinícius Figueiredo Jul 01 '17 at 04:16
  • @DamianLattenero Copied and pasted: Enter a price: 56.4 Enter a price: 56.6 Enter a price: Traceback (most recent call last): File "--------\Calculating Price.py", line 12, in n = float(input("Enter a price: ")) ValueError: could not convert string to float: >>> – Crescendo Jul 01 '17 at 04:17
  • Did you guys try running his code? The error was quite clear. – McGlothlin Jul 01 '17 at 04:18
  • @McGlothlin sure it was, but his code, assuming it's a receipt script, doesn't work like intended, therefore we also apply modification for it not only to work without returning errors, but to work as intended. – Vinícius Figueiredo Jul 01 '17 at 04:20
  • My mistake, I didn't catch that. – McGlothlin Jul 01 '17 at 04:22
  • 1
    @Crescendo to avoid this error, you should just replace the line with `array.append(float(n))`, and let your input be as the original one: `n = input("Enter a price: ")`, this way you avoid the error when trying to stop inserting values. Or simply convert to float inside the function, as my answer suggests. – Vinícius Figueiredo Jul 01 '17 at 04:24
  • As always @DamianLattenero the nice guy. Good answer +1. change the `n` into `float` while appending into the `array`. That would be good. – void Jul 01 '17 at 04:53
  • @ViníciusAguiar thanks so much for showing the error to me, I didn't notice that, I made an update to the answer doing what you clever suggested :). Thanks again – developer_hatch Jul 01 '17 at 20:02
2

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))
Vinícius Figueiredo
  • 6,300
  • 3
  • 25
  • 44
0

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.
pstatix
  • 3,611
  • 4
  • 18
  • 40
0

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.
kmfsousa
  • 183
  • 1
  • 1
  • 11
  • _"while true is generally unsafe"_ - Meh, not really. As long as you make sure you have a break condition, it's perfectly fine to use a `while True` loop. It's really no less safe than recursion. I like the rest of your answer, but this part just bugs me a bit :P – Christian Dean Jul 01 '17 at 04:53
  • It bugs me too. `while True` or `while condition`--> would equally be `while true` as long as condition is true .so both are almost same as long as you have a `break` based on some condition inside `while` . – void Jul 01 '17 at 04:57