为什么我的if语句return提示错误?
Why does my if statement return the wrong prompt?
我确定答案就在眼前,但我似乎无法弄清楚如何在输入正确条件时修复第一个 if 语句中的 return。
create_password = input("Enter password here: ")
if len(create_password) > 6 and create_password.isdigit() > 0:
print("Your account is ready!")
elif len(create_password) < 6 and create_password.isdigit() < 1:
print("Password must be more than 6 characters and must include a number")
elif len(create_password) > 6 and create_password.isdigit() == 0:
print("Password must include a number")
else:
print("Your password sucks")
假设我输入 elephant100,我试图让提示成为“您的帐户已准备就绪!”。但令我沮丧的是,它打印出“密码必须包含一个数字”,我不明白为什么。我的其他条件与正确的输入匹配,但这是唯一不起作用的条件。
.isdigit()
方法returnsTrue
如果所有字符都是数字,否则False
。因此它 returns False
在这种情况下,因为你的字符串包含像 e、l、p 等字母。所以语句 print("Your account is ready!")
将永远不会被执行。
原来我需要使用 isalnum()、isnumeric() 和 isalpha() 来解决我的问题。谢谢 Muhammed Jaseem 帮我弄明白了!这是我修改后的代码。
if create_password.isnumeric() == True:
print("Password must be more than 6 characters and include letters")
elif create_password.isalpha() == True:
print("Password must be more than 6 characters and include numbers")
elif len(create_password) > 6 and create_password.isalnum() == True:
print("Your account is ready!")
else:
print("Your password sucks. Must be more than 6 characters and contain only letters and numbers")
我确定答案就在眼前,但我似乎无法弄清楚如何在输入正确条件时修复第一个 if 语句中的 return。
create_password = input("Enter password here: ")
if len(create_password) > 6 and create_password.isdigit() > 0:
print("Your account is ready!")
elif len(create_password) < 6 and create_password.isdigit() < 1:
print("Password must be more than 6 characters and must include a number")
elif len(create_password) > 6 and create_password.isdigit() == 0:
print("Password must include a number")
else:
print("Your password sucks")
假设我输入 elephant100,我试图让提示成为“您的帐户已准备就绪!”。但令我沮丧的是,它打印出“密码必须包含一个数字”,我不明白为什么。我的其他条件与正确的输入匹配,但这是唯一不起作用的条件。
.isdigit()
方法returnsTrue
如果所有字符都是数字,否则False
。因此它 returns False
在这种情况下,因为你的字符串包含像 e、l、p 等字母。所以语句 print("Your account is ready!")
将永远不会被执行。
原来我需要使用 isalnum()、isnumeric() 和 isalpha() 来解决我的问题。谢谢 Muhammed Jaseem 帮我弄明白了!这是我修改后的代码。
if create_password.isnumeric() == True:
print("Password must be more than 6 characters and include letters")
elif create_password.isalpha() == True:
print("Password must be more than 6 characters and include numbers")
elif len(create_password) > 6 and create_password.isalnum() == True:
print("Your account is ready!")
else:
print("Your password sucks. Must be more than 6 characters and contain only letters and numbers")