Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Arrow up icon
GO TO TOP
Python 3 Data Visualization Using ChatGPT / GPT-4

You're reading from   Python 3 Data Visualization Using ChatGPT / GPT-4 Master Python Visualization Techniques with AI Integration

Arrow left icon
Product type Paperback
Published in Aug 2024
Publisher Mercury_Learning
ISBN-13 9781836649250
Length 314 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Authors (2):
Arrow left icon
Mercury Learning and Information Mercury Learning and Information
Author Profile Icon Mercury Learning and Information
Mercury Learning and Information
Oswald Campesato Oswald Campesato
Author Profile Icon Oswald Campesato
Oswald Campesato
Arrow right icon
View More author details
Toc

Table of Contents (10) Chapters Close

Preface
1. Chapter 1: Introduction to Python 2. Chapter 2: Introduction to NumPy FREE CHAPTER 3. Chapter 3: Pandas and Data Visualization 4. Chapter 4: Pandas and SQL 5. Chapter 5: Matplotlib and Visualization 6. Chapter 6: Seaborn for Data Visualization 7. Chapter 7: ChatGPT and GPT-4 8. Chapter 8: ChatGPT and Data Visualization 9. Index

EXCEPTION HANDLING IN PYTHON

Unlike JavaScript, you cannot add a number and a string in Python. However, you can detect an illegal operation using the try/except construct in Python, which is similar to the try/catch construct in languages such as JavaScript and Java.

An example of a try/except block is here:

try:
  x = 4
  y = 'abc'
  z = x + y
except:
  print('cannot add incompatible types:', x, y)

When you run the preceding code, the print() statement in the except code block is executed because the variables x and y have incompatible types.

Earlier in the chapter, you also saw that subtracting two strings throws an exception:

>>> 'a' - 'b'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'str' and 'str'

A simple way to handle this situation is to use a try/except block:

>>> try:
...  print('a' - 'b')
... except TypeError:
...  print('TypeError exception while trying to subtract two strings')
... except:
...  print('Exception while trying to subtract two strings')
...

The output from the preceding code block is here:

TypeError exception while trying to subtract two strings

As you can see, the preceding code block specifies the finer-grained exception called TypeError, followed by a generic except code block to handle all other exceptions that might occur during the execution of your Python code. This style is similar to the exception handling in Java code.

Listing 1.10 displays the content of exception1.py that illustrates how to handle various types of exceptions.

LISTING 1.10: exception1.py

import sys

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except IOError as err:
    print("I/O error: {0}".format(err))
except ValueError:
    print("Could not convert data to an integer.")
except:
    print("Unexpected error:", sys.exc_info()[0])
    raise

Listing 1.10 contains a try block followed by three except statements. If an error occurs in the try block, the first except statement is compared with the type of exception that occurred. If there is a match, then the subsequent print() statement is executed, and the program terminates. If not, a similar test is performed with the second except statement. If neither except statement matches the exception, the third except statement handles the exception, which involves printing a message and then “raising” an exception. Note that you can also specify multiple exception types in a single statement, as shown here:

except (NameError, RuntimeError, TypeError):
    print('One of three error types occurred')

The preceding code block is more compact, but you do not know which of the three error types occurred. Python allows you to define custom exceptions, but this topic is beyond the scope of this book.

lock icon The rest of the chapter is locked
Visually different images
CONTINUE READING
83
Tech Concepts
36
Programming languages
73
Tech Tools
Icon Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
Icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Icon 50+ new titles added per month and exclusive early access to books as they are being written.
Python 3 Data Visualization Using ChatGPT / GPT-4
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at R$50/month. Cancel anytime
Modal Close icon
Modal Close icon