Exceptions Category Page - PythonForBeginners.com https://www.pythonforbeginners.com Learn By Example Wed, 16 Jun 2021 14:12:40 +0000 en-US hourly 1 https://wordpress.org/?v=5.8.13 https://www.pythonforbeginners.com/wp-content/uploads/2020/05/cropped-pfb_icon-32x32.png Exceptions Category Page - PythonForBeginners.com https://www.pythonforbeginners.com 32 32 201782279 ValueError: Invalid Literal For int() With Base 10 https://www.pythonforbeginners.com/exceptions/valueerror-invalid-literal-for-int-with-base-10 Wed, 16 Jun 2021 14:12:38 +0000 https://www.pythonforbeginners.com/?p=8838 Python ValueError: invalid literal for int() with base 10 is an exception which can occur when we attempt to convert a string literal to integer using int() method and the string literal contains characters other than digits. In this article, we will try to understand the reasons behind this exception and will look at different […]

The post ValueError: Invalid Literal For int() With Base 10 appeared first on PythonForBeginners.com.

]]>
Python ValueError: invalid literal for int() with base 10 is an exception which can occur when we attempt to convert a string literal to integer using int() method and the string literal contains characters other than digits. In this article, we will try to understand the reasons behind this exception and will look at different methods to avoid it in our programs.

What is “ValueError: invalid literal for int() with base 10” in Python?

A ValueError is an exception in python which occurs when an argument with the correct type but improper value is passed to a method or function.The first part of the message i.e. “ValueError” tells us that an exception has occurred because an improper value is passed as argument to the int() function. The second part of the message “invalid literal for int() with base 10”  tells us that we have tried to convert an input to integer but the input has characters other than digits in the decimal number system.

Working of int() function

The int() function in python takes a string or a number as first argument and an optional argument base which denotes the number format. The base has a default value 10 which is used for decimal numbers but we can pass a different value  for base such as 2 for binary number or 16 for hexadecimal number. In this article, we will use the int() function with only the first argument and the default value for base will always be zero.  This can be seen in the following examples.

We can convert a floating point number to integer as given in the following example.When we convert a floating point number into integer using int() function, the digits after the decimal are dropped from the number in the output. 


print("Input Floating point number is")
myInput= 11.1
print(myInput)
print("Output Integer is:")
myInt=int(myInput)
print(myInt)

Output:

Input Floating point number is
11.1
Output Integer is:
11

We can convert a string consisting of digits to an integer as given in the following example. Here the input consists of only the digits and hence it will be directly converted into an integer. 

print("Input String is:")
myInput= "123"
print(myInput)
print("Output Integer is:")
myInt=int(myInput)
print(myInt)

Output:

Input String is:
123
Output Integer is:
123

The two input types shown in the above two examples are the only input types for which int() function works properly. With other types of inputs, ValueError will be generated with the message ”invalid literal for int() with base 10” when they are passed as arguments to the int() function. Now , we will look at various types of inputs for which ValueError can be generated in the int() function.

When does “ValueError: invalid literal for int() with base 10” occur?

As discussed above, “ValueError: invalid literal for int()” with base 10 can occur when input with an inappropriate value is passed to the int() function. This can happen in the following conditions.

1.Python ValueError: invalid literal for int() with base 10 occurs when input to int() method is alphanumeric instead of numeric and hence the input cannot be converted into an integer.This can be understood with the following example.

In this example, we pass a string containing alphanumeric characters to the int() function due to which ValueError occurs showing a message “ ValueError: invalid literal for int() with base 10”  in the output.

print("Input String is:")
myInput= "123a"
print(myInput)
print("Output Integer is:")
myInt=int(myInput)
print(myInt)

Output:


Input String is:
123a
Output Integer is:
Traceback (most recent call last):

  File "<ipython-input-9-36c8868f7082>", line 5, in <module>
    myInt=int(myInput)

ValueError: invalid literal for int() with base 10: '123a'

2. Python ValueError: invalid literal for int() with base 10 occurs when the input to int() function contains space characters and hence the input cannot be converted into an integer. This can be understood with the following example.

