【问题标题】:Please show me how to make this code more "Pythonic" [closed]请告诉我如何使这段代码更“Pythonic”[关闭]
【发布时间】:2019-04-15 21:34:13
【问题描述】:

此代码功能齐全,无需使用错误处理。有没有更有效的方法来写这个?我很想向大家学习。

from getpass import getpass

username = input("Username: ")
grant_access = False

while not grant_access:
  password = getpass("Password: ")
  if password == 'pass123':
    grant_access = True
  elif password != 'pass123':
    while not grant_access:
      password = getpass("Re-enter Password: ")
      if password == 'pass123':
        grant_access = True
      elif password != 'pass123':
        continue

print("Logging in...")

【问题讨论】:

标签: python python-3.x loops


【解决方案1】:

你可以这样做:

from getpass import getpass

username = input("Username: ")
password = getpass("Password: ")

if password != 'pass123':
  while True:
    password = getpass("Re-enter Password: ")
    if password == 'pass123':
      break

print("Logging in...")

甚至像这样:

from getpass import getpass

username = input("Username: ")
password = getpass("Password: ")

while password != 'pass123':
  password = getpass("Re-enter Password: ")

print("Logging in...")

【讨论】:

  • 为什么要在 if 里面放一段时间?只需while password != 'pass123':
  • 我忘记了 := 是什么时候添加的,但感觉是个不错的地方
  • 不错的提示,已更改。
猜你喜欢
  • 1970-01-01
  • 2017-09-15
  • 2013-05-10
  • 2010-11-03
  • 2022-06-10
  • 1970-01-01
  • 2013-03-11
  • 2017-08-04
  • 1970-01-01
相关资源
最近更新 更多