Ошибка ValueError в Python возникает, когда функция получает аргумент правильного типа, но несоответствующее значение. Также не следует описывать ситуацию более точным исключением, например IndexError.
Содержание
- Пример
- Обработка исключения
- ValueError в функции
Пример
Вы получите ValueError с математическими операциями, такими как квадратный корень из отрицательного числа.
>>> import math >>> >>> math.sqrt(-10) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: math domain error >>>
Обработка исключения
Вот простой пример обработки исключения ValueError с помощью блока try-except.
import math x = int(input('Please enter a positive number:n')) try: print(f'Square Root of {x} is {math.sqrt(x)}') except ValueError as ve: print(f'You entered {x}, which is not a positive number.')
Вот результат работы программы с разными типами ввода.
Please enter a positive number: 16 Square Root of 16 is 4.0 Please enter a positive number: -10 You entered -10, which is not a positive number. Please enter a positive number: abc Traceback (most recent call last): File "/Users/pankaj/Documents/PycharmProjects/hello-world/journaldev/errors/valueerror_examples.py", line 11, in <module> x = int(input('Please enter a positive number:n')) ValueError: invalid literal for int() with base 10: 'abc'
Наша программа может вызывать ValueError в функциях int() и math.sqrt(). Итак, мы можем создать вложенный блок try-except для обработки обоих. Вот обновленный фрагмент, который позаботится обо всех сценариях ValueError.
import math try: x = int(input('Please enter a positive number:n')) try: print(f'Square Root of {x} is {math.sqrt(x)}') except ValueError as ve: print(f'You entered {x}, which is not a positive number.') except ValueError as ve: print('You are supposed to enter positive number.')
Вот простой пример, в котором мы поднимаем ValueError для входного аргумента правильного типа, но неподходящего значения.
import math def num_stats(x): if x is not int: raise TypeError('Work with Numbers Only') if x < 0: raise ValueError('Work with Positive Numbers Only') print(f'{x} square is {x * x}') print(f'{x} square root is {math.sqrt(x)}')
( 3 оценки, среднее 3.67 из 5 )
Помогаю в изучении Питона на примерах. Автор практических задач с детальным разбором их решений.
Here’s a revised version of your code which still works plus it illustrates how to raise a ValueError
the way you want. By-the-way, I think find_last()
, find_last_index()
, or something simlar would be a more descriptive name for this function. Adding to the possible confusion is the fact that Python already has a container object method named __contains__()
that does something a little different, membership-testing-wise.
def contains(char_string, char):
largest_index = -1
for i, ch in enumerate(char_string):
if ch == char:
largest_index = i
if largest_index > -1: # any found?
return largest_index # return index of last one
else:
raise ValueError('could not find {!r} in {!r}'.format(char, char_string))
print(contains('mississippi', 's')) # -> 6
print(contains('bababa', 'k')) # ->
Traceback (most recent call last):
File "how-to-raise-a-valueerror.py", line 15, in <module>
print(contains('bababa', 'k'))
File "how-to-raise-a-valueerror.py", line 12, in contains
raise ValueError('could not find {} in {}'.format(char, char_string))
ValueError: could not find 'k' in 'bababa'
Update — A substantially simpler way
Wow! Here’s a much more concise version—essentially a one-liner—that is also likely faster because it reverses (via [::-1]
) the string before doing a forward search through it for the first matching character and it does so using the fast built-in string index()
method. With respect to your actual question, a nice little bonus convenience that comes with using index()
is that it already raises a ValueError
when the character substring isn’t found, so nothing additional is required to make that happen.
Here it is along with a quick unit test:
def contains(char_string, char):
# Ending - 1 adjusts returned index to account for searching in reverse.
return len(char_string) - char_string[::-1].index(char) - 1
print(contains('mississippi', 's')) # -> 6
print(contains('bababa', 'k')) # ->
Traceback (most recent call last):
File "better-way-to-raise-a-valueerror.py", line 9, in <module>
print(contains('bababa', 'k'))
File "better-way-to-raise-a-valueerror", line 6, in contains
return len(char_string) - char_string[::-1].index(char) - 1
ValueError: substring not found
Обработка ошибок увеличивает отказоустойчивость кода, защищая его от потенциальных сбоев, которые могут привести к преждевременному завершению работы.
Прежде чем переходить к обсуждению того, почему обработка исключений так важна, и рассматривать встроенные в Python исключения, важно понять, что есть тонкая грань между понятиями ошибки и исключения.
Ошибку нельзя обработать, а исключения Python обрабатываются при выполнении программы. Ошибка может быть синтаксической, но существует и много видов исключений, которые возникают при выполнении и не останавливают программу сразу же. Ошибка может указывать на критические проблемы, которые приложение и не должно перехватывать, а исключения — состояния, которые стоит попробовать перехватить. Ошибки — вид непроверяемых и невозвратимых ошибок, таких как OutOfMemoryError
, которые не стоит пытаться обработать.
Обработка исключений делает код более отказоустойчивым и помогает предотвращать потенциальные проблемы, которые могут привести к преждевременной остановке выполнения. Представьте код, который готов к развертыванию, но все равно прекращает работу из-за исключения. Клиент такой не примет, поэтому стоит заранее обработать конкретные исключения, чтобы избежать неразберихи.
Ошибки могут быть разных видов:
- Синтаксические
- Недостаточно памяти
- Ошибки рекурсии
- Исключения
Разберем их по очереди.
Синтаксические ошибки (SyntaxError)
Синтаксические ошибки часто называют ошибками разбора. Они возникают, когда интерпретатор обнаруживает синтаксическую проблему в коде.
Рассмотрим на примере.
a = 8
b = 10
c = a b
File "", line 3
c = a b
^
SyntaxError: invalid syntax
Стрелка вверху указывает на место, где интерпретатор получил ошибку при попытке исполнения. Знак перед стрелкой указывает на причину проблемы. Для устранения таких фундаментальных ошибок Python будет делать большую часть работы за программиста, выводя название файла и номер строки, где была обнаружена ошибка.
Недостаточно памяти (OutofMemoryError)
Ошибки памяти чаще всего связаны с оперативной памятью компьютера и относятся к структуре данных под названием “Куча” (heap
). Если есть крупные объекты (или) ссылки на подобные, то с большой долей вероятности возникнет ошибка OutofMemory
. Она может появиться по нескольким причинам:
- Использование 32-битной архитектуры Python (максимальный объем выделенной памяти невысокий, между 2 и 4 ГБ);
- Загрузка файла большого размера;
- Запуск модели машинного обучения/глубокого обучения и много другое;
Обработать ошибку памяти можно с помощью обработки исключений — резервного исключения. Оно используется, когда у интерпретатора заканчивается память и он должен немедленно остановить текущее исполнение. В редких случаях Python вызывает OutofMemoryError
, позволяя скрипту каким-то образом перехватить самого себя, остановить ошибку памяти и восстановиться.
Но поскольку Python использует архитектуру управления памятью из языка C (функция malloc()
), не факт, что все процессы восстановятся — в некоторых случаях MemoryError
приведет к остановке. Следовательно, обрабатывать такие ошибки не рекомендуется, и это не считается хорошей практикой.
Ошибка рекурсии (RecursionError)
Эта ошибка связана со стеком и происходит при вызове функций. Как и предполагает название, ошибка рекурсии возникает, когда внутри друг друга исполняется много методов (один из которых — с бесконечной рекурсией), но это ограничено размером стека.
Все локальные переменные и методы размещаются в стеке. Для каждого вызова метода создается стековый кадр (фрейм), внутрь которого помещаются данные переменной или результат вызова метода. Когда исполнение метода завершается, его элемент удаляется.
Чтобы воспроизвести эту ошибку, определим функцию recursion
, которая будет рекурсивной — вызывать сама себя в бесконечном цикле. В результате появится ошибка StackOverflow
или ошибка рекурсии, потому что стековый кадр будет заполняться данными метода из каждого вызова, но они не будут освобождаться.
def recursion():
return recursion()
recursion()
---------------------------------------------------------------------------
RecursionError Traceback (most recent call last)
in
----> 1 recursion()
in recursion()
1 def recursion():
----> 2 return recursion()
... last 1 frames repeated, from the frame below ...
in recursion()
1 def recursion():
----> 2 return recursion()
RecursionError: maximum recursion depth exceeded
Ошибка отступа (IndentationError)
Эта ошибка похожа по духу на синтаксическую и является ее подвидом. Тем не менее она возникает только в случае проблем с отступами.
Пример:
for i in range(10):
print('Привет Мир!')
File "", line 2
print('Привет Мир!')
^
IndentationError: expected an indented block
Исключения
Даже если синтаксис в инструкции или само выражение верны, они все равно могут вызывать ошибки при исполнении. Исключения Python — это ошибки, обнаруживаемые при исполнении, но не являющиеся критическими. Скоро вы узнаете, как справляться с ними в программах Python. Объект исключения создается при вызове исключения Python. Если скрипт не обрабатывает исключение явно, программа будет остановлена принудительно.
Программы обычно не обрабатывают исключения, что приводит к подобным сообщениям об ошибке:
Ошибка типа (TypeError)
a = 2
b = 'PythonRu'
a + b
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
in
1 a = 2
2 b = 'PythonRu'
----> 3 a + b
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Ошибка деления на ноль (ZeroDivisionError)
10 / 0
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
in
----> 1 10 / 0
ZeroDivisionError: division by zero
Есть разные типы исключений в Python и их тип выводится в сообщении: вверху примеры TypeError
и ZeroDivisionError
. Обе строки в сообщениях об ошибке представляют собой имена встроенных исключений Python.
Оставшаяся часть строки с ошибкой предлагает подробности о причине ошибки на основе ее типа.
Теперь рассмотрим встроенные исключения Python.
Встроенные исключения
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StopAsyncIteration
+-- ArithmeticError
| +-- FloatingPointError
| +-- OverflowError
| +-- ZeroDivisionError
+-- AssertionError
+-- AttributeError
+-- BufferError
+-- EOFError
+-- ImportError
| +-- ModuleNotFoundError
+-- LookupError
| +-- IndexError
| +-- KeyError
+-- MemoryError
+-- NameError
| +-- UnboundLocalError
+-- OSError
| +-- BlockingIOError
| +-- ChildProcessError
| +-- ConnectionError
| | +-- BrokenPipeError
| | +-- ConnectionAbortedError
| | +-- ConnectionRefusedError
| | +-- ConnectionResetError
| +-- FileExistsError
| +-- FileNotFoundError
| +-- InterruptedError
| +-- IsADirectoryError
| +-- NotADirectoryError
| +-- PermissionError
| +-- ProcessLookupError
| +-- TimeoutError
+-- ReferenceError
+-- RuntimeError
| +-- NotImplementedError
| +-- RecursionError
+-- SyntaxError
| +-- IndentationError
| +-- TabError
+-- SystemError
+-- TypeError
+-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
+-- Warning
+-- DeprecationWarning
+-- PendingDeprecationWarning
+-- RuntimeWarning
+-- SyntaxWarning
+-- UserWarning
+-- FutureWarning
+-- ImportWarning
+-- UnicodeWarning
+-- BytesWarning
+-- ResourceWarning
Прежде чем переходить к разбору встроенных исключений быстро вспомним 4 основных компонента обработки исключения, как показано на этой схеме.
Try
: он запускает блок кода, в котором ожидается ошибка.Except
: здесь определяется тип исключения, который ожидается в блокеtry
(встроенный или созданный).Else
: если исключений нет, тогда исполняется этот блок (его можно воспринимать как средство для запуска кода в том случае, если ожидается, что часть кода приведет к исключению).Finally
: вне зависимости от того, будет ли исключение или нет, этот блок кода исполняется всегда.
В следующем разделе руководства больше узнаете об общих типах исключений и научитесь обрабатывать их с помощью инструмента обработки исключения.
Ошибка прерывания с клавиатуры (KeyboardInterrupt)
Исключение KeyboardInterrupt
вызывается при попытке остановить программу с помощью сочетания Ctrl + C
или Ctrl + Z
в командной строке или ядре в Jupyter Notebook. Иногда это происходит неумышленно и подобная обработка поможет избежать подобных ситуаций.
В примере ниже если запустить ячейку и прервать ядро, программа вызовет исключение KeyboardInterrupt
. Теперь обработаем исключение KeyboardInterrupt
.
try:
inp = input()
print('Нажмите Ctrl+C и прервите Kernel:')
except KeyboardInterrupt:
print('Исключение KeyboardInterrupt')
else:
print('Исключений не произошло')
Исключение KeyboardInterrupt
Стандартные ошибки (StandardError)
Рассмотрим некоторые базовые ошибки в программировании.
Арифметические ошибки (ArithmeticError)
- Ошибка деления на ноль (Zero Division);
- Ошибка переполнения (OverFlow);
- Ошибка плавающей точки (Floating Point);
Все перечисленные выше исключения относятся к классу Arithmetic
и вызываются при ошибках в арифметических операциях.
Деление на ноль (ZeroDivisionError)
Когда делитель (второй аргумент операции деления) или знаменатель равны нулю, тогда результатом будет ошибка деления на ноль.
try:
a = 100 / 0
print(a)
except ZeroDivisionError:
print("Исключение ZeroDivisionError." )
else:
print("Успех, нет ошибок!")
Исключение ZeroDivisionError.
Переполнение (OverflowError)
Ошибка переполнение вызывается, когда результат операции выходил за пределы диапазона. Она характерна для целых чисел вне диапазона.
try:
import math
print(math.exp(1000))
except OverflowError:
print("Исключение OverFlow.")
else:
print("Успех, нет ошибок!")
Исключение OverFlow.
Ошибка утверждения (AssertionError)
Когда инструкция утверждения не верна, вызывается ошибка утверждения.
Рассмотрим пример. Предположим, есть две переменные: a
и b
. Их нужно сравнить. Чтобы проверить, равны ли они, необходимо использовать ключевое слово assert
, что приведет к вызову исключения Assertion
в том случае, если выражение будет ложным.
try:
a = 100
b = "PythonRu"
assert a == b
except AssertionError:
print("Исключение AssertionError.")
else:
print("Успех, нет ошибок!")
Исключение AssertionError.
Ошибка атрибута (AttributeError)
При попытке сослаться на несуществующий атрибут программа вернет ошибку атрибута. В следующем примере можно увидеть, что у объекта класса Attributes
нет атрибута с именем attribute
.
class Attributes(obj):
a = 2
print(a)
try:
obj = Attributes()
print(obj.attribute)
except AttributeError:
print("Исключение AttributeError.")
2
Исключение AttributeError.
Ошибка импорта (ModuleNotFoundError)
Ошибка импорта вызывается при попытке импортировать несуществующий (или неспособный загрузиться) модуль в стандартном пути или даже при допущенной ошибке в имени.
import nibabel
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
in
----> 1 import nibabel
ModuleNotFoundError: No module named 'nibabel'
Ошибка поиска (LookupError)
LockupError
выступает базовым классом для исключений, которые происходят, когда key
или index
используются для связывания или последовательность списка/словаря неверна или не существует.
Здесь есть два вида исключений:
- Ошибка индекса (
IndexError
); - Ошибка ключа (
KeyError
);
Ошибка ключа
Если ключа, к которому нужно получить доступ, не оказывается в словаре, вызывается исключение KeyError
.
try:
a = {1:'a', 2:'b', 3:'c'}
print(a[4])
except LookupError:
print("Исключение KeyError.")
else:
print("Успех, нет ошибок!")
Исключение KeyError.
Ошибка индекса
Если пытаться получить доступ к индексу (последовательности) списка, которого не существует в этом списке или находится вне его диапазона, будет вызвана ошибка индекса (IndexError: list index out of range python).
try:
a = ['a', 'b', 'c']
print(a[4])
except LookupError:
print("Исключение IndexError, индекс списка вне диапазона.")
else:
print("Успех, нет ошибок!")
Исключение IndexError, индекс списка вне диапазона.
Ошибка памяти (MemoryError)
Как уже упоминалось, ошибка памяти вызывается, когда операции не хватает памяти для выполнения.
Ошибка имени (NameError)
Ошибка имени возникает, когда локальное или глобальное имя не находится.
В следующем примере переменная ans
не определена. Результатом будет ошибка NameError
.
try:
print(ans)
except NameError:
print("NameError: переменная 'ans' не определена")
else:
print("Успех, нет ошибок!")
NameError: переменная 'ans' не определена
Ошибка выполнения (Runtime Error)
Ошибка «NotImplementedError»
Ошибка выполнения служит базовым классом для ошибки NotImplemented
. Абстрактные методы определенного пользователем класса вызывают это исключение, когда производные методы перезаписывают оригинальный.
class BaseClass(object):
"""Опередляем класс"""
def __init__(self):
super(BaseClass, self).__init__()
def do_something(self):
# функция ничего не делает
raise NotImplementedError(self.__class__.__name__ + '.do_something')
class SubClass(BaseClass):
"""Реализует функцию"""
def do_something(self):
# действительно что-то делает
print(self.__class__.__name__ + ' что-то делает!')
SubClass().do_something()
BaseClass().do_something()
SubClass что-то делает!
---------------------------------------------------------------------------
NotImplementedError Traceback (most recent call last)
in
14
15 SubClass().do_something()
---> 16 BaseClass().do_something()
in do_something(self)
5 def do_something(self):
6 # функция ничего не делает
----> 7 raise NotImplementedError(self.__class__.__name__ + '.do_something')
8
9 class SubClass(BaseClass):
NotImplementedError: BaseClass.do_something
Ошибка типа (TypeError)
Ошибка типа вызывается при попытке объединить два несовместимых операнда или объекта.
В примере ниже целое число пытаются добавить к строке, что приводит к ошибке типа.
try:
a = 5
b = "PythonRu"
c = a + b
except TypeError:
print('Исключение TypeError')
else:
print('Успех, нет ошибок!')
Исключение TypeError
Ошибка значения (ValueError)
Ошибка значения вызывается, когда встроенная операция или функция получают аргумент с корректным типом, но недопустимым значением.
В этом примере встроенная операция float
получат аргумент, представляющий собой последовательность символов (значение), что является недопустимым значением для типа: число с плавающей точкой.
try:
print(float('PythonRu'))
except ValueError:
print('ValueError: не удалось преобразовать строку в float: 'PythonRu'')
else:
print('Успех, нет ошибок!')
ValueError: не удалось преобразовать строку в float: 'PythonRu'
Пользовательские исключения в Python
В Python есть много встроенных исключений для использования в программе. Но иногда нужно создавать собственные со своими сообщениями для конкретных целей.
Это можно сделать, создав новый класс, который будет наследовать из класса Exception
в Python.
class UnAcceptedValueError(Exception):
def __init__(self, data):
self.data = data
def __str__(self):
return repr(self.data)
Total_Marks = int(input("Введите общее количество баллов: "))
try:
Num_of_Sections = int(input("Введите количество разделов: "))
if(Num_of_Sections < 1):
raise UnAcceptedValueError("Количество секций не может быть меньше 1")
except UnAcceptedValueError as e:
print("Полученная ошибка:", e.data)
Введите общее количество баллов: 10
Введите количество разделов: 0
Полученная ошибка: Количество секций не может быть меньше 1
В предыдущем примере если ввести что-либо меньше 1, будет вызвано исключение. Многие стандартные исключения имеют собственные исключения, которые вызываются при возникновении проблем в работе их функций.
Недостатки обработки исключений в Python
У использования исключений есть свои побочные эффекты, как, например, то, что программы с блоками try-except работают медленнее, а количество кода возрастает.
Дальше пример, где модуль Python timeit
используется для проверки времени исполнения 2 разных инструкций. В stmt1
для обработки ZeroDivisionError
используется try-except, а в stmt2
— if
. Затем они выполняются 10000 раз с переменной a=0
. Суть в том, чтобы показать разницу во времени исполнения инструкций. Так, stmt1
с обработкой исключений занимает больше времени чем stmt2
, который просто проверяет значение и не делает ничего, если условие не выполнено.
Поэтому стоит ограничить использование обработки исключений в Python и применять его в редких случаях. Например, когда вы не уверены, что будет вводом: целое или число с плавающей точкой, или не уверены, существует ли файл, который нужно открыть.
import timeit
setup="a=0"
stmt1 = '''
try:
b=10/a
except ZeroDivisionError:
pass'''
stmt2 = '''
if a!=0:
b=10/a'''
print("time=",timeit.timeit(stmt1,setup,number=10000))
print("time=",timeit.timeit(stmt2,setup,number=10000))
time= 0.003897680000136461
time= 0.0002797570000439009
Выводы!
Как вы могли увидеть, обработка исключений помогает прервать типичный поток программы с помощью специального механизма, который делает код более отказоустойчивым.
Обработка исключений — один из основных факторов, который делает код готовым к развертыванию. Это простая концепция, построенная всего на 4 блоках: try
выискивает исключения, а except
их обрабатывает.
Очень важно поупражняться в их использовании, чтобы сделать свой код более отказоустойчивым.
One of the trickier parts of designing and writing code remains to be exception handling. Poor exception handling causes a number of issues, including:
- Poorly designed code that is challenging to test, understand and refactor.
- It is challenging to identify the primary cause of errors.
- Inadequate logging.
- Poor monitoring and understanding.
These issues not only make it challenging to restructure and add new features to the code but also make it difficult to manage the application in real-world settings. One of those exceptions is ValueError and we will discuss in this article what ValueError is and how to fix it. Let us go through everything about ValueError in Python.
What is ValueError in Python?
An exception is referred to as occurring during the execution of any script. In Python, exception handling is done with the try-except block. Python has a large number of built-in exceptions to deal with typical problems, like IndexError, KeyError, NameError, TypeError, ValueError, etc. Python’s ValueError occurs when a function is called with the proper argument type but with the wrong value. This kind of mistake frequently occurs during mathematical calculations, when a ValueError Python arises. We will discuss the process to handle it in Python.
When a user calls a function with an invalid value but a valid argument, Python raises ValueError. Even though the value is the correct argument, it typically happens in mathematical processes that call for a specific kind of value. When an object is given the incorrect value, the Python ValueError is raised. This may occur if the value is incorrect for the intended operation or if the value is missing altogether. A ValueError is raised, for instance, if a negative integer is supplied to a square root operation.
ValueError example 1:
Code
a=10
b=int('valueerror')
print(b)
Output
Explanation
The output shown after running the aforementioned script is as follows. The output indicates that the ValueError occurred at line 2, where the string «valueerror» was converted using the int() function.
ValueError example 2:
Here is an illustration of a Python ValueError that occurs while attempting to square the root a negative number:
Code
import math
a=-10
print(math.sqrt(a))
Output
Explanation
The math.sqrt() function is given a negative integer in the example above. Running the aforementioned code results in a ValueError since the function expects a positive number.
Before moving on to the topic of how to fix it let us see one exciting topic in ValueError.
ValueError — Unpacking
Retrieving values from a list and assigning them to a list of variables is referred to as unpacking. When the number of variables and values don’t match, this error occurs. The inequality prevents Python from knowing which values to assign to which variables. This results in the ValueError: too many values to unpack the problem.
Now let us discuss two problems of the exception mentioned above and how to solve them:
First problem: Occurs when list unpacking
Imagine you have a list of fruits and you want to give a few variables the values from the list.
This procedure can be imitated below:
>>fruits = ['Apple', 'Mango', 'orange']
>>fruits_1, fruits_2 = fruits
Output
Because there are three values in the list but we only assign them to two variables, we are receiving this traceback.
Python is therefore unable to determine which fruit we prefer — Apple, Mango, or Orange. We can resolve this quickly:
>>fruits = ['Apple', 'Mango', 'Orange']
>>fruits_1, fruits_2,fruits_3 = fruits
fruits_3 makes this section of code function properly because we now have an equal number of variables and list values.
Apple, Mango, and Orange are now assigned to fruits_1, fruits_2, and fruits_ 3, respectively, via this change’s communication to Python.
Second Problem: Unpacking when a return statement is used in a function. Consider that we wish to create a function that computes the values of variables — variable 1 and variable 2, then returns the results for usage elsewhere in our program.
Here is a function that specifically provides us with the sum, and difference of two variables:
Code
def computes(x, y):
sum = x + y
diff= x - y
mul=x*y
return sum, diff, mul
result_1, result_2,result_3 = computes(7, 5)
Output
The function returns three variables, but we only requested two, hence this error happens.
Python doesn’t know which two variables we’re looking for, therefore the value error informs us that we’ve made a mistake rather than presuming and giving us simply two values (which can destroy our program later if they’re the incorrect values).
You have a few choices for how to effectively capture the function’s output. The below improvement includes methods to avoid this problem.
def computes(x, y):
sum = x + y
diff= x - y
mul=x*y
return sum, diff,mul
result_1, result_2,result_3 = computes(7, 5)
print(f"Option 1: sum={result_1}, diff={result_2}, mul={result_3}")
The program can now run without errors because Python can now directly link the return of sum, product, and difference to result 1, result 2, and result 3, respectively.
Another option for improvement to the above program can also include just underscore instead of result_3 and return the output with any variables assigned.
In the output, while printing you can also use just results instead of separately declaring result_1,result_2, and result_3 and extracting the result like you will get the element in the array.
Most common uses of ValueError exception
Example-1: Handle the ValueError for incorrect data
The script below should be placed in a Python file to collect the user’s age value. The try block will throw the ValueError exception and output the custom error message if the user enters a non-numeric value for the age field. If the user’s actual age is obtained, the message will be printed using that age value.
Code
try:
age = int(input("Enter your age: "))
if age >= 18 :
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
except ValueError:
print("Only alphabetics are acceptable. Please type your number as numeric characters")
Output
As the above problem is a basic program for user to check if he is eligible to vote or not. So there is a possibility for the user to type non-numeric values as you can see in the above screenshot.
Example-2: Usage of the ValueError Python inside and outside of the function
The following Python program will demonstrate how ValueError is used both inside and outside of the function. Here, it has been defined to use the sign() function to determine whether an integer is positive or negative. When an invalid argument value is supplied to the process, the function will show the ValueError. The ValueError provided by the function will be caught by the try-except block, which will then provide an error message.
Code
def sign(n):
try:
value = int(n)
#Checking the number is positive or negative
if value> 0:
print("The number is positive")
else:
print("The number is negative")
except ValueError:
print("Error occurred inside the function: ", "Please Correct") raise
try:
#Take the input from the user
number = input("Enter a number a value: ")
#Calling the function
sign(number)
except ValueError:
print("Error occurred outside the function: ", "Please correct")
Output:
The above problems explains whether the value entered by the user is a positive or negative number. If there is any input other than a number, it will show an exception inside and outside of the function.
Other uses of ValueError
Example 1: File reading IO
The following Python script will open a file for reading and print the contents of the file. Create a Python file. An IOError will be shown if the filename used in the script is not reachable, and a ValueError will be generated if the file includes any alphabetic characters.
Example 2: Command line argument
The following Python script will take a number from the value of the command-line argument. If a numeric value is provided in the command-line argument, the specific message will be written; if not, a ValueError will be issued and an error message will be displayed.
How ValueError Python is fixed
A try-except block can be used in Python programs to fix ValueError. The try block should contain the lines of code that can show the ValueError, and the except block should have the code to catch and handle the problem.
Code
import math
try:
math.sqrt(-10)
except ValueError:
print('Positive number is required for square root operation. So please change the number')
Output
The try-except block is used in this case to check for the ValueError. The except block in the code above detects the ValueError and handles it, resulting in the output shown above.
Conclusion
It is always for a software developer to handle any exceptions that occurs in a program. To be a successful developer it is always important to be a good tester, debugger, and compiler. So we have seen what ValueError is in Python and how to fix it using try and except.
The value in Python is the data that is stored inside a particular item. A ValueError in Python indicates that there is a problem with the program typed that you tried to assign the incentive to. This should not be confused with Python types. Therefore, when a proper and valid argument is received, Python ValueError occurs; however, it is not really worth it. Additionally, the situation shouldn’t be described by a more precise exception, like IndexError.
Overview
As you already know, an exception happens when an error occurs during the execution of a script. Python’s try-except block is used to manage exceptions. Python has many built-in exceptions to handle common failures, such as IndexError, KeyError, NameError, TypeError, Python ValueError, and so on. In Python, a ValueError is a rather straightforward concept. A Python ValueError is thrown when you assign the incorrect value to an object. That means Python ValueError is raised when a function receives an argument of the correct type but an inappropriate value.
What is Python ValueError?
In Python, a ValueError occurs when a correct argument type but an incorrect value is supplied to a function. This type of inaccuracy is most common in mathematical operations. When the ValueError Python arises and how to handle it in Python is demonstrated in this article.
Python won’t accept your code when you have the same type of object but the incorrect value. Let’s understand this by taking a real-life example. Suppose that you are trying to place a 7-inch phone into a 6-inch phone box. Did you see the problem? The phone will not fix in the box. That is a Python ValueError in a nutshell.
Make sure you don’t mix up a Python ValueError and TypeError. A TypeError, as opposed to a ValueError, is raised when an operation is performed that uses an incorrect or unsupported object type. For example, consider our previous example, if you are trying to fit a TV in a phone box, then Python is smart enough to know that these two types do not match.
Let’s consider a simple example to understand the Python ValueError.
Here is the output of the program.
As shown in the above code snippet, you will get a python ValueError with the mathematical operations, as you can see there is no such thing as the square root of a negative number, therefore the python raises a ValueError.
How Does Python ValueError Work?
As discussed above, Value Error in python occurs when a correct argument type but an incorrect value is supplied to a function. There are many reasons you might see the Python ValueError pop-ups and these are mentioned below:
- Trying to “unpack” more values than you have
- When you attempt to operate on a value that does not exist.
- The value is impossible (For example, finding the root of a negative number will result in a ValueError exception)
Steps to Avoid Python ValueError
There are various steps to avoid the Python ValueError. You can handle the ValueError using the try and except block. When the errors arise from an invalid output, in that case, the try and except block is very much useful to handle the Python ValueError that you’ll study in the next section.
You can also use the raise keyword to avoid the ValueError.
Handling Python ValueError
Let’s see how you can handle the Python ValueError using the try and except block in python.
In the below example, the main part of the code is in between the try and except block. The user is asked to enter the present age. If the ValueError has occurred for the input value, then the except block will be executed.
Here is the output of the program with different types of input.
Value Error Python Examples
Let’s take some more examples to understand how you can handle the Python ValueError.
Example:
In the below example, a classic example of obtaining a square root is discussed. We have used the try and except block to handle the error.
Here is the output of the program with different types of input.
Example:
Now, let’s take another example in which the Python ValueError is handled without the try-except block and by using the raise keyword inside the function.
Here is the output of the program with different types of input.
Conclusion
- A Python ValueError is thrown when you assign the incorrect value to an object.
- In Python, a ValueError occurs when a correct argument type but an incorrect value is supplied to a function. This type of inaccuracy is most common in mathematical operations.
- A TypeError, as opposed to a ValueError, is raised when an operation is performed that is using an incorrect or unsupported object type.
- You can handle the ValueError using the try and except block.
Read More:
- sqrt() function in python.
- type() in Python.