In this example, we pass a string containing space to the int() function due to which ValueError occurs showing a message “ ValueError: invalid literal for int() with base 10”  in the output.

print("Input String is:")
myInput= "12 3"
print(myInput)
print("Output Integer is:")
myInt=int(myInput)
print(myInt)

Output:

Input String is:
12 3
Output Integer is:
Traceback (most recent call last):

  File "<ipython-input-10-d60c59d37000>", line 5, in <module>
    myInt=int(myInput)

ValueError: invalid literal for int() with base 10: '12 3'

3. Python ValueError: invalid literal for int() with base 10 occurs when the input to int() function contains any punctuation marks like period “.” or comma “,”.  Hence the input cannot be converted into an integer.This can be understood with the following example.

In this example, we pass a string containing period character “.” to the int() function due to which ValueError occurs showing a message “ ValueError: invalid literal for int() with base 10”  in the output.

print("Input String is:")
myInput= "12.3"
print(myInput)
print("Output Integer is:")
myInt=int(myInput)
print(myInt)

Output:

Input String is:
12.3
Output Integer is:
Traceback (most recent call last):

  File "<ipython-input-11-9146055d9086>", line 5, in <module>
    myInt=int(myInput)

ValueError: invalid literal for int() with base 10: '12.3'

How to avoid “ValueError: invalid literal for int() with base 10”?

We can avoid the ValueError: invalid literal for int() with base 10 exception using preemptive measures to check if the input being passed to the int() function consists of only digits or not. We can use several ways to check if the input being passed to int() consists of only digits or not as follows.

1.We can use regular expressions to check if the input being passed to the int() function consists of only digits or not. If the input contains characters other than digits, we can prompt the user that the input cannot be converted to integer. Otherwise, we can proceed normally.

In the python code given below, we have defined a regular expression “[^\d]” which matches every character except digits in the decimal system. The re.search() method searches for the pattern and if the pattern is found, it returns a match object. Otherwise re.search() method returns None. 

Whenever, re.search() returns None, it can be accomplished that the input has no characters other than digits and hence the input can be converted into an integer as follows.

import re
print("Input String is:")
myInput= "123"
print(myInput)
matched=re.search("[^\d]",myInput)
if matched==None:
    myInt=int(myInput)
    print("Output Integer is:")
    print(myInt)
else:
    print("Input Cannot be converted into Integer.")

Output:

Input String is:
123
Output Integer is:
123

If the input contains any character other than digits,re.search() would contain a match object and hence the output will show a message that the input cannot be converted into an integer.

import re
print("Input String is:")
myInput= "123a"
print(myInput)
matched=re.search("[^\d]",myInput)
if matched==None:
    myInt=int(myInput)
    print("Output Integer is:")
    print(myInt)
else:
    print("Input Cannot be converted into Integer.")

Output:

Input String is:
123a
Input Cannot be converted into Integer.

2.We can also use isdigit() method to check whether the input consists of only digits or not. The isdigit() method takes a string as input and returns True if the input string passed to it as an argument consists only of digital in the decimal system  . Otherwise, it returns False. After checking if the input string consists of only digits or not, we can convert the input into integers.

In this example, we have used isdigit() method to check whether the given input string consists of only the digits or not. As the input string ”123” consists only of digits, the isdigit() function will return True and the input will be converted into an integer using the int() function as shown in the output.

print("Input String is:")
myInput= "123"
print(myInput)
if myInput.isdigit():
    print("Output Integer is:")
    myInt=int(myInput)
    print(myInt)
else:
    print("Input cannot be converted into integer.")

Output:

Input String is:
123
Output Integer is:
123

If the input string contains any other character apart from digits, the isdigit() function will return False. Hence the input string will not be converted into an integer.

In this example, the given input is “123a” which contains an alphabet due to which isdigit() function will return False and the message will be displayed in the output that the input cannot be converted into integer as shown below.

print("Input String is:")
myInput= "123a"
print(myInput)
if myInput.isdigit():
    print("Output Integer is:")
    myInt=int(myInput)
    print(myInt)
else:
    print("Input cannot be converted into integer.")    

