How to handle invalid argument in Python

3 Answers

0 votes
def import_data(name, save=False, check=False):
    if check and not save:
        raise ValueError("save must be True if check is True")

import_data("example", save=False, check=True) # Raises ValueError


'''
run:

ERROR!
Traceback (most recent call last):
  File "<main.py>", line 5, in <module>
  File "<main.py>", line 3, in import_data
ValueError: save must be True if check is True

'''

 



answered May 21, 2025 by avibootz
0 votes
def process_data(data):
    if not isinstance(data, list):
        raise TypeError("data must be a list")

process_data("a_string_not_a_list") # Raises TypeError


'''
run:

ERROR!
Traceback (most recent call last):
  File "<main.py>", line 5, in <module>
  File "<main.py>", line 3, in process_data
TypeError: data must be a list

'''

 



answered May 21, 2025 by avibootz
0 votes
def calculate_perimeter(length, width):
    if length < 0 or width < 0:
        raise ValueError("length or width cannot be negative")
        
calculate_perimeter(9, -4) # Raises TypeError


'''
run:

ERROR!
Traceback (most recent call last):
  File "<main.py>", line 5, in <module>
  File "<main.py>", line 3, in calculate_perimeter
ValueError: length or width cannot be negative

'''

 



answered May 21, 2025 by avibootz

Related questions

4 answers 304 views
4 answers 329 views
4 answers 271 views
4 answers 271 views
3 answers 227 views
6 answers 425 views
...