用Python实现ifelse条件

2024-06-16 14:16:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须登录,但由于某些原因,它不工作。能帮我点忙吗?你知道吗

我有这个代码,但我不能让它工作。你知道吗

username=input("please enter your username")
password=input("please enter your password")
if username=="student1":
password=="password123"
print("accsess granted")

else username!="student1":
password !="password123"
print "inncorect login"

Tags: 代码inputyourifusername原因passwordelse
3条回答
  1. 缩进已关闭

  2. 您的if格式不正确

  3. 你自相矛盾的print陈述让人怀疑你使用的是什么版本(版本很重要!括号很重要!)


幸运的是,解决方法非常简单。您需要一个if-else语句。else不需要条件。你知道吗

username = input("please enter your username")
password = input("please enter your password")

if username == "student1" and password == "password123":
    print("access granted")

else:
    print("incorrect login")

如果您使用的是python2,请改用raw_input。你知道吗

现在,您的脚本只检查用户名是否为“student1”,并对密码执行无用的检查。请尝试此版本(假设为Python 2.7):

username = raw_input("please enter your username")
password = raw_input("please enter your password")
if username == "student1" and password == "password123":
    print "access granted"
else:
    print "incorrect login"

更好的是,您应该散列您的密码,因为现在打开python文件并四处查看以找到正确的密码就足够了。例如:

from hashlib import md5
username = raw_input("please enter your username")
password = raw_input("please enter your password")
password2 = md5()
password2.update(password)
if username == "student1" and password2.hexdigest() == "482c811da5d5b4bc6d497ffa98491e38":
    print "access granted"
else:
    print "incorrect login"

我用以下代码生成哈希:

from hashlib import md5
m = md5()
m.update('password123')
print m.hexdigest()
if username=="student1" and password=="password123":
  print("accsess granted")

相关问题 更多 >