【问题标题】:Code works without loop but doesn't work with loop代码在没有循环的情况下工作,但不适用于循环
【发布时间】:2020-02-24 12:20:30
【问题描述】:
file = open("Login.txt","a")
file.write (newusername1)
file.write (",")
file.write (newpassword1)
file.write("\n")
file.close()

print("")

incorrect_credentials2=True 

while incorrect_credentials2:
    username1=input("Please enter your username: ")
    password1=input("Please enter your password: ")
    with open('Login.txt') as f:
        if username1 +","+ password1 in f.read():
            print("Logged In")
            incorrect_credentials2 = False
        else:
            print("Incorrect username or password")
            incorrect_credentials2 = True

当我删除不正确的_credentials2 位(循环)时,这段代码有效,但是当我拥有它时,它不会显示在外壳中。任何帮助将不胜感激

【问题讨论】:

  • 请附上证明问题的minimal reproducible example,不要链接到外部网站
  • 你的第二个 if 条件在 while 循环之外,你永远不会退出第一个 while 循环。所以你的代码卡在那里。检查下面我的答案以获取更正的代码。

标签: python loops


【解决方案1】:

我认为你被困在第一个 while 循环中。请参阅我在第一个循环中添加条件的更正代码。 https://repl.it/repls/UnderstatedExtrasmallStrings

if accountmanagement == 1:
  while incorrect_credentials1:
      username1=input("Please enter your username: ")
      password1=input("Please enter your password: ")
      with open('Login.txt') as f:
        if username1 +","+ password1 in f.read():
          print("Logged In")
          incorrect_credentials1=False
        else:
          print("Incorrect username or password")
          incorrect_credentials1=True

【讨论】:

  • 谢谢你,这对我的两段代码都有帮助
【解决方案2】:

您需要将if accountmanagement == 2: 条件放在while 循环中。

print("Hello Player 1, you need an account to play Dice!")
print("1: Login to your account")
print("2: Create an account")
accountmanagement = int(input())

print("\n")

incorrect_credentials1= True

while incorrect_credentials1:
    if accountmanagement == 1:
        username1=input("Please enter your username: ")
        password1=input("Please enter your password: ")
        with open('Login.txt') as f:
            if username1 +","+ password1 in f.read():
                print("Logged In")
                incorrect_credentials1=False
            else:
                print("Incorrect username or password")
                incorrect_credentials1=True


    if accountmanagement == 2:
        newusername1 = input("Please enter your name: ")
        newpassword1 = input("Excellent! Now let's create a password: ")

        file = open("Login.txt","a")
        file.write (newusername1)
        file.write (",")
        file.write (newpassword1)
        file.write("\n")
        file.close()
        incorrect_credentials1=False
    else:
        print("Incorrect option selected.)
        incorrect_credentials1 = False

您对第二个 if 条件的缩进在 while 循环之外。只要把它放进去,你就可以走了。

【讨论】:

  • 如果他们选择 2,则现在有一个无限循环(它还有一个无限循环是输入,例如 3 用于帐户管理)
  • 是的,因为我们没有考虑用户输入除1 and 2以外的任何值的情况。正在更新答案。
  • 如果出现任何其他问题,请检查并告诉我。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-21
  • 1970-01-01
相关资源
最近更新 更多