My notes: Learning CS50 Python -Lecture 3 - Exceptions

0:00 Introduction

Problems in your code and how to solve them

SyntaxError-> something wrong with your

Errors are For you to solve

0:24 Exceptions

0:52 SyntaxError

---- see code

x = int(input("What's x?"))

print (f"x is {x}" )

---

3:29 ValueError

6:57 "ValueError: invalid literal for int() with base 10: 'cat'"

what is int-> converts users input to integer

8:52 try, except

"ValueError"

----code here

try

x = int(input("What's x?"))

print (f"x is {x}" )

except ValueError:"

-----

code here

----

try:

x = int(input("What's x?"))

print (f"x is {x}" )

except ValueError:

print("x is not an integer")

------

There are other errors you can catch

Python-Except is anything is wrong

Problems: Hides other bugs

and you can't determine which other bugs and difficult to remedies it later on

Figure out "WHAT COULD HAPPEN" and determine explicitly

It takes practice to determine which errors will have

----

14:18 NameError

//

try:

x = int(input("What's x?"))

except ValueError:

print("x is not an integer")

print (f"x if {x}")

----

NameError <= Refer to a code that you shouldn't do

`

Why is x is NameError

-Due to order of operations

Value Error=

error is in the right

no copy value on the left

even though we see x... but the left is not evaluated

line 6 only looks it is defined

18:35 else

-----code here

'try:

x = int(input("What's x?"))

except ValueError:

print("x is not an integer")

else:

print (f"x if {x}")

'

---

22:40 Reprompting, break

the code presented:

---

try:

x = int(input("What's x?"))

except ValueError:

print("x is not an integer")

else:

print (f"x if {x}")

---

Loop-something that happens again

Prompt the user for x so ask for a value until they then complied with a value that we want

use break to breakout of the loop

if we just print-it doesnt break in the loop

can i use break in else?

you can use break in loop to breakout and also in conditional (if else,) and it's not restrictive

if nothing goes wrong, it will continue

while True:

try:

x = int(input("What's x?"))

break

except ValueError:

print("x is not an integer")

print(f"x is {x}")

----

29:50 get_int

-get int from the user

-share with other people

def get

while True:

try:

x = int(input("What's x?"))

except ValueError:

print("x is not an integer")

else:

break

return

-------

def main()

x = get_int():

print(f"x {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()

---

def main():

x = get_int()

print(f"x {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()

-

return vs

return-return a value

break -break out of loop and might also return a v alue

35:48 pass

41:32 Function Arguments

43:52 Conclusion