Python Forum
ValueError: invalid literal for int() with base 10: '\n'
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
ValueError: invalid literal for int() with base 10: '\n'
#1
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)
Reply
#2
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)
Reply
#3
Provide the entire error string please.
Reply
#4
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))
Reply
#5
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
Reply
#6
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'
Reply
#7
On row #10 you do line.strip(). Strings are immutable so what is happening:

>>> s = '1\n'
>>> s.strip()
'1'
>>> s
'1\n'
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#8
(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.
Reply
#9
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)
Reply
#10
Nice. Do you now get the result you wanted?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  ValueError: invalid literal for int() with base 10: omega_elite 5 5,675 Dec-30-2020, 06:11 AM
Last Post: delonbest
  invalid literal for int() with base 10: '# NRECS: 1096\n' Baloch 8 4,452 May-24-2020, 02:08 AM
Last Post: Larz60+
  invalid literal for int() with base 10: '' mrsenorchuck 5 5,321 Apr-29-2020, 05:48 AM
Last Post: markfilan
  zlib decompress error: invalid code lengths set / invalid block type DreamingInsanity 0 6,739 Mar-29-2020, 12:44 PM
Last Post: DreamingInsanity
  input-ValueError: invalid literal for int() jacklee26 2 2,509 Feb-21-2020, 01:27 PM
Last Post: ndc85430
  ValueError: invalid literal for int() with base 10: '0.5' emmapaw24 2 3,671 Feb-16-2020, 07:24 PM
Last Post: emmapaw24
  ValueError: invalid literal for int() with base 10: '' Jay123 7 7,216 Aug-05-2019, 02:43 PM
Last Post: Jay123
  ValueError: invalid rectstyle object fen1c5 1 5,617 Jun-05-2019, 02:51 PM
Last Post: heiner55
  ValueError: invalid literal for int() with base 10: '' ivinjjunior 6 9,068 Apr-20-2019, 05:37 PM
Last Post: keames
  Problem with "invalid literal for int() with base 10: '' jirkaj4 4 10,382 Jan-23-2018, 06:55 PM
Last Post: jirkaj4

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020