def log_in():
user_name1="xyz"
try:
user_name =(input("Enter your username:"))
if (user_name ==user_name1):
print("welcome")
except TypeError:
print("Enter only characters")
log_in()
我想在用户输入整数值而不是字符串值时生成异常
答案 0 :(得分:1)
当您在控制台中输入整数时,input(...)
将以字符串形式返回用户输入的输入。所以你永远不会得到TypeError
例外。您也不需要在str()
附近添加input()
功能。
答案 1 :(得分:0)
由于您对Type Checking
感兴趣,您可能希望稍微颠倒您的逻辑:
def log_in():
user_name1 = "xyz"
user_name = input("Enter your username:\n") # str()
try:
# FOR YOUR USE CASE, IT WOULD SUFFICE TO SIMPLY TRY TO CAST THE ENTERED
# INPUT TO AN INT (INITIALLY) - REGARDLESS OF WHETHER IT'S INT OR STRING:
# PERHAPS STRIP-OFF ALL EXTRA WHITE-SPACES AS WELL
int( user_name.strip() )
# IF WE ARE SURE IT'S AN INT, THEN: WE RESPOND ACCORDINGLY -
print("Solely Numeric characters are not allowed as Username....")
# THEN IMMEDIATELY BAIL OUT OF THE FUNCTION:
return False
except:
pass
# COMPARE ENTERED USERNAME WITH EXPECTED VALUE
# IF ALL GOES WELL THEN, WELCOME THE USER
if user_name.strip() == user_name1:
print("welcome")
else:
print("Wrong Credentials....")
log_in()