I have the following 2D list
listItem = [["Apple", "TP123", "67", "77"], [
"Orange", "TP223", "55", "66"], ["Banana", "TP777", "98", "88"], ["Cherry", "TP123", "98", "88"]]
I want to compare the user input with the second element in each list in the listItem and print out the whole list if the value matches. If the value doesn't match, I will ask the user to enter the value again and again.
Here is my code:
def repeat():
tp = input("Please enter your tp: ")
for i in range(len(listItem)):
if tp == listItem[i][1]:
print(listItem[i])
break
else:
repeat()
I am facing some problems here. In the listItem, there are two "TP123". However, if the user enters "TP123", it only prints out one result instead of two. But if I didn't use the break, the code will keep asking users to enter another value even though the value they enter matches.
I am a python beginner, can anyone help me to solve this problem, thank you very much.
Use an extra variable and set it to True if their are matches, and use an if statement to trigger the repeat function again if it's False:
And also better without range:
def repeat():
tp = input("Please enter your tp: ")
match = False
for i in listItem:
if tp == i[1]:
print(i)
match = True
if not match:
repeat()
You are breaking before it can find the next item. Also no need to use range just loop through the list.
def repeat():
tp = input("Please enter your tp: ")
print(*(i for i in listItem if i[1] == tp), sep='\n')
Or in full for loop:
def repeat():
tp = input("Please enter your tp: ")
for i in listItem:
if tp == i[1]:
print(i)
Related
The program I have written does not work as intended, I have spent quite a while trying to solve it and cannot figure it out, it keeps repeating over and over, or until the end of the loop, any help would be much appreciated.
heres the code
def find_similar(choice1, list1):
if choice1 == 'author':
name = str(input('enter name of which author you would like to find: '))
i = 0
while(i<len(list1)):
if name == list1[i]:
print(list1[i])
print(list1[i-1])
print(list1[i+1])
i= i+1
else:
i= i+1
else:
print('index too low')
if choice1 =='year':
index1 = int(input('enter index of which year you would like to sort by: '))
if(index1-1>=0):
i = 0
print(list1[index1])
print(list1[index1-1])
print(list1[index1-2])
while(i<=len(list1)):
if index1 == i:
print(list1[i])
print(list1[i-1])
print(list1[i-2])
i= i+1
else:
i = i +1
else:
print('index too low')
user_info = input('Enter a series of books, stories or movies, their year, and author/director, each of which followed by a comma (example: Tell-Tale Heart Poe 1843,)(type ! to end): ')
user_response_list = user_info.split()
print(user_response_list)
choice = input('What would you like to search for? (author or year)')
find_similar(choice, user_response_list)
I've tried using a loop to go through the list in order to find anything matching, but it just keeps repeating.
This might be a good time to use for loops and enumerate().
Also f-strings in python are your best friend. Google them and learn how to use them if you do not already (example includes f-strings)
def find_similar(choice, list1):
## do not need seperate variables to do a simple == check
if choice == "author":
search = input('enter name')
elif choice == "year":
search = int(input('enter year'))
else:
print(f'{choice} is not a valid choice') ## search python f-strings
return ##exits the function and returns None
for i, item in enumerate(list1): ## enumerate(somelist) returns an iterator similar to i = i+1 or i+=1 and the next item in the list.
if search == item:
if choice=="author":
print(f'{list1[i-1]}, {item}, {list1[1+1]}')
return ##exits the function and the loop
elif choice=="author":
print(f'{list1[i-2]}, {list1[i-1]}, {item}')
return ##exits the function and the loop
print('finished')
Hopefully that will help out.
I'm new to Python and learning. I'm trying to write a program to:
User input full name (with space)
Check duplication to a list (I used split and join to compare strings)
If find a duplication, re-input new name
If not, simply break the loop and print "Thanks"
I only need to print "Duplicated" or "Thanks" 1 time, not multiple times with For loop.
My issue is when I cant re-call the input with my code (with duplicated input) or break the loop (after new name)
list=["M T", "Smith Jenkins", "P T", "C P"]
while True:
user=input("Your full name :")
usercheck="".join(user.split())
print(usercheck)
for i in list:
j="".join(i.split())
if usercheck ==j:
print("Duplicated ! Please enter new name")
else:
print("Thanks")
break
You need to think about that
if the current name in the iteratation is same :that's a dup
if the current name is different : you can't conclude there is not dup now, you need to test the others
So you can use the for/else construction, the else will be executed if no break has been seen in the loop, in your case if no duplicated has been found, there you'll be able to break the while loop
names = []
while True:
user = input("Your full name :")
usercheck = "".join(user.split())
print(usercheck)
for name in names:
j = "".join(name.split())
if usercheck == j:
print("Duplicated ! Please enter new name")
break
else:
print("Thanks")
break
If that is too tricky, you can keep with a variable that will help you know whether you've seen a duplicate or not
while True:
user = input("Your full name :")
usercheck = "".join(user.split())
duplicated = False
for name in names:
j = "".join(name.split())
if usercheck == j:
print("Duplicated ! Please enter new name")
duplicated = True
break
if duplicated:
print("Thanks")
break
Made a list where I want the user to insert x followed by a number. once they have inputted, say x1, I would like x1 to be removed from the list as they are asked to input another number starting with x.
I want the list to be on loop as well, only stopping until one of the groups (of three number) has been chosen.
Disclaimer - I am a beginner at Python + Jupyter Notebook
allwins = (('x1','x2','x3'),
('x4','x5','x6'),
('x7','x8','x9'),
('x1','x4','x7'),
('x2','x5','x8'),
('x3','x6','x9'),
('x1','x5','x9'),
('x7','x5','x3'))
in_item = input("Please enter x followed by a number 1-9: ")
if in_item in allsolutions:
input("Good choice. Now pick another number starting with x: ")
else in_item not in allsolutions:
input("That did not work. Try again: ")
Idk how to keep loop for atleast a few times until the user inputs 3 diff numbers that makes a group.
You can't remove something from a tuple, so you need to make the inner tuples lists.
Then you need to loop over the main tuple, removing the input from each of them if it exists. After you do this you can check if the list is empty.
allwins = (
['x1','x2','x3'],
['x4','x5','x6'],
['x7','x8','x9'],
['x1','x4','x7'],
['x2','x5','x8'],
['x3','x6','x9'],
['x1','x5','x9'],
['x7','x5','x3'])
while True:
in_item = input("Please enter x followed by a number 1-9: ")
item_found = False
solution_found = False
for sublist in allwins:
if in_item in sublist:
sublist.remove(in_item)
item_found = True
if sublist == []:
solution_found = True
if solution_found:
print("You found all of them, congratulations!")
break
elif item_found:
print("Good choice, now pick another")
else:
print("That did not work, now try again")
I've edited my code to the following:
while(True):
#get user to input a noun as a string variable
noun = input()
#get user to input a positive number for the integer variable
number = int(input())
#if the user inputs quit into the string variable stop program
if noun == 'quit':
break
#otherwise print the output
else:
print('Eating {} {} a day keeps the doctor away.'.format(number,noun))
And I get the following error codes:
It looks like you edited the code since these answers, this should work
while(True):
noun, number = input().split()
number = int(number)
#if the user inputs quit into the string variable stop program
if noun == 'quit':
break
#otherwise print the output
else:
print('Eating {} {} a day keeps the doctor away.'.format(number,noun))
Your problem was that you're calling input twice every loop. So, noun was set to 'apples 5' and number was set to 'shoes 2' which cannot be converted to an integer. You can split the input to get your noun and number.
You should be taking the input inside the loop, otherwise it is an endless loop or if you did write quit then it would just run once. Also there is no need for the == 0 condition to break from the loop according to the problem you have presented.
The problem is that you just take the first input, just get the inputs inside the loop insted.
Also the else should be idented with the if statement and you don't need the number == 0 condition, so the resulting code should be somehting like:
while(True):
#get user to input a noun as a string variable
noun = input()
#get user to input a positive number for the integer variable
number = int(input())
if noun == 'quit':
break
else:
print('Eating {} {} a day keeps the doctor away.'.format(number,noun))
Here is how I would write. :)
while True:
noun = input("Enter a noun: ")
if noun == 'quit':
print("Quitting the program...")
break
while True:
number = input("Enter a number: ")
try:
if type(int(number)) == int:
break
except ValueError:
print("Invalid input. Please enter a number.")
if number == '0':
print("Quitting the program...")
break
print("Eating {} {} a day keeps the doctor away.".format(number, noun))
I am trying to find an item in a list without using "in" method. I tried to do it using loop. The code executed successfully, but giving collective result for both (item found as well as item not found). I tried to fix it using break statement. It somehow worked. But still not getting result as expected.
The code written in python3.2 is:-
list=[]
item=""
while item!='DONE':
item=input("Enter the number, To discontinue enter 'DONE': ")
if item.isdigit():
item=int(item)
list.append(item)
else:
list.append(item)
del list[-1]
print("The list is: ",list)
num=int(input("Enter the number you want to search in list: "))
def search(list,num):
for i in range(len(list)):
if list[i]==num:
print("Item found")
break
else:
print("Not found")
return
search(list,num)
Please suggest how I can modify it to search both "integer" as well as "string" type elements. My code is working fine for integer type element.
You're trying to convert the string to an int when you do this:
num = int(input("Enter the number you want to search in list: "))
When the input isn't a number, this will throw an exception.
Instead, why don't you just do the same thing you did in the first part of your code using isdigit()? If it's a number, cast it to an int, and if it's not a number, leave it as a string. Then your code should work for non-numbers too.
num = input("Enter the number you want to search in list: ")
if num.isdigit():
num = int(num)
Alternatively, a second solution would be not to cast anything to int in either the first or second part of your code. So in other words, keep everything as strings, i.e.
while item != 'DONE':
item = input("Enter the number, To discontinue enter 'DONE': ")
list.append(item)
...
num = input("Enter the number you want to search in list: ")
Use :
def seach(l, elm):
try:
l.index(elm)
print "found"
except:
print "not found"
It is way more pythonic than a custom loop.
PS : As you are in your learning phase, do not try to find way to perform a task. The 'in' keyword is made for it.
There's really no need to differentiate between integers and strings — they're both just values that Python can handle the same way to do what you want in this case. Given that fact, you could rewrite your code along the following lines (which includes several other techniques you could use to simplify the logic and organize your code in a more standard way — see PEP 8 - Style Guide for Python Code):
def search(a_list, value):
for item in a_list: # note: no need to use an index to iterate a list
if item == value:
print("Value found")
break
else: # only executes if loop finishes without break
print("Value not found")
my_list = [] # note: avoid using the names of built-ins like "list"
while True:
value = input("Enter an value, to discontinue enter 'DONE': ")
if value == 'DONE':
break
my_list.append(value)
print("The list is: ", my_list)
value = int(input("Enter the value you want to search for in the list: "))
search(my_list, value)
Since this is a learning exercise, I'll submit this as a search avoiding in. Others will claim it is a dirty rotten cheat. Why?
def search(inlist, item):
print(item, end="")
if inlist.__contains__(item):
print(" found")
else:
print(" not found")
mylist = []
item = None
while item != 'DONE':
item = input("Enter the number, To discontinue enter 'DONE': ")
mylist.append(item)
while True:
num = input("Enter the item you want to search for: ")
search(mylist, num)
.
.
Also in the spirit of learning, here is a solution which uses a set. We probably would not bother creating a list in the first place if we were using a set, but let's assume the list came from elsewhere.
The point here is that if you had a large list and a very large number of searches then using a set will probably be faster than iterating through the list.
def search(inset, item):
print(item, end="")
if inset & set((item,)):
print(" found")
else:
print(" not found")
mylist = []
item = None
while item != 'DONE':
item = input("Enter the number, To discontinue enter 'DONE': ")
mylist.append(item)
myset = set(mylist)
while True:
num = input("Enter the item you want to search for: ")
search(myset, num)