list index out of range for while loop - python

def main():
infile = open('charge_accounts.txt', 'r')
chargeAccounts = infile.readlines()
index = 0
while index < len(chargeAccounts):
chargeAccounts[index] = chargeAccounts[index].rstrip('\n')
index += 1
userAccount = input("Please enter a charge account number: ")
count = 0
while userAccount != chargeAccounts[count] or chargeAccounts[count] == chargeAccounts[17]:
count += 1
if chargeAccounts[index] == userAccount:
print("The account number", userAccount, "is in the list.")
else:
print("The account number", userAccount, "in not in the list.")
main()
I'm trying to make a code in python that has the user input a number and checks to see if that number is in a list. When I try to run this code, I get an error that says that the list index is out of range in the while loop. There are only 18 items in the list, and I have the while loop set to terminate at 17(which should be 18 in the list).
Edit: It also doesn't work if the while loop is set to chargeAccounts[count] != chargeAccounts[17]:
Here's the exact error code:
Traceback (most recent call last):
File "F:/CPT 168/Ch 7/AndrewBroughton_Chapter7_Excersizes/7-5/7-5.py", line 23, in <module>
main()
File "F:/CPT 168/Ch 7/AndrewBroughton_Chapter7_Excersizes/7-5/7-5.py", line 13, in main
while userAccount != chargeAccounts[count] or chargeAccounts[count] != chargeAccounts[17]:
IndexError: list index out of range
Here's the content of the original text file:
5658845
4520125
7895122
8777541
8451277
1302850
8080152
4562555
5552012
5050552
7825877
1250255
1005231
6545231
3852085
7576651
7881200
4581002

A while loop will keep looping as long as its condition is True.
count = 0
while userAccount != chargeAccounts[count] or chargeAccounts[count] == chargeAccounts[17]:
count += 1
If I enter an invalid userAccount to your program, the first part of the condition userAccount != chargeAccounts[count] is always going to be True. That makes the entire condition True, since you're using or logic.
Furthermore, if you want to check to see if you've reached the end of a list, you don't have to check the contents of the last list element (chargeAccounts[count] == chargeAccounts[17]). Check the length instead (count == len(chargeAccounts)).
To fix this, change that loop condition to something like
while count < len(chargeAccounts) and userAccount != chargeAccounts[count]:
(I'm not sure if this is exactly what you need, because I don't really follow the logic of your program. This should get you past the current error, though.)

You get the error at the string if chargeAccounts[index] == userAccount: because index is already bigger than the index of the last element of the list (because you left the loop with this index above).
I would recommend you to follow a few rules to work with lists that could save you from similar errors with indices.
Use for-loop instead of while-loop, if you lineary go through each element.
Use break if you want to leave the loop and keep the index
So you code may look like this:
with open('charge_accounts.txt', 'r') as infile:
chargeAccounts = infile.readlines()
for index in range(len(chargeAccounts)):
chargeAccounts[index] = chargeAccounts[index].strip()
userAccount = input("Please enter a charge account number: ")
found = False
for chargeAccount in chargeAccounts:
if chargeAccount = userAccount:
found = True
break
if found:
print("The account number", userAccount, "is in the list.")
else:
print("The account number", userAccount, "in not in the list.")

Related

How to count and store an unknown number of inputs Python

I need to take in an unknown number of strings, each on a new line, count them and determine if they were entered in alphabetical order.
I have to do this without using lists or dictionaries.
I’m lost. I tried assigning each to a variable but realized that without knowing the number of inputs that was not going to work without a loop of some kind that ends when there is no additional input. I have tried that but can’t figure out how to assign a new variable in the loop
try this one:
count = 0
prev = ''
isAlphabetical = True
while True:
curr = input('Enter string:')
if curr == '': # this is the ending condition. you may want to change it.
break
count+=1
if curr < prev:
isAlphabetical = False
prev = curr
print('count =',count)
if isAlphabetical:
print('they are in alphabetical order')
else:
print('they are not in alphabetical order')
the above code takes the inputs until the user enters nothing and press the enter button. it takes track of the order of the inputs and the number of them.

Finding whether element entering in a list is duplicate or unique, while the program is running

