-3
def image_info(**o):
    print(type(o))
    print(o)
    {
        'image_title': 'my_cat',
        'image_id': 1234

    }

    info = (
        f"\"Image '{o['image_title']}'"
        f" has id {o['image_id']}"
    )
    return info


info = image_info(image_title='my_cat', image_id=1234)
print(info)

Here is my code. How to create a TypeError error, for the absence of image_title and image_id?

def image_info(**o):
    if 'image_title' + 'image_id':
        raise TypeError("ERROR")
    return (image_info)

  • 1
    What are you trying to do with `if 'image_title' + 'image_id':`? You realize that it's equivalent to `if 'image_titleimage_id':`, which in turn is equivalent to `if True:`. – Tom Karzes Jul 16 '23 at 12:57
  • Try `if not ('image_title' in o or 'image_id' in o):`. Also, I think it's better practice to raise a `ValueError` rather than a `TypeError`, but that might depend on the context of your program. – B Remmelzwaal Jul 16 '23 at 13:06
  • Please take the [tour]. If this is homework, please read [How to ask and answer homework questions](https://meta.stackoverflow.com/q/334822/4518341). See also [ask]. Your code doesn't make much sense, but I think you want to ask [How to check if a key is in a dictionary](/q/1602934/4518341), which has already been asked. Please start with your own research in the future. – wjandrea Jul 16 '23 at 23:20

1 Answers1

0

You want an if statement to check if either of the values is missing, and if so raise the TypeError. Something like this:

def image_info(**o):
    print(type(o))
    print(o)
    if 'image_title' not in o.keys() or 'image_id' not in o.keys():
        raise TypeError
    info = (
        f"\"Image '{o['image_title']}'"
        f" has id {o['image_id']}"
    )
    return info

Personally I would use ValueError or AttributeError but any should work fine.

Cmd858
  • 761
  • 1
  • 6
  • 10