【问题标题】:Counter - skipping element and not increasing during the for loop计数器 - 跳过元素并且在 for 循环期间不增加
【发布时间】:2021-05-26 20:07:29
【问题描述】:

所以我正在为我的班级编写一个基本的登录系统,并且我正在使用 for 循环和计数器来线性搜索列表。但是,当我输入一个应该正确的用户名时,它返回为未经授权的。我尝试在循环的每次传递之间打印计数器,我发现即使范围是 (0,6) 它最多只能计数到三个?

image of code, shell and error message

import random

userver = 0
userList = ["Arabella12", "Constance01", "Hugo11", "James09", "Jane12", "Max06", "Ted04"]
pwrdList = ["bella12", "1234", "HGWel!", "j@me£S", "Password", "notpassword", "ted4"]
found = False
pfound = False

def login():
    username = input("Type in your username ")
    index1 = 0
    wrong = 0
    found = False
    c3 = 0
    print("index one before c3 loop=", index1)  #delete after testing
    for c3 in range(0, 6): #username check counter
        if username == userList[c3]:  #if username is found with the counter c3
            found = True  #making the key for the next part of the code true
            index = s(c3)
            print(index," is the index")
            c3 = c3 + 1
            break
        elif found == False:
            print("c3: ", c3)  #checking counter- delete after debugging
            print("unauthorised user...attempting again")  #if username isnt present
            c3 = c3 + 1  #upping the counter
            exit

login()

【问题讨论】:

  • 您为什么要“增加计数器”,而不是让for 循环自行进行?也许你需要read more about for loops in Python
  • 在 for 循环中使用 exit 有什么意义?
  • 您正在干扰计数器 - 不要“手动”增加它。

标签: python arrays for-loop counter linear-search


【解决方案1】:

范围不正确,因为您使用的是 而不是"。此外,您不需要在 elif 中使用 exit 并增加计数器 - 它会自动完成

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-26
    • 1970-01-01
    • 2015-07-17
    • 1970-01-01
    • 1970-01-01
    • 2018-06-11
    • 2023-03-08
    相关资源
    最近更新 更多