Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 请告诉我如何使此代码更;蟒蛇的;_Python_Python 3.x_Loops - Fatal编程技术网

Python 请告诉我如何使此代码更;蟒蛇的;

Python 请告诉我如何使此代码更;蟒蛇的;,python,python-3.x,loops,Python,Python 3.x,Loops,此代码功能齐全,无需使用错误处理。有没有更有效的方法来写这个?我很想向你们大家学习 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

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

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...")

你可以这样做:

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中需要一段时间?只需使用密码!='pass123':。我忘了是什么时候添加的:=的,但那感觉像是一个很好的地方。尼斯提示,改变了这一点。