Output:

Input String is:
123a
Input cannot be converted into integer.

3.It may be possible that the input string contains a floating point number and has a period character “.” between the digits. To convert such inputs to integers using the int() function, first we will check if the input string contains a floating point number i.e. it has only one period character between the digits or not using regular expressions. If yes, we will first convert the input into a floating point number which can be passed to int() function and then we will show the output. Otherwise, it will be notified that the input cannot be converted to an integer.

In this example,  “^\d+\.\d$” denotes a pattern which starts with one or more digits, has a period symbol ”.” in the middle and ends with one or more digits which is the pattern for floating point numbers. Hence, if the input string is a floating point number, the re.search() method will not return None and the input will be converted into a floating point number using float() function and then it will be converted to an integer as follows. 

import re
print("Input String is:")
myInput= "1234.5"
print(myInput)
matched=re.search("^\d+\.\d+$",myInput)
if matched!=None:
    myFloat=float(myInput)
    myInt=int(myFloat)
    print("Output Integer is:")
    print(myInt)
else:
    print("Input is not a floating point literal.")

Output:

Input String is:
1234.5
Output Integer is:
1234

If the input is not a floating point literal, the re.search() method will return a None object and  the message will be shown in the output that input is not a floating point literal as follows.

import re
print("Input String is:")
myInput= "1234a"
print(myInput)
matched=re.search("^\d+\.\d$",myInput)
if matched!=None:
    myFloat=float(myInput)
    myInt=int(myFloat)
    print("Output Integer is:")
    print(myInt)
else:
    print("Input is not a floating point literal.")

Output:

Input String is:
1234a
Input is not a floating point literal.

For the two approaches using regular expressions, we can write a single program using groupdict() method after writing named patterns using re.match() object. groupdict() will return a python dictionary of named captured groups in the input and thus can be used to identify the string which can be converted to integer.

4.We can also use exception handling in python using python try except to handle the ValueError whenever the error occurs. In the try block of the code, we will normally execute the code. Whenever ValueError occurs, it will be raised in the try block and will be handled by the except block and a proper message will be shown to the user.

 If the input consists of only the digits and is in correct format, output will be as follows.

print("Input String is:")
myInput= "123"
print(myInput)
try:
    print("Output Integer is:")
    myInt=int(myInput)
    print(myInt)
except ValueError:
    print("Input cannot be converted into integer.")

Output:

Input String is:
123
Output Integer is:
123

If the input contains characters other than digits such as alphabets or punctuation, ValueError will be thrown from the int() function which will be caught by the except block and a message will be shown to the user that the input cannot be converted into integer.

print("Input String is:")
myInput= "123a"
print(myInput)
try:
    print("Output Integer is:")
    myInt=int(myInput)
    print(myInt)
except ValueError:
    print("Input cannot be converted into integer.")

Output:

Input String is:
123a
Output Integer is:
Input cannot be converted into integer.

Conclusion

In this article, we have seen why “ValueError: invalid literal for int() with base 10” occurs in python and have understood the reasons and mechanism behind it. We have also seen that this error can be avoided by first checking if the input to int() function consists of only digits or not using different methods like regular expressions and inbuilt functions. 

The post ValueError: Invalid Literal For int() With Base 10 appeared first on PythonForBeginners.com.

]]>
8838
User Defined Exceptions in Python https://www.pythonforbeginners.com/exceptions/user-defined-exceptions-in-python Fri, 19 Mar 2021 12:35:33 +0000 https://www.pythonforbeginners.com/?p=8456 When we write programs in python for real life applications, there are many constraints on the values which the variables can take in the program. For example, age cannot have a negative value. When a person inputs a negative value for age, the program should show an error message. But these types of constraints  cannot […]

The post User Defined Exceptions in Python appeared first on PythonForBeginners.com.

]]>
When we write programs in python for real life applications, there are many constraints on the values which the variables can take in the program. For example, age cannot have a negative value. When a person inputs a negative value for age, the program should show an error message. But these types of constraints  cannot be applied in the python programs automatically. To handle these types of errors and force constraints on values, we use user defined exceptions in python. In this article we will look at different methods by which we can implement user defined exceptions in python.

