Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Challenge: Safely Auth | Error Handling
Mastering Python: Annotations, Errors and Environment

book
Challenge: Safely Auth

Note

These comments help you find the code that needs to be modified:
========== Modify code below ==========
========== Modify code above ==========

Compito

Swipe to start coding

You have implemented the login() function, which raises errors. Implement the safely_auth() function that uses the login() function and catches errors.

  1. Create a code block to track errors (mention the keyword).
  2. Call the login() function in the error tracking block.
  3. Catch the TypeError and save its info inside the error variable.
  4. Print the error variable (error info) in the console.
  5. Catch the ValueError and save its info inside the error variable.

Soluzione

USER_EMAIL = "top.user@in.the.world"
USER_PASSWORD = "super123secure321password"

def login(email, password):
if not isinstance(email, str):
raise TypeError("The email should be string")
if not isinstance(password, str):
raise TypeError("The password should be string")
if not "@" in email:
raise ValueError("The taken email argument is not email")
if not (email == USER_EMAIL and password == USER_PASSWORD):
raise ValueError("There are no user with this email and password")
else:
print("Authorize is successful")


def safely_auth(email, password):
try:
login(email, password)
except TypeError as error:
print("TypeError:", error)
except ValueError as error:
print("ValueError:", error)


print("Auth with wrong mail")
safely_auth("qw123d", "super123se123321password")

print("-" * 40)

print("Auth with wrong password type")
safely_auth("cat@top.mail", 12512)

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 3. Capitolo 6
USER_EMAIL = "top.user@in.the.world"
USER_PASSWORD = "super123secure321password"

def login(email, password):
if not isinstance(email, str):
raise TypeError("The email should be string")
if not isinstance(password, str):
raise TypeError("The password should be string")
if not "@" in email:
raise ValueError("The taken email argument is not email")
if not (email == USER_EMAIL and password == USER_PASSWORD):
raise ValueError("There are no user with this email and password")
else:
print("Authorize is successful")

# ========== Modify code below ==========
def safely_auth(email, password):
___:
___(email, password)
except ___ as error:
print("TypeError:", ___)
___ ValueError as ___:
print("ValueError:", error)
# ========== Modify code above ==========

print("Auth with wrong mail")
safely_auth("qw123d", "super123se123321password")

print("-" * 40)

print("Auth with wrong password type")
safely_auth("cat@top.mail", 12512)

Chieda ad AI

expand
ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

some-alt