Lecture 3 Part 3 - CS50's Introduction To Programming With Python
Lecture 3 Part 3 - CS50's Introduction To Programming With Python
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()
https://cs50.harvard.edu/python/2022/notes/3/ 5/8
11/18/24, 4:20 AM Lecture 3 - CS50's Introduction to Programming with Python
print(f"x is {x}")
def get_int():
while True:
try:
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.
https://cs50.harvard.edu/python/2022/notes/3/ 6/8