What are user defined exceptions in python?

User defined exceptions in python are created by programmers to enforce constraints on the values which the variables in the program can take. Python has many built in exceptions which are raised when there is some error in the program. A program automatically terminates after showing which inbuilt exception has occurred while executing the program when it reaches into an undesired state. We can stop the program from entering into an undesired state by enforcing constraints using user defined exceptions.

User defined exceptions can be implemented by raising an exception explicitly, by using assert statement or by defining custom classes for user defined exceptions. We will study each method one by one in this article.

Using raise keyword explicitly after conditional statements

Inbuilt exceptions are raised automatically by a program in python but we can also raise inbuilt exceptions using the python try except blocks and raise keyword. By raising an inbuilt exception explicitly using raise keyword, we can use them anywhere in the program to enforce constraints on the values of variables.

For example, suppose we have to calculate the year of birth of a person from its age, we can do it as following:

age= 10
print("Age is:")
print(age)
yearOfBirth= 2021-age
print("Year of Birth is:")
print(yearOfBirth)

Output:

Age is:
10
Year of Birth is:
2011

The program has given proper output in the case by subtracting age from current year. Now suppose we give a negative value for age in input, say -10.

age= -10
print("Age is:")
print(age)
yearOfBirth= 2021-age
print("Year of Birth is:")
print(yearOfBirth)

Output:

Age is:
-10
Year of Birth is:
2031

When we provide a negative number for age, the program still works fine but gives an output which is logically incorrect because no person can have his year of birth in future.

To prevent this kind of year, we can check if the value given in age as input is negative and then we can force the program to raise an exception using raise keyword as follows.

The syntax for raise statement is raise ExceptionName . When an error is raised, the code in the except block should handle the exception otherwise it will cause error in the program.

try:
    age= -10
    print("Age is:")
    print(age)
    if age<0:
        raise ValueError
    yearOfBirth= 2021-age
    print("Year of Birth is:")
    print(yearOfBirth)
except ValueError:
    print("Input Correct age.")

Output:

Age is:
-10
Input Correct age.

Here we can see that for age -10, the program handles the case successfully. Lets check if it gives correct year of birth when given correct value of age.

try:
    age= 10
    print("Age is:")
    print(age)
    if age<0:
        raise ValueError
    yearOfBirth= 2021-age
    print("Year of Birth is:")
    print(yearOfBirth)
except ValueError:
    print("Input Correct age.")

Output:

Age is:
10
Year of Birth is:
2011

So, we can see that after using raise statement in try except block, the program gives correct output in both the cases. Now we will see how we can use assert statements to enforce the same constraint.

Using Assert statements to implement user defined exceptions in python

We can use assert statement to implement constraints on values of our variable in python. When, the condition given in assert statement is not met, the program gives AssertionError in output.

The syntax for assert statement in python is assert condition where condition can be any conditional statement which evaluates to True or False. When the condition in assert statement evaluates to True, the program works normally. When the condition in the assert statement evaluates to False, the program gives AssertionError.

To enforce the constraint that age should be greater than zero, we can use assert statement as shown in the following program.

age= 10
print("Age is:")
print(age)
assert age>0
yearOfBirth= 2021-age
print("Year of Birth is:")
print(yearOfBirth)

Output:

Age is:
10
Year of Birth is:
2011

When negative value is given as input for age, the condition will evaluate to false and program will end due to AssertionError.

age= -10
print("Age is:")
print(age)
assert age>0
yearOfBirth= 2021-age
print("Year of Birth is:")
print(yearOfBirth)

Output:

Age is:
-10
Traceback (most recent call last):

  File "<ipython-input-9-214b1ab4dfa4>", line 4, in <module>
    assert age>0

AssertionError

We can also give a message to print when condition is not met in assert statement. The syntax for printing the message with assert statement is assert condition, message . message should be a string constant. Whenever the condition in assert statement evaluates to False, the program will raise an AssertionError and will print the message.

