【问题标题】:How to change a variable within a program如何更改程序中的变量
【发布时间】:2013-12-04 16:52:18
【问题描述】:

有人可以检查此代码吗?大部分都在工作,但是当他们输入“管理员”时,它应该允许他们设置新密码“输入新密码”,但新密码不会保存。任何人都可以帮我解决它吗?谢谢

program = ("live")
while program == ("live"):
    password = ("Python")
    question = input("What is the password? ")
    if question == password:
        print ("well done")
    if question == ("admin"):
        n_password = input("What is the new password? ")
        password = n_password
        question = input("What is the password? ")
    else:
        question = input("What is the password? ")

【问题讨论】:

  • ("live") 的类型是什么?
  • 请注意:请不要将密码“保存”为明文。当用户设置密码时,您只需存储该密码的哈希值。下次他“登录”时,您检查哈希值是否相同。
  • 无需将您的字符串括在括号中(这样做时您不会列出列表)。
  • 与其使用input,不如考虑getpass,它在标准库中并且非常易于使用。顺便说一下,检查你的逻辑流程。在每个循环中,用户将被要求输入两次密码(不管admin 与否)。

标签: python variables for-loop


【解决方案1】:

您需要将第一行 password = ... 移出循环:

program = ("live")
password = ("Python")
while program ==("live"):
    question=input("What is the password? ")
    if question == password:
        print ("well done")
    if question == ("admin"):
        n_password = input("What is the new password? ")
        password=n_password
        question=input("What is the password? ")
    else:
        question=input("What is the password? ")

这确保密码第一次是Python,但之后它将使用password 的新值。另请注意,您可以删除一些 input() 调用:

program = ("live")
password = ("Python")
while program ==("live"):
    question=input("What is the password? ")
    if question == password:
        print ("well done")
    if question == ("admin"):
        n_password = input("What is the new password? ")
        password=n_password

【讨论】:

  • 帮助很大,非常感谢!
  • 请从您的答案中删除不需要的括号。
【解决方案2】:

您需要将 password = ("Python") 放在您的 while 循环开始之前。

【讨论】:

    猜你喜欢
    • 2011-04-07
    • 2012-04-25
    • 1970-01-01
    • 2022-10-14
    • 2021-08-17
    • 1970-01-01
    • 2016-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多