so, I came across this question, where I have to create a list, take the elements as input from the user. After doing so, I have to check whether the elements entered by the user are 'Unique' or 'Duplicate', and this has to be done while the program is running. i.e if the input entered is duplicate, then I have to terminate the program then and there, otherwise proceed.
I have written the following code (Python):
list = []
num = int(input('enter no. of elements in list: '))
for i in range(0,num):
q = int(input('element %d: '%(i+1)))
list.append(q)
print(list)
cnt = 0
for i in range(0,num):
if(list[i]==q):
cnt = cnt+1
if(cnt>1):
print('Duplicate')
else:
cnt = cnt+0
if(cnt==0):
print('Unique')
print('\nProgram Terminated!')
The thing is that, I know that I might have to use the break statement in the loop where I check whether the values are equal, but I somehow can't place it correctly.
Thank you! :)
If you want to check each time the user puts in a new element, i think this is the solution to your question:
list = []
num = int(input('enter no. of elements in list: '))
for i in range(0, num):
q = int(input('element %d: ' % (i+1)))
if q not in list:
print('Unique')
list.append(q)
else:
print('Duplicate')
break
print(list)
print('\nProgram Terminated!')

Phone number lookup program: (index) and while loop

Can anybody please explain this code a little bit for me about why are we using the (index) and while loop?
def main():
people = ['todd','david','angela','steve','bob','josh','ben']
phoneNumbers = ['234-7654','567-1234','888-8745','789-5489','009-7566','444-6990','911-9111']
found = False
index = 0
searchValue = raw_input('Enter a name to search for phone number: ')
while found == False and index < len(people):
if people[index] == searchValue:
found = True
else:
index = index + 1
if found:
print('the phone number is: ',phoneNumbers[index])
else:
print('that name was not found')
main()
Your program is looping through the whole list of phoneNumbers and people. Each item on a list has its own index value. In python, the first item in the list has an index of 0. According to your question, indexes were used to find at which position the person's name is. Then the same index position is used to find what is the phone number in the other list. But to determine this, we have builtin method to find the index position of an item in a list. I have made modifications to your code and now it is optimized.people.index(searchValue)returns the index position of the searchValue. For example, if the searchValue is steve, then the index position we get will be 3. We need to use this index position to find the phone number in the other list. So to do that we can simply do phoneNumbers[people.index(searchValue)] that simply means phoneNumbers[3]. This returns the 4th item which is 789-5489 that is the phone number.
NOTE:
Index of a list always starts with 0
listName.index(item) returns the index position
listName[index] returns the item
def main():
people = ['todd','david','angela','steve','bob','josh','ben']
phoneNumbers = ['234-7654','567-1234','888-8745','789-5489','009-7566','444-6990','911-9111']
searchValue = input('Enter a name to search for phone number: ')
if searchValue in people:
print(f"The phone number is {phoneNumbers[people.index(searchValue)]}")
else:
print('that name was not found')
main()
Some information about the logic:
while found == False means until the name is found in the list
and index < len(people) means the number of iterations that should
take place in the list people
if people[index] == searchValue checks if the person in the list is
same as the person the user searched for
found = True means that the person that we are looking for has been found. This will quit from the while loop because we mentioned that we
need to execute the code only when found = false. But now it is
true. So it will quit from the while loop
else: index = index + 1 is to shift to the next position. We
already completed checking if the first item is equivalent to the
user input. If it is not equal, then we need to check if the next
name in the list is equal to the user input.
Keep in mind that only one of if or else will occur. That means when the condition for if is satisfied, only the if part will occur and the else part is not to be bothered. When the condition for if is not satisfied, only else will occur. Therefore, if the name is not found only we are checking the next item. If we found it, we are just going to quit from the while loop.
In while found == False and index < len(people):, found == False means run until find a name, and index < len(people) means searched every name from list.
And the reason using index is phone number locates at same index in phonenumbers.

Program ignoring if elif statements