age= -10
print("Age is:")
print(age)
assert age>0 , "Age should be positive integer"
yearOfBirth= 2021-age
print("Year of Birth is:")
print(yearOfBirth)

Output:

Age is:
-10
Traceback (most recent call last):

  File "<ipython-input-10-82c11649bdd0>", line 4, in <module>
    assert age>0 , "Age should be positive integer"

AssertionError: Age should be positive integer

In the output, we can see that message that “Age should be positive integer” is also printed along with AssertionError.

We can also handle AssertionError by using try except block if want to disallow the program from exiting prematurely. There may be cases when python write to file operation has been performed, if the program exits prematurely, the data written in the file will not be saved. For the data written in the file to be saved, we need to close the file before the program exits. For this we will have to use try except blocks along with assert statement as follows.

try:
    age= -10
    print("Age is:")
    print(age)
    assert age>0
    yearOfBirth= 2021-age
    print("Year of Birth is:")
    print(yearOfBirth)
except AssertionError:
    print("Input Correct age.")
    

Output:

Age is:
-10
Input Correct age.

In the output, we can see that when age is less than 0, AssertionError has occurred but it has been handled by code in except block. If we want to perform any file operation then we can implement the code in except block or we can use finally block to implement the code.

Defining custom classes for user defined exceptions

To create a user defined exception, we create a class with desired exception name which should inherit Exception class. After that, we can raise the exception in our code anywhere according to our need to implement constraints.

To generate a user defined exception, we use the “raise” keyword when a certain condition is met. The exception is then handled by the except block of the code. We then use pass statement. pass statement is used to show that we will not implement anything in our custom exception class. It is used as a placeholder and does nothing, still we have to use it because if we leave the body of our custom class empty, python interpreter will show that there is error in our code.

Example:



class NegativeAgeError(Exception):
    pass
try:
    age= -10
    print("Age is:")
    print(age)
    if age<0:
        raise NegativeAgeError
    yearOfBirth= 2021-age
    print("Year of Birth is:")
    print(yearOfBirth)
except NegativeAgeError:
    print("Input Correct age.")

Output:

Age is:
-10
Input Correct age.

Here we can see that when age has a value less than zero, the try block in the program throws NegativeAgeError using raise keyword. The exception is then handled by except block. If we will give correct value for age as input, it will print the year of birth normally.


class NegativeAgeError(Exception):
    pass
try:
    age= 10
    print("Age is:")
    print(age)
    if age<=0:
        raise NegativeAgeError
    yearOfBirth= 2021-age
    print("Year of Birth is:")
    print(yearOfBirth)
except NegativeAgeError:
    print("Input Correct age.")

Output:

Age is:
10
Year of Birth is:
2011

Conclusion:

In this article, we have seen how to implement constraints on values of variables in python using custom exception handling methods like assert keyword, raise keyword and custom exception class. We can also use user defined exceptions to implement different real life constraints in our program so that programs are syntactically correct and logically sound.Stay tuned for more articles.

The post User Defined Exceptions in Python appeared first on PythonForBeginners.com.

]]>
8456
Exception Handling in Python https://www.pythonforbeginners.com/error-handling/exception-handling-in-python Thu, 11 Jul 2013 05:45:26 +0000 https://www.pythonforbeginners.com/?p=5827 Overview In this post we will cover how Python handles errors with exceptions. What is an Exception? An exception is an error that happens during execution of a program. When thaterror occurs, Python generate an exception that can be handled, which avoids yourprogram to crash. Why use Exceptions? Exceptions are convenient in many ways for […]

The post Exception Handling in Python appeared first on PythonForBeginners.com.

]]>
Overview

In this post we will cover how Python handles errors with exceptions.

What is an Exception?

An exception is an error that happens during execution of a program. When that
error occurs, Python generate an exception that can be handled, which avoids your
program to crash.

Why use Exceptions?

Exceptions are convenient in many ways for handling errors and special conditions
in a program. When you think that you have a code which can produce an error then
you can use exception handling.

Raising an Exception

You can raise an exception in your own program by using the raise exception
statement.

Raising an exception breaks current code execution and returns the exception
back until it is handled.

