Lecture 3 Part 1 - CS50's Introduction To Programming With Python
Lecture 3 Part 1 - CS50's Introduction To Programming With Python
Donate (https://cs50.harvard.edu/donate)
Lecture 3
Exceptions
Runtime Errors
try
else
Creating a Function to Get an Integer
pass
Summing Up
Exceptions
Exceptions are things that go wrong within our coding.
https://cs50.harvard.edu/python/2022/notes/3/ 1/8
11/18/24, 4:18 AM Lecture 3 - CS50's Introduction to Programming with Python
In our text editor, type code hello.py to create a new file. Type as follows (with the intentional errors included):
print("hello, world)
Runtime Errors
Runtime errors refer to those created by unexpected behavior within your code. For example, perhaps you intended for a user to
input a number, but they input a character instead. Your program may throw an error because of this unexpected input from the
user.
In your terminal window, run code number.py . Code as follows in your text editor:
x = int(input("What's x? "))
print(f"x is {x}")
Notice that by including the f , we tell Python to interpolate what is in the curly braces as the value of x . Further, testing out
your code, you can imagine how one could easily type in a string or a character instead of a number. Even still, a user could type
nothing at all – simply hitting the enter key.
As programmers, we should be defensive to ensure that our users are entering what we expected. We might consider “corner
cases” such as -1 , 0 , or cat .
If we run this program and type in “cat”, we’ll suddenly see ValueError: invalid literal for int() with base 10: 'cat'
Essentially, the Python interpreter does not like that we passed “cat” to the int function.
An effective strategy to fix this potential error would be to create “error handling” to ensure the user behaves as we intend.
You can learn more in Python’s documentation of Errors and Exceptions (https://docs.python.org/3/tutorial/errors.html).
https://cs50.harvard.edu/python/2022/notes/3/ 2/8