Python Forum

Full Version: ValueError: invalid literal for int() with base 10: '\n'
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm getting the error "int() with base 10" can anyone please find the error
Quote:choclate 35
biscuit 20
Icecream 50

Discount 5
Quote:this is the data in my text file to extract the price i'm using slicing


def calculate(fname):
    try:
        with open(fname, "r") as file:
            totalAmount = 0
            FreeItems = 0
            Discount = 0
            ItemsPurchased = 0
            FinalAmount = 0
            for line in file.readlines():
                line.strip()
                ItemsPurchased += 1
                if(line[line.find(' ')+1:] != "Free"):
                    totalAmount += int(line[line.find(' ')+1:])
                elif(line[line.find(' ')+1:] == "Free"):
                    FreeItems += 1
                elif(line[line.find("Discount")] == "Discount"):
                    Discount += int(line[line.find(' ')+1:])
            FinalAmount = totalAmount-Discount

    except IOError:
        print("File doesn't exist cannot perform operations on the file")
    else:
        print("No of items purchased:".format(ItemsPurchased))
        print("No of free items:".format(FreeItems))
        print("Amount to pay:".format(totalAmount))
        print("Discount given:".format(Discount))
        print("Final Amount paid:".format(FinalAmount))


if __name__ == "__main__":
    fname = input()
    calculate(fname)
Quote:I'm getting the error "int() with base 10" can anyone please find the error

Quote:choclate 35
biscuit 20
Icecream 50

Discount 5

Quote:this is the data in my text file to extract the price i'm using slicing
def calculate(fname):
    try:
        with open(fname, "r") as file:
            totalAmount = 0
            FreeItems = 0
            Discount = 0
            ItemsPurchased = 0
            FinalAmount = 0
            for line in file.readlines():
                line.strip()
                ItemsPurchased += 1
                if(line[line.find(' ')+1:] != "Free"):
                    totalAmount += int(line[line.find(' ')+1:])
                elif(line[line.find(' ')+1:] == "Free"):
                    FreeItems += 1
                elif(line[line.find("Discount")] == "Discount"):
                    Discount += int(line[line.find(' ')+1:])
            FinalAmount = totalAmount-Discount
 
    except IOError:
        print("File doesn't exist cannot perform operations on the file")
    else:
        print("No of items purchased:".format(ItemsPurchased))
        print("No of free items:".format(FreeItems))
        print("Amount to pay:".format(totalAmount))
        print("Discount given:".format(Discount))
        print("Final Amount paid:".format(FinalAmount))
 
 
if __name__ == "__main__":
    fname = input()
    calculate(fname)
Provide the entire error string please.
The problem is with your input. If you look at the Traceback, you should see the error raised. 'ValueError:' Capturing the error in your try/except blocks will allow you to see just what the offending line is.

    except IOError:
        print("File doesn't exist cannot perform operations on the file")
    except ValueError:
        print("Invalid input:")
        print(repr(line))
    else:
        print("No of items purchased:".format(ItemsPurchased))
        print("No of free items:".format(FreeItems))
        print("Amount to pay:".format(totalAmount))
        print("Discount given:".format(Discount))
        print("Final Amount paid:".format(FinalAmount))
Deanhstad means show entire, unaltered error traceback.
It contains very valuable information about error, and shows program flow that led up to the error.
And don't forget error tags
Quote:This is the error i'm encountering while executing the code
Traceback (most recent call last):
  File "C:\Users\srini\github\Wipro-python-based-projects\Exception handling\Main.py", line 33, in <module>
    calculate(fname)
  File "C:\Users\srini\github\Wipro-python-based-projects\Exception handling\Main.py", line 14, in calculate
    totalAmount += int(line[line.find(' ')+1:])
ValueError: invalid literal for int() with base 10: '\n'
On row #10 you do line.strip(). Strings are immutable so what is happening:

>>> s = '1\n'
>>> s.strip()
'1'
>>> s
'1\n'
(Apr-10-2020, 01:39 AM)srisrinu Wrote: [ -> ]
Error:
Traceback (most recent call last): File "C:\Users\srini\github\Wipro-python-based-projects\Exception handling\Main.py", line 33, in <module> calculate(fname) File "C:\Users\srini\github\Wipro-python-based-projects\Exception handling\Main.py", line 14, in calculate totalAmount += int(line[line.find(' ')+1:]) ValueError: invalid literal for int() with base 10: '\n'
So you knew all the time the error is in line 14. Or better: line 13 in the code as you show it to us. And you let us guess!?
So the problem is the parameter of the int() function.
When you have something like this, insert a print statement just before the offending line to check what the parameter is. Then you can see what really happens. Like this:
                    print(f"DEBUG1:  |{line[line.find(' ')+1:]}|")
                    totalAmount += int(line[line.find(' ')+1:])
And by the way, you strip the line but you do nothing with the returned value.
    line.strip()
I think you meant to do something like:
    stripped_line = line.strip()
I hope this helps you.
def calculate(fname):
    try:
        with open(fname, "r") as file:
            totalAmount = 0
            FreeItems = 0
            Discount = 0
            ItemsPurchased = 0
            FinalAmount = 0
            flst = file.readlines()
            for line in flst:
                if (not line.isspace()):
                    line = line.rstrip("\n")
                    if(not line.startswith("Discount")):
                        ItemsPurchased += 1
                        if(line[line.find(' ')+1:] != "Free"):
                            totalAmount += int(line[line.find(' ')+1:])
                        elif(line[line.find(' ')+1:] == "Free"):
                            FreeItems += 1
                    elif(line.startswith("Discount")):
                        Discount += int(line[line.find(' ')+1:])
            FinalAmount = totalAmount-Discount

    except IOError:
        print("File doesn't exist cannot perform operations on the file")
    except ValueError:
        print("Invalid input:")
        print(repr(line))
    else:
        print("No of items purchased:{}".format(ItemsPurchased))
        print("No of free items:{}".format(FreeItems))
        print("Amount to pay:{}".format(totalAmount))
        print("Discount given:{}".format(Discount))
        print("Final Amount paid:{}".format(FinalAmount))


if __name__ == "__main__":
    fname = input()
    calculate(fname)
Nice. Do you now get the result you wanted?