Exception Errors

Below is some common exceptions errors in Python:
IOError
If the file cannot be opened.

ImportError
If python cannot find the module

ValueError
Raised when a built-in operation or function receives an argument that has the
right type but an inappropriate value

KeyboardInterrupt
Raised when the user hits the interrupt key (normally Control-C or Delete)

EOFError
Raised when one of the built-in functions (input() or raw_input()) hits an
end-of-file condition (EOF) without reading any data

Exception Errors Examples

Now, when we know what some of the exception errors means, let’s see some
examples:


except IOError:
print('An error occurred trying to read the file.')
except ValueError:
print('Non-numeric data found in the file.')
except ImportError:
print "NO module found"
except EOFError:
print('Why did you do an EOF on me?')
except KeyboardInterrupt:
print('You cancelled the operation.')
except:
print('An error occurred.')

Try to use as few try blocks as possible and try to distinguish the failure
conditions by the kinds of exceptions they throw.

Set up exception handling blocks

To use exception handling in Python, you first need to have a catch-all except
clause.

The words “try” and “except” are Python keywords and are used to catch exceptions.

try-except [exception-name] (see above for examples) blocks

The code within the try clause will be executed statement by statement.

If an exception occurs, the rest of the try block will be skipped and the
except clause will be executed.

try:
some statements here
except:
exception handling
Let's see a short example on how to do this:

try:
print 1/0
except ZeroDivisionError:
print "You can't divide by zero, you're silly."

How does it work?

The error handling is done through the use of exceptions that are caught in try
blocks and handled in except blocks. If an error is encountered, a try block
code execution is stopped and transferred down to the except block.

In addition to using an except block after the try block, you can also use the
finally block.

The code in the finally block will be executed regardless of whether an exception
occurs.

Code Example

Let’s write some code to see what happens when you not use error handling in your
program.

This program will ask the user to input a number between 1 and 10, and then print
the number.

number = int(raw_input("Enter a number between 1 - 10"))
print "you entered number", number

This program works perfectly fun as long as the user enters a number, but what
happens if the user puts in something else (like a string)?

Enter a number between 1 - 10
hello

You can see that the program throws us an error when we enter a string.


Traceback (most recent call last):
File "enter_number.py", line 1, in
number = int(raw_input("Enter a number between 1 - 10
"))
ValueError: invalid literal for int() with base 10: 'hello'

ValueError is an exception type. Let’s see how we can use exception handling to
fix the previous program

import sys
print "Lets fix the previous code with exception handling"

try:
number = int(raw_input("Enter a number between 1 - 10"))

except ValueError:
print "Err.. numbers only"
sys.exit()

print "you entered number", number

If we now run the program, and enter a string (instead of a number), we can see
that we get a different output.

Lets fix the previous code with exception handling
Enter a number between 1 - 10
hello
Err.. numbers only




Try … except … else clause

The else clause in a try , except statement must follow all except clauses, and is
useful for code that must be executed if the try clause does not raise an
exception.


try:
data = something_that_can_go_wrong

except IOError:
handle_the_exception_error

else:
doing_different_exception_handling
Exceptions in the else clause are not handled by the preceding except clauses.

Make sure that the else clause is run before the finally block.

Try … finally clause

The finally clause is optional. It is intended to define clean-up actions that
must be executed under all circumstances


try:
raise KeyboardInterrupt


finally:
print ‘Goodbye, world!’

Goodbye, world!
KeyboardInterrupt


A finally clause is always executed before leaving the try statement, whether an
exception has occurred or not.
Remember that if you don’t specify an exception type on the except line, it will
catch all exceptions, which is a bad idea, since it means your program will ignore
unexpected errors as well as ones which the except block is actually prepared to
handle.

More Reading

http://en.wikibooks.org/wiki/Python_Programming/Exceptions

http://www.linuxjournal.com/article/5821

http://docs.python.org/2/library/exceptions.html

http://docs.python.org/2/tutorial/errors.html

http://stackoverflow.com/questions/855759/python-try-else

The post Exception Handling in Python appeared first on PythonForBeginners.com.

]]>
5827