0% found this document useful (0 votes)
2 views5 pages

45 Textbook: Intro to Python Textbook | CodeHS

Chapter 4 of the Intro to Python textbook covers functions and exceptions in Python programming. It explains how to handle errors using try and except blocks to prevent program crashes due to exceptions like ValueError and ZeroDivisionError. The chapter includes exercises for practicing exception handling and creating functions that validate user input.

Uploaded by

xilifo7836
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views5 pages

45 Textbook: Intro to Python Textbook | CodeHS

Chapter 4 of the Intro to Python textbook covers functions and exceptions in Python programming. It explains how to handle errors using try and except blocks to prevent program crashes due to exceptions like ValueError and ZeroDivisionError. The chapter includes exercises for practicing exception handling and creating functions that validate user input.

Uploaded by

xilifo7836
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Intro to Python Textbook

(/textbook/intropython_textbook/) CHAPTER 4

1. Python and Console Interaction Functions and Exceptions


(/textbook/intropython_textbook/1)
2. Conditionals
(/textbook/intropython_textbook/2)
3. Looping
(/textbook/intropython_textbook/3)
4. Functions and Exceptions
(/textbook/intropython_textbook/4)
4.1 Functions
(/textbook/intropython_textbook/4.1) 4.5 Exceptions
4.2 Functions and Parameters
(/textbook/intropython_textbook/4.2)
 Exceptions
4.3 Namespaces in Functions
(/textbook/intropython_textbook/4.3) In this lesson, you’ll explore Python’s way of handling errors with
4.4 Functions and Return exceptions. You have practiced using programs that include input
Values from a user. Many times, the user is asked for a number.b But
(/textbook/intropython_textbook/4.4)
what if the user enters something that isn’t a number at all, like
4.5 Exceptions
“abcd”?
(/textbook/intropython_textbook/4.5)
Exceptions The int function will convert a string into an integer but only if the
Try and Except string really contains an integer! If it doesn’t, this will actually
Enter a Number
crash our program.
Check Your Understanding
1 my_number = int(input("Enter a number: "))
Exercise: Enter a Negative 2 print("Your number: " + str(my_number))

Error: Line 1
ValueError: invalid literal for int() with base 10: 'abcd' on line 1

What Python is actually doing is raising an exception and a


special type of exception at that - this is called a ValueError. You
can see the type of exception written in the error message.
Let’s look at another type of exception that can be raised. What
do you think is going to happen in this program?

1 numerator = int(input("Enter #: "))


2 denominator = int(input("Enter #: "))
3 if numerator % denominator == 0:
4 print("Divisible!")
5 else:
6 print("Not divisible.")

Did you spot the error? Python won’t let you divide by zero!
In this case, the exception is a ZeroDivisionError and it causes
the program to stop dead in its tracks.

Error: Line 3
ZeroDivisionError: integer division or modulo by zero on line 3
Exceptions are runtime errors in a program. By default, they stop
the program. Python has a way of letting programmers handle
exceptions which is known as try and except. These are
programming constructs that can be used to gracefully handle
exceptions so that a program can continue in spite of them.
In this module, you’ve seen a number of programs in which the
interpreter doesn’t move sequentially but rather jumps around to
different code blocks. Exceptions are another way in which the
interpreter can jump in a non-sequential manner.

 Try and Except


If you have some code that might raise an exception, you can put
it inside what’s called a try block. You then follow it with an
except block, which specifies the type of exception you want to
handle. That block contains code that will run if an exception is
raised.
In this program, the user is first asked for a numerator. Let’s say
they enter 10. Then, they are asked for a denominator. Let’s say
they enter 0. Next, Python enters the try block. Since the try
block is paired with an except block that can handle a
ZeroDivisionError , the interpreter will jump straight to the
except block if a ZeroDivisionError happens.

The interpreter checks if the numerator is divisible by the


denominator using the modulus operator % . Since it is not in this
case, a ZeroDivisionError exception is raised! The interpreter
skips the rest of the try block and goes straight to the exception
block. Then, the print in the exception block runs.

Try and Except


1 numerator = int(input("Enter #: "))
2 denominator = int(input("Enter #: ")) Output
3 try:
4 if numerator % denominator == 0:
5 print("Divisible!")
Run Stop
6 else:
7 print("Not divisible.")
8 except ZeroDivisionError:
9 print("Cannot divide by zero!")
10
11 print("All done!")
12
 Enter a Number
Let’s try to fix the first example as well with a try and except code
block. You’ll want to predict what type of exception will need to
be handled. In this program, a ValueError exception occurred.
Now, when the user enters letters and the ValueError exception
is raised, the interpreter can jump to the except block which
stops the program from crashing. The print executes, and the
program can continue as normal.
Run the program and explore with these guiding questions:
Try entering the following values. What do you expect to
happen and what is the result?

2
-4
.5
hi

Optional Challenge: Alter the program so that the user is


continually asked for their age until they enter a valid value.

 Check Your Understanding


 Exercise: Enter a Negative Number
In this exercise, you get to put together a bunch of the
knowledge you’ve acquired in this module!

Write a function called retrieve_negative_number that


repeatedly asks the user for a negative number. If the user enters
a positive number or zero, the function should tell them and
reprompt. If the user enters something that isn’t a number, the
function should also tell them and reprompt.
When the user finally enters a negative number, the function
should return this number.
Call this function to test it!
You will need:
A function definition, with no parameters.
A try and except block.
A while loop.
A return statement.
An if statement.
Hint: The return keyword is even more powerful than break . If
you are inside of a loop, and that loop is inside of a function,
break just breaks out of the loop. return , on the other hand,
breaks out of the entire function (and possibly also returns a
value).

Previous Section Next Section



Previous Section Next Section
 4.4 Functions and Return Va…
(/textbook/intropython_textbook/4.4)
5 Strings

You might also like