I'm stumped, I have no idea why this is not working. It just ignores everything except for the else statement. No idea what could be causing this, help!
The program is just too simple to mess up, and yet, here it is, not working.
def main(): #the main function, where the program is held.
print("Opening Account List now...\n")#flavor tx to add user context for the list of numbers to be displayed.
infile = open('CHarge Accounts.txt', 'r')#opens the 'CHarge Accounts' text file in read-only mode,
#and saves it to the variable 'infile'.
numbers = infile.readlines()#The '.readlines()' command opens the text file stored in the 'infile'
#variable and and reads every single line of text in the file.
#It then saves the data that has been read to the variable 'numbers'.
infile.close()#This closes the text file being within the 'infile' variable, preventing data from being los,
#and causing errors in the program
index = 0#control value for the number of values to be inserted into the 'numbers' list.
#
while index < len(numbers): #while the index value is less than the number of values within numbers.
#This means that as long as index is less than however many account numbers
#that are within the 'numbers' list, the loop will continue.
numbers[index] = int(numbers[index])#While the loop runs, the values in the numbers index will be
#converted to integer values
index += 1 #controlling value increments for every number read
print (numbers, '\n')
x = 0 #control value for the while loop.
while x == 0: #Loop begins.
accnumber = int(input("Please type in the account number you'd like to change, or type in -1 to exit."))
if accnumber not in numbers and not -1:#Checks if account number is not in the saved txt file data, and
#if the user has inputted the 'kill' value.
print("The account number you have typed in is invalid.")#informs user data is invalid
elif accnumber in numbers and not -1:#Checks if the account number is within the saved text file data, and
#if the user has inputted the 'kill' value.
print("The account number you have selected is valid.")#text informs user that data is valid
elif accnumber == -1:#Checks if the account number value is -1
print("Goodbye!")#Flavor for the user
x = 1 #activates the control variable to break the loop
main()
if accnumber not in numbers and not -1:
# ^^^^^^
When evaluated as a truth-statement, 0 is False and any other integer is True. So -1 is True, not -1 is False, and (anything) and not -1 is always False.
Therefore your if and elif clauses always get skipped.
Try
if accnumber not in numbers and accnumber != -1:
instead.
Also:
your commenting is overdone to the point of obscuring your program. I presume this is some sort of class requirement, ie commenting every line?
your use of while loops and index variables is very non-idiomatic and could be replaced by a list comprehension as follows:
.
def main():
print("Opening Account List now...\n")
with open('Charge Accounts.txt') as inf:
numbers = [int(line) for line in inf]
print(numbers, '\n')
while True:
accnumber = int(input("Please enter an account number (or -1 to exit): "))
if accnumber == -1:
print("Goodbye!")
break
elif accnumber not in numbers:
print("The account number you have typed in is invalid.")
else:
print("The account number you have selected is valid.")
main()
Your code is a bit messy. When you are adding comments, please try to make it reader friendly. Also, spend more time on basic syntax!
def main():
print("Opening Account List now...\n")
infile = open('CHarge Accounts.txt', 'r')
numbers = infile.readlines()
infile.close()
index = 0
while index < len(numbers):
numbers[index] = int(numbers[index])
index += 1
print (numbers, '\n')
x = 0 #control value for the while loop.
while x == 0:
accnumber = int(input("Please type in the account number you'd like to change, or type in -1 to exit."))
if (accnumber not in numbers) and (accnumber !=-1):
print("The account number you have typed in is invalid.")
elif (accnumber in numbers) and (accnumber !=-1):
print("The account number you have selected is valid.")#text informs user that data is valid
elif accnumber == -1:#Checks if the account number value is -1
print("Goodbye!")#Flavor for the user
x = 1 #activates the control variable to break the loop
main()

How to call an item from a dictionary in python?

So I have a dictionary which consists of a number and its definition is the corresponding element on the periodic table.
I have built up the dictionary like this:
for line in open("periodic_table.txt"):
temp.append(line.rstrip())
for t in temp:
if t[1] != " ":
elements[x] = t[3:]
else:
elements[x] = t[2:]
x += 1
I know that every element is in table because I ask the program to print the dictionary.
The point of this is that the user enters a number or element name and the number and name are both printed like this:
while count == 0:
check = 0
line = input("Enter element number or element name: ")
if line == "":
count = count + 1
break
for key,value in elements.items():
if line == value:
print ("Element number for",line,"is",key)
check = 1
break
if line.isdigit():
if int(line) <= 118 and int(line) > 0:
print ("Element number",line, "is",elements[int(line)])
check = 1
break
if check == 0:
print ("That's not an element!")
This works for every element except the last one, Ununoctium, in the dictionary. When the user enters 118 this element is printed, but if they enter 'ununoctium' then the program says "That is not an element!". Why is this and how do I fix it?
Thanks in advance
It is much easier to have python do the lookup for you. Ignoring empty lines for now:
elements = []
for line in open("periodic_table.txt"):
elements.append(line[3:])
You can then do a lookup like this:
if answer.isdigit():
print elements[int(answer)]
else:
print elements.index(answer)
I suspect this is a case sensitive issue.
Changing
if line == value:
to
if line.lower() == value.lower():
would solve that problem.
While you are there, why have the if inside the for loop?
You could check that first, and then don't need the break
if line.isdigit():
if int(line) <= 118 and int(line) > 0:
print ("Element number",line, "is",elements[int(line)])
check = 1
#<-------- break no longer required
else:
#for loop as above

Categories

Resources