Phone number lookup program: (index) and while loop - python

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.

Related

How do I take an input, add it to a list, and use loops and if elif else statements to check if any two values are the same?

I am trying to make a simple program that uses for loops, if-elif-else statements, and input to take three "employees" salaries and compare them to see if A, any of them have the same salary. Or B if non of them have the same salary. So far, this is what I got but both strategies I've tried haven't been successful and I don't understand why :(. All help is appreciated, and spare me for I'm still new to coding and I'm trying to teach myself through these exercises. Thank you kindly!
salarylist = []
salarylist = list(map(int, salarylist))
maxLengthList = 3
while len(salarylist) < maxLengthList:
salary_of_employee = int(input("Enter your salary: "))
salarylist.append(salary_of_employee)
print("salary of employees are:\n")
print(type(salarylist))
print(salarylist)
print(type(salarylist))
x = salarylist
if salary_of_employee == salarylist[x]:
print(f"these are the same salary.{salary_of_employee} and {salarylist[x]}")
else:
print('non of the salaries are the same.')
############################################################################
empOne = salarylist[0]
empTwo = salarylist[1]
empThree = salarylist[2]
if empOne == salarylist[0]:
print("these are the same salary.")
elif empTwo == salarylist[1]:
print('these are the same salary')
elif empThree == salarylist[2]:
print('these are the same salary')
else:
print('non of the salaries are the same.')
I have tried running your code and it gives a horrible error.
I clearly understood your desire. Most of your logic don't meet it.
So I decided to RE-Code everything based upon your requirements {for loops, if, elif, else statement, 3 employees etc..}
MAX_LEN = 3
COUNTER = 1
LIST_SAL = []
while MAX_LEN >= COUNTER:
ASK_SAL = int(input('Enter your salary :'))
LIST_SAL.append(ASK_SAL)
COUNTER+=1
print(LIST_SAL)
for check in LIST_SAL:
if LIST_SAL.count(check)>1:
print('Same salaries presented in the list')
break
else:
print('Salaries of employees are unique!')
break
Okay so ..
I created a variable max_len = 3 which is the total number of employees and then I initiated the variable COUNTER to 1 so that it iterates in the while loop and gets incremented by 1 each time.
Therafter a variable named ask_sal asks the user for salaries {3 times} and appends each input to the LIST_SAL variable {a list}. And then I printed the list for visualisation.
There after I accessed the elements in the list {list_sal} by a for loop with the variable check which looks for the number of time an element repeats in the list all by the help of count() function Which, IF greater then one prints "SAME salaries presented" OR else prints "Unique salary"..
You might be wondering why have I used 2 break statements..
Well they are used to break the further iteration as the if or else condition are met in the first iteration.
If you try removing the break statements, the print function will work the number of times the same salaries occur in the list.
Hope I helped you.. I am too , a newbie in programming yet I love it and practice a lot .
Keep grinding and Working hard
When you have the list of salaries, create a set from that list and compare the length, if same length then salaries will be unique, otherwise there will be at least one common salary
lst2 = set(salarylist)
if(len(lst2) == len(salarylist)):
print("Non of the salaries are the same.")
else:
print("Same salaries found")
To find the same salaries loop through the the set and check count of elements in the list, if greater than one, then duplicate.
for sal in lst2:
if(salarylist.count(sal) > 1):
print("Duplicate here")

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!')

Finding the next entity in a list python

I am relatively new to python and I have searched the web for an answer but I can't find one.
The program below asks the user for a number of inputs, and then asks them to input a list of integers of length equal to that of the number of inputs.
Then the program iterates through the list, and if the number is less than the ToyValue, and is less than the next item in the list the variable ToyValue increments by one.
NoOfToys=0
ToyValue=0
NumOfTimes=int(input("Please enter No of inputs"))
NumberList=input("Please enter Input")
NumberList=NumberList.split(" ")
print(NumberList)
for i in NumberList:
if int(i)>ToyValue:
ToyValue=int(i)
elif int(i)<ToyValue:
if int(i)<int(i[i+1]):
NoOfToys=NoOfVallys+1
ToyValue=int(i[i+1])
else:
pass
print(NoOfVallys)
Here is an example of some data and the expected output.
#Inputs
8
4 6 8 2 8 4 7 2
#Output
2
I believe I am having trouble with the line i[i+1], as I cannot get the next item in the list
I have looked at the command next() yet I don't think that it helps me in this situation.
Any help is appreciated!
You're getting mixed up between the items in the list and index values into the items. What you need to do is iterate over a range so that you're dealing solidly with index values:
NoOfToys = 0
ToyValue = 0
NumOfTimes = int(input("Please enter No of inputs"))
NumberList = input("Please enter Input")
NumberList = NumberList.split(" ")
print(NumberList)
for i in range(0, len(NumberList)):
value = int(NumberList[i])
if value > ToyValue:
ToyValue = value
elif value < ToyValue:
if (i + 1) < len(NumberList) and value < int(NumberList[i + 1]):
NoOfToys = NoOfVallys + 1
ToyValue = int(NumberList[i + 1])
else:
pass
print(NoOfVallys)
You have to be careful at the end of the list, when there is no "next item". Note the extra check on the second "if" that allows for this.
A few other observations:
You aren't using the NumOfTimes input
Your logic is not right regarding NoOfVallys and NoOfToys as NoOfVallys is never set to anything and NoOfToys is never used
For proper Python coding style, you should be using identifiers that start with lowercase letters
The "else: pass" part of your code is unnecessary

list index out of range for while loop

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

Categories

Resources