Incorrect checking of fields in list using a for loop

2024/11/15 17:33:58

I have the following code that seeks to read the file contents into a list (this bit works) and then display a message of acceptance, IF the bank details (user and corresponding number) matches.

e.g. if username: customer1 and account_number:1 is entered >> Access Granted and so on for each customer and account number in the file.

File details

customer1,1
customer2,2
customer3,3
customer4,4
customer5,5

Code

def strip_split_read_from_file():bankdetails=[]with open("bankdetails.txt","r") as f:for line in f:line=line.rstrip() #r strip removes the new line character from the right side of the stringsplit_line=line.split(",")for field in split_line:bankdetails.append(field)accessgranted=Falsewhile accessgranted==False:username=input("username:")password=input("account no:")for i in bankdetails:if username==bankdetails[i] and password==bankdetails[i+1]:accessgranted=Truebreakelse:accessgranted=Falseif accessgranted==True:print("Access Granted")else:print("Sorry, wrong credentials")

Error

 if username==bankdetails[i] and password==bankdetails[i+1]:
TypeError: list indices must be integers, not str

For an answer, and teaching/learning purposes I would like the following

  1. Correction with clear explanation of the error using the existing, provided code

  2. Suggestions as to alternative ways to achieve the same objective in the most efficient method possible

Answer

for i in bankdetails: means that i will become every element in bankdetails, not that it will become the position of the element. If you want it to become the position, you must do for i in len(bankdetails), because len() is the function to get the length of a data structure. However, since you take two fields every time, I'd recommend to do it with a while structure, like this:

total = len(bankdetails) - 1
i = 0
while i < total:if username==bankdetails[i] and password==bankdetails[i+1]:accessgranted=Truebreakelse:accessgranted=Falsei += 2

However, if you have lots of entries in your list, iterating over all of them can take a lot of time. To avoid this, using a dictionary is the best option: checking if an item is in it is a lot faster, and you don't need to iterate to find the value associated with it.

If you don't know how dictionaries work, it kinda works like a list, except they're not ordered, and the way you look for an item is checking the value associated to a key. Let's be more clear. In your file, you have:

customer1,1
customer2,2
customer3,3
customer4,4
customer5,5

The way to add them in a dictionary would be:

bankdetails={} #Notice that they're initialized as {}with open("bankdetails.txt","r") as f:for line in f:line=line.rstrip() #r strip removes the new line character from the right side of the stringsplit_line=line.split(",")username = split_line[0]password = split_line[1]bankdetails[username] = password

This way, bankdetails will contain {'customer1': '1', 'customer2': '2', ... }

And, to look for the user and its password, you'd have to do this:

username=input("username:")
password=input("account no:")
if username in bankdetails:if bankdetails[username]==password:accessgranted=Truebreakelse:accessgranted=False

This will do exactly what you wanted, but much faster if you had lots of entries.

https://en.xdnf.cn/q/119025.html

Related Q&A

Why myVar = strings.Fields(scanner.Text()) take much more time than comparable operation in python?

Consider the following code in golangnow := time.Now() sec1 := now.Unix()file, err := os.Open(file_name) if err != nil {log.Fatal(err) } defer file.Close()scanner := bufio.NewScanner(file)var parsedLin…

When reading an excel file in Python can we know which column/field is filtered

I want to capture the field or column name that is filtered in the excel file when reading through python. I saw that we can also capture only the filtered rows by using openpyxl and using hidden == Fa…

Error:__init__() missing 1 required positional argument: rec

I am new to python. I am trying to do microphone file that ought to detect, listen, record and write the .wav files. However, it is giving me an error while I am trying to run the file. It is saying:Ty…

Maya: Connect two Joint chains with Parent Constraint

So here is a snipit of an IK spine builder Ive been working on. Ive figure out how to make lists to duplicate the bound into an IK chain, what Ive got stuck on however is I want my list and for loop to…

What is the equivalent for onkeydown and onkeyup (Javascript events) in python?

There are events called onkeydown and onkeyup in Javascript. Can anyone please suggest the python equivalent of it?

Matching number string pairs

I have the following sample string:R10666: 273141 C1 + 273141 C2 + 273141 C3 + 273141 C4 + 273141 C5 - 273141 C6I want to obtain:[(273141,C1), ..., (- 273141, C6)]The numbers can be floating point numb…

Turning a text file into a tabular format [duplicate]

This question already has answers here:How do I print parameters of multiple objects in table form? [duplicate](2 answers)Line up columns of numbers (print output in table format)(7 answers)Closed 5 y…

Python: Read file with list as list

I have placed a list in a text file. I want python to read the text file and return the contents as a list. However, it is instead reading the content as a string:Text file:[a,b,c]Python:ids=[]writtenF…

Tkinter scrollbar not scrollable

I followed some tutorial on attaching a scrollbar to a textbox. However, in the tutorial, the scrollbar is really a "bar". When I tried myself, I can only press the arrows to move up or down,…

How to create multiple roles through discord.py bot?

I have been trying to make my discord bot create multiple roles through a command. But it simply doesnt work. Here is what I have done so far: @commands.command()async def create_roles(self, ctx):guild…