[英]how to compare if two values are the same but different cases in python
So the exercise I'm doing goes:所以我正在做的练习是:
086 Ask the user to enter a new password.
086 要求用户输入新密码。 Ask them to enter it again.
请他们再次输入。 If the two passwords match, display “Thank you”.
如果两个密码匹配,显示“谢谢”。 If the letters are correct but in the wrong case, display th emessage “They must be in the same case”,otherwise display the message “Incorrect”.
如果字母正确但大小写错误,则显示消息“它们必须大小写相同”,否则显示消息“不正确”。
My attempt looks like this:我的尝试如下所示:
passw = input("Enter password: ")
passw2 = input("Enter password again: ")
if passw == passw2:
print("Thank you.")
elif passw != passw2 and passw.lower == passw2.lower:
print("They must be in the same case.")
else:
print("Incorrect.")
That didn't give me the result I was hoping for though.但这并没有给我我希望的结果。 This should be really simple but as you can tell I'm a beginner:) Thank you in Advance!
这应该很简单,但你可以告诉我我是一个初学者:) 提前谢谢你!
Marcel马塞尔
That passw.lower
is a method, the method itself, you may call it to have the password in lowercase. passw.lower
是一个方法,方法本身,你可以调用它来获得小写的密码。 Also remove passw != passw2
in second ìf
that's mandatory True
还要删除
passw != passw2
在第二个ìf
如果这是强制性的True
if passw == passw2:
print("Thank you.")
elif passw.lower() == passw2.lower():
print("They must be in the same case.")
else:
print("Incorrect.")
More更多的
passw = "Abc"
print(passw.lower(), "/", type(passw.lower()))
# abc / <class 'str'>
print(passw.lower, "/", type(passw.lower))
# <built-in method lower of str object at 0x00000202611D4730> / <class 'builtin_function_or_method'>
The problem is that your elif
condition always evaluates to True
:问题是您的
elif
条件始终评估为True
:
elif passw != passw2 and passw.lower == passw2.lower:
str.lower
is a function, and comparing a function with the same function logically ends up being True
. str.lower
是 function,将 function 与相同的 function 进行比较逻辑上最终为True
。 You have to call the functions instead and compare their results.您必须改为调用函数并比较它们的结果。 Additionally, you are doing comparing
passw
and passw
twice: once you check if they are the same in the if
condition, and once you check if they are not the same in the elif
condition.此外,您正在比较
passw
和passw
两次:一次在if
条件下检查它们是否相同,一次在elif
条件下检查它们是否不同。 This is useless, because the elif
condition will only ever be executed when the if
condition was False
.这是没有用的,因为只有当
if
条件为False
时才会执行elif
条件。 Following the working code:遵循工作代码:
passw = input("Enter password: ")
passw2 = input("Enter password again: ")
if passw == passw2:
print("Thank you.")
elif passw.lower() == passw2.lower():
print("They must be in the same case.")
else:
print("Incorrect.")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.