Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära 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 ==========

Uppgift

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.

Lösning

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)

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 3. Kapitel 6
single

single

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)

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

some-alt