0% found this document useful (0 votes)
39 views6 pages

CS50 Lecture 3: Python Error Handling

The document summarizes key concepts from Lecture 3 of CS50's Introduction to Programming with Python course. It discusses exceptions, runtime errors, and how to handle errors using try/except blocks. It provides examples of getting integer input from the user, validating the input, and re-prompting using a while loop if an error occurs. It also introduces functions to abstract away repeated code like getting integer input.

Uploaded by

rahmifitria0306
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)
39 views6 pages

CS50 Lecture 3: Python Error Handling

The document summarizes key concepts from Lecture 3 of CS50's Introduction to Programming with Python course. It discusses exceptions, runtime errors, and how to handle errors using try/except blocks. It provides examples of getting integer input from the user, validating the input, and re-prompting using a while loop if an error occurs. It also introduces functions to abstract away repeated code like getting integer input.

Uploaded by

rahmifitria0306
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

12/6/23, 11:04 AM Lecture 3 - CS50's Introduction to Programming with Python

CS50’s Introduction to Programming with Python


OpenCourseWare

Donate  ([Link]

David J. Malan ([Link]


malan@[Link]
 ([Link]  ([Link] 
([Link]  ([Link]
 ([Link] 
([Link]  ([Link]

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.
 In our text editor, type code [Link] to create a new file. Type as follows (with the
intentional errors included):

print("hello, world)

Notice that we intentionally left out a quotation mark.


 Running python [Link] in our terminal window, an error is outputted. The compiler
states that it is a “syntax error.”” Syntax errors are those that require you to double-check
that you typed in your code correction.
 You can learn more in Python’s documentation of Errors and Exceptions
([Link]

[Link] 1/6
12/6/23, 11:04 AM Lecture 3 - CS50's Introduction to Programming with Python

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 [Link] . 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 print 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
([Link]

try

 In Python try and except are ways of testing out user input before something goes
wrong. Modify your code as follows:

try:
x = int(input("What's x?"))
print(f"x is {x}")
except ValueError:
print("x is not an integer")

Notice how, running this code, inputting 50 will be accepted. However, typing in cat will
produce an error visible to the user, instructing them why their input was not accepted.
 This is still not the best way to implement this code. Notice that we are trying to do two
lines of code. For best practice, we should only try the fewest lines of code possible that
we are concerned could fail. Adjust your code as follows:

try:
x = int(input("What's x?"))
except ValueError:

[Link] 2/6
12/6/23, 11:04 AM Lecture 3 - CS50's Introduction to Programming with Python
print("x is not an integer")

print(f"x is {x}")

Notice that while this accomplishes our goal of trying as few lines as possible, we now
face a new error! We face a NameError where x is not defined . Look at this code and
consider: Why is x not defined in some cases?
 Indeed, if you examine the order of operations in x = int(input("What's x?")) , working
right to left, it could take an incorrectly inputted character and attempt to assign it as an
integer. If this fails, the assignment of the value of x never occurs. Therefore, there is no x
to print on our final line of code.

else

 It turns out that there is another way to implement try that could catch errors of this
nature.
 Adjust your code as follows:

try:
x = int(input("What's x?"))
except ValueError:
print("x is not an integer")
else:
print(f"x is {x}")

Notice that if no exception occurs, it will then run the block of code within else . Running
python [Link] and supplying 50 , you’ll notice that the result will be printed. Trying
again, this time supplying cat , you’ll notice that the program now catches the error.
 Considering improving our code, notice that we are being a bit rude to our user. If our user
does not cooperate, we currently simply end our program. Consider how we can use a loop
to prompt the user for x and if they don’t prompt again! Improve your code as follows:

while True:
try:
x = int(input("What's x?"))
except ValueError:
print("x is not an integer")
else:
break

print(f"x is {x}")

Notice that while True will loop forever. If the user succeeds in supplying the correct
input, we can break from the loop and then print the output. Now, a user that inputs
something incorrectly will be asked for input again.

Creating a Function to Get an Integer


[Link] 3/6
12/6/23, 11:04 AM Lecture 3 - CS50's Introduction to Programming with Python

 Surely, there are many times that we would want to get an integer from our user. Modify
your code as follows:

def main():
x = get_int()
print(f"x is {x}")

def get_int():
while True:
try:
x = int(input("What's x?"))
except ValueError:
print("x is not an integer")
else:
break
return x

main()

Notice that we are manifesting many great properties. First, we have abstracted away the
ability to get an integer. Now, this whole program boils down to the first three lines of the
program.
 Even still, we can improve this program. Consider what else you could do to improve this
program. Modify your code as follows:

def main():
x = get_int()
print(f"x is {x}")

def get_int():
while True:
try:
x = int(input("What's x?"))
except ValueError:
print("x is not an integer")
else:
return x

main()

Notice that return will not only break you out of a loop, but it will also return a value.
 Some people may argue you could do the following:

def main():
x = get_int()
print(f"x is {x}")

def get_int():
while True:
try:

[Link] 4/6
12/6/23, 11:04 AM Lecture 3 - CS50's Introduction to Programming with Python
return int(input("What's x?"))
except ValueError:
print("x is not an integer")

main()

Notice this does the same thing as the previous iteration of our code, simply with fewer
lines.

pass

 We can make it such that our code does not warn our user, but simply re-asks them our
prompting question by modifying our code as follows:

def main():
x = get_int()
print(f"x is {x}")

def get_int():
while True:
try:
return int(input("What's x?"))
except ValueError:
pass

main()

Notice that our code will still function but will not repeatedly inform the user of their
error. In some cases, you’ll want to be very clear to the user what error is being produced.
Other times, you might decide that you simply want to ask them for input again.
 One final refinement that could improve the implementation of this get_int function.
Right now, notice that we are relying currently upon the honor system that the x is in
both the main and get_int functions. We probably want to pass in a prompt that the
user sees when asked for input. Modify your code as follows.

def main():
x = get_int("What's x? ")
print(f"x is {x}")

def get_int(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
pass

main()

[Link] 5/6
12/6/23, 11:04 AM Lecture 3 - CS50's Introduction to Programming with Python

 You can learn more in Python’s documentation of pass


([Link]

Summing Up
Errors are inevitable in your code. However, you have the opportunity to use what was learned
today to help prevent these errors. In this lecture, you learned about…

 Exceptions
 Value Errors
 Runtime Errors
 try
 else
 pass

[Link] 6/6

Common questions

Powered by AI

Defensive programming is a design philosophy aimed at ensuring the software continues to function under unforeseen conditions, such as incorrect input or unexpected user behavior. In the program examples, defensive programming is applied by including exception handling with try-except blocks to anticipate and handle potential input errors like non-numeric values. This prevents the program from crashing due to invalid user inputs and prompts users repeatedly until a valid input is provided, thereby robustly guarding against user errors .

The code initially attempted to take an integer input from the user and used a try-except block to handle input errors. Iteratively, it refined the error handling by reducing the number of lines within the try block to only those that could raise an exception. Next, it introduced a while loop to repeatedly prompt the user until a valid integer was entered. Finally, the introduction of a get_int function abstracted repeated integer validation tasks, improving modularity and reuse. Each iteration aimed to make the code more efficient and user-friendly by progressively addressing edge cases and improving the code's structure .

To repeatedly prompt users until valid input was received, a while True loop was employed, paired with try-except blocks for error handling. If the input failed to meet criteria (e.g., not being an integer), the loop continued, repeatedly prompting the user. This strategy benefits by ensuring that the program remains in a request loop until a valid integer is entered, preventing the program from proceeding with flawed or incomplete data and enhancing robustness against incorrect user inputs .

Returning values from functions is crucial as it allows a function to output a result that can be used elsewhere in the program. In the context of the get_int function, returning the integer value ensures that the input validation is complete before reporting the result back to the main program. This separation of concern allows for cleaner code, enhances the readability, and promotes reuse of the get_int function in different contexts across the program, making the program more modular .

In Python, the order of operations dictates that all expressions on the right-hand side of an assignment are evaluated before the assignment occurs. In the example provided, if an invalid input causes an exception before the assignment is complete, the variable x is never defined, leading to a NameError when referenced. This highlights that a variable's scope and existence depend on the successful completion of its initialization process .

Syntax errors occur when the language interpreter fails to parse a line of source code because the code does not follow the correct structure or syntax rules, such as missing quotation marks around a string. These errors are usually caught at the time of code compilation. In contrast, runtime errors happen during the execution of a program, often due to incorrect inputs or unexpected program flow, such as trying to convert a non-numeric input to an integer .

The 'else' clause in try-except blocks is executed if the try block does not raise an exception. This feature enhances exception handling by clearly separating the code segments which are meant to run only in the absence of exceptions. Thus, it helps in keeping exception code strictly confined to handling errors while allowing normal operation flow to be explicitly stated, which can improve code readability and maintainability .

Using 'pass' within a try-except block effectively silences errors, allowing the program to continue execution silently when an exception occurs. This approach can minimize user feedback and may lead to user confusion about input errors, potentially resulting in poor user experience. In contrast, providing explicit feedback helps guide users to correct their input, enhancing interaction quality. However, 'pass' can be suitable in contexts where user error messages are undesirable or distracting, indicating a trade-off between explicit communication and seamless execution flow .

Handling exceptions is crucial in programming to prevent the program from crashing and to provide a mechanism for coping with error conditions that may arise during execution. Python’s try-except construct allows developers to isolate portions of code that might cause errors and handle them gracefully. This construct enables the program to recover from unexpected conditions by redirecting the flow of execution through alternative paths rather than terminating abruptly .

The final implementation of the get_int function included passing a prompt argument to customize the input request shown to the user. This improvement enhances user experience by providing users with clear and specific request messages directly tailored for each instance where an integer input is needed. It promotes modular and flexible function design, allowing the same function to be reused in different contexts while maintaining clarity in user interaction .

You might also like