Finding and replacing in a list using user input (python) - python

I need help with an extra credit portion of my assignment. The objective is to make a list and then allow the user to input their own data (in this case birds) and then it sort and return the birds. The extra credit portion is to allow the user to edit any info after. I don't know how to find/replace what a user gives it.
code:
def sorted_list():
bird_list.sort()
for i in bird_list:
print(i)
print()
print('There are', len(bird_list), 'birds in the list.')
#end for
#end def
cond = 'y'
while cond == 'y':
bird = input('Type the name of another bird (RETURN when finished): ')
if bird in bird_list:
print(bird, 'is already in the list.')
else:
bird_list.append(bird)
print(bird, 'has been added to the list.')
if bird == '':
cond = 'n'
sorted_list()
#end if
#end while
edit = input('Edit? (y/n) ')
print()
if edit == 'y':
change = input('Which bird would you like to change? ')
if change == bird_list[0]:
i = input('Enter correction ' )
else:
print('Entry not found in list')
EDIT:
resolved the edit issue using this
if edit == 'y':
change = input('Which bird would you like to change? ')
if change in bird_list:
loc = bird_list.index(change)
bird_list.remove(change)
correction = input('Enter correction ' )
bird_list.insert(loc, correction)
else:
print('Entry not found in list')

First, you can use .index to find an item's position in a list.
But there is another problem in your code, which is the reason you got the 'Entry not found on list' output when you enter a name which would be at index 0 in the list, that is the first time you enter a blank string(enter the Enter key without input nothing), you append a blank string bird name in you bird_list, and your sorted_list method sort the blank string '' in the first place of the list, here:
if bird in bird_list:
print(bird, 'is already in the list.')
# if bird is ''(first time), it will be appended to the list, too
else:
bird_list.append(bird)
print(bird, 'has been added to the list.')
if bird == '':
cond = 'n'
# and this will sort '' in the 0 index of the list
sorted_list()
the correct logic should be:
if bird in bird_list:
print(bird, 'is already in the list.')
elif bird != '':
bird_list.append(bird)
print(bird, 'has been added to the list.')
else:
cond = 'n'
sorted_list()

It looks like you intend to find the position of an arbitrary bird given their name. To find an item with a specific value in a python list, use list.index. stdtypes documentation

Related

Check element in list of array Python [duplicate]

This question already has answers here:
Check if element exists in tuple of tuples
(2 answers)
Closed 1 year ago.
I want to check if there is an element in a list of array
for example, I have:
horselist = [(1,"horse A","owner of A"), (2,"horse B", "owner of B")]
So if I want to check if "horse A" is in the list. I tried:
horsename_check = input("Enter horse name: ")
for i in horselist:
if (i[1] == horsename_check):
treatment = input("Enter treatment: ")
print("{0} found with treatment {1}".format(horsename_check,treatment))
else:
print("{0} id {1} profile is not in the database. "
"(You must enter the horse's profile before adding med records)".format(horsename_check, i[0]))
But if I input the horse name is : "horse B".
Input will also check every array in the list and print out the statement not found in array 1.
input:
Enter the horse name:horse B
horse B id 2 profile is not in the database. (You must enter the horse's profile before adding med records)
Enter treatment:
So how can I get rid of that ? Thank you.
You just need to move the else to be part of the for loop:
horsename_check = input("Enter horse name: ")
for i in horselist:
if (i[1] == horsename_check):
treatment = input("Enter treatment: ")
print("{0} found with treatment {1}".format(horsename_check, treatment))
break
else:
print("{0} id {1} profile is not in the database. "
"(You must enter the horse's profile before adding med records)".format(horsename_check, i[0]))
You need to print the "horse not found" message only after traversing all the list, not very time you find an element. And you should exit the loop after finding the correct horse, no point in iterating beyond that point. You should use for's else construct for this:
horsename_check = input("Enter horse name: ")
for i in horselist:
if i[1] == horsename_check:
treatment = input("Enter treatment: ")
print("{0} found with treatment {1}".format(horsename_check,treatment))
break
else:
print("{0} id {1} profile is not in the database. "
"(You must enter the horse's profile before adding med records)".format(horsename_check, i[0]))
horselist = [(1,"horse A","owner of A"), (2,"horse B", "owner of B")]
neededHorse = "horse B"
found = 0
for horse in horselist:
if neededHorse in horse:
found = horse[0]
if found != 0:
print("Horse found in ",found)
else:
print("Horse not found!")
This should work, you can keep a condition outside the loop and check it post the loop

Default output of input

I'm trying to make a sample code that extracts first name from a full name.
If my input is not string or simply press just enter, it will print out enter valid name.
But no matter what I type, it just prints out normal outcome.
Also if I type nothing, it just makes an error.
How can I solve this?
name = input("Enter your full name (end to stop): ")
def print_first_name():
if type(name) == str:
name.split()
first = name.split()[0]
last = name.split()[-1]
print('Your first name is: ', first)
elif name == 'end':
break
else:
print('You must enter at least your first name!')
print_first_name()
name = input("Enter your full name: ")
def print_first_name():
if len(name) > 0:
first = name.split()[0]
if first.isalpha():
print('Your first name is: ', first)
else:
print("Enter a valid name")
last = name.split()[-1]
else:
print('You must enter at least your first name!')
print_first_name()
The condition you wrote (type(name)==str) will always be true
we cant use break outside a loop. (in your case, there was no loop at all, so u cant use break)
if you enter nothing, it gives an error because the line
name.split()[0]
if name="", (which means an empty string), name.split() gives an empty list
In a empty list, there will be no element at index 0, so it gives an error.
When you say if type(name) == str:, then even when you type end as input, this condition is satisfied and the if block is executed and hence code flow never goes to the elif block.
You can put your else condition first and then the if condition:
if name == 'end':
#do whatever
elif type(name) == str:
#do whatever
else:
print('Invalid input')
Your code has a few problems, marked with comments below:
name = input("Enter your full name (end to stop): ")
# Generally you should pass a variable to a function
# or define the variable inside the function, rather
# than using a global variable (name). It's not clear
# which part of the code you want to isolate in a
# function in this example, so it's probably simplest
# not to use a function at all.
def print_first_name():
# The next test will always be True, so the else
# and elif parts will never run.
# You probably want a test for non-empty
# strings with only alphabetic characters instead
if type(name) == str:
# the next line creates a list of the parts of
# name (if possible) but doesn't store it
# anywhere, so it has no effect.
name.split()
# the next two lines will fail if name is
# an empty string
first = name.split()[0]
last = name.split()[-1]
print('Your first name is: ', first)
# the next block needs to be moved earlier to
# make sure it is tested before you try to extract
# the names
elif name == 'end':
# break cannot be used inside a function
# even if the function is called in a loop
break
else:
print('You must enter at least your first name!')
print_first_name()
Here's a version that fixes these problems:
while True:
name = input("Enter your full name (end to stop): ")
# check this first, to avoid treating as a name
if name == 'end':
break
# check whether name contains any digits or is empty
elif name.isalpha() and name != "":
name_parts = name.split()
first = name_parts[0]
last = name_parts[-1]
print('Your first name is: ', first)
else:
print('You must enter at least your first name!')
input() defaults to returning a string type. It looks like you're trying to sanitize the input by making sure the input is a string of letters, and also has a length > 0 before running.
You would probably be served by flipping out
if type(name) == str:
with something that checks both for a non-zero AND alpha only. so something like
if name.isalpha() and len(name) > 0:
{conditional code here...}
The input is always string, so you can use a array or list to store 0 -> 9 numbers (The str one). If there is a number in input, it'll print something.
You can use '' to describe that input is empty

Removing values in lists by user input (Python)

First time poster and I am very new to programming in general, (so please go easy on me) although I have worked in the IT industry as a help desk technician and field engineer.
I am in my first year at university and and have been asked to add a section on to a program to allow the user to remove entries that they have inputted into a list.
This is my code.
values = []
def programMenu():
print('This program will accept values until 0 is entered.')
choice = continueChoice()
if choice == 'Y':
ages = collectValues()
print('There are ', len(values),' in the data set.')
print('The values are as follows:', end ='')
print(values)
else:
return
def continueChoice():
print('Would you like to continue(Y/N):', end ='')
choice = str(input()).upper()
print(choice)
while choice != 'Y' and choice != 'N':
print('Invalid option. Would you like to continue(Y/N):', end ='')
choice = str(input()).upper()
return choice
def collectValues():
values = []
while True:
print ('Please enter each value:', end ="")
valValue = (int(input()))
if (valValue ==0):
break
values.append(valValue)
return values
def removeValues():
print(values)
print('Would you like to delete any entries?')
reage = str(input()).upper()
while reage == 'Y':
print('Which ages would you like to remove')
delVal = (int(input()))
values.remove(delVal)
else:
programMenu()
programMenu()
removeValues()
I have been trying to solve this for two days but I am getting an error "ValueError: list.remove(x): x not in list"
I have tried writing the removeValues code at the end of the operation to add values, I have tried to move the values = [] call around etc and have had no luck.
I checked the removeValues definition was actually taking the input by editing to get the program to print the value the user entered that they wished to be removed and that worked.
Any help is appreciated, I've only been coding a few months and I have emailed my lecturer but giving what's happening in the world at the moment the university are understaffed.
Thanks in advance.
before deleting the value from the list you need to add a if condition to check if value is present in the list or not for example:
if delVal in values:
values.remove(delVal)
else:
print('Value Not Found in the list')
and your while loop is in infinite loop as value of reage = 'Y' and you are not changing it inside the loop to stop.
you can use if statement instead of while.
def removeValues():
print(values)
print('Would you like to delete any entries?')
reage = str(input()).upper()
# if reage == 'Y'
if reage == 'Y':
print('Which ages would you like to remove')
delVal = (int(input()))
# check if delVal is present in the list or not
if delVal in values:
values.remove(delVal)
print('Deleted Age : '+ str(delVal))
print(values)
# if not then print the msg.
else:
print(str(delVal)+' Not Found in the list: ',str(values))
# you can uncomment the below code to again call removeValues function to ask for correct value to delete
#removeValues()
# if reage is not equal to 'Y' then it calls the programMenu again.
else:
programMenu()
You are not able to remove it because you are initializing the values in collectValues function each time. So the list is storing any value - just comment on this line and should work. Anyway, you also need to have exit criteria for each other functions.
values = []
def programMenu():
print('This program will accept values until 0 is entered.')
choice = continueChoice()
if choice == 'Y':
ages = collectValues()
print('There are ', len(values),' in the data set.')
print('The values are as follows:', end ='')
print(values)
else:
return
def continueChoice():
print('Would you like to continue(Y/N):', end ='')
choice = str(input()).upper()
print(choice)
while choice != 'Y' and choice != 'N':
print('Invalid option. Would you like to continue(Y/N):', end ='')
choice = str(input()).upper()
return choice
def collectValues():
#values = []
while True:
print ('Please enter each value:', end ="")
valValue = (int(input()))
if (valValue ==0):
break
values.append(valValue)
return values
def removeValues():
print(values)
print('Would you like to delete any entries?')
reage = str(input()).upper()
while reage == 'Y':
print('Which ages would you like to remove')
delVal = (int(input()))
values.remove(delVal)
else:
programMenu()
programMenu()
removeValues()
There are a few things that can be improved but I will try to keep the interface more or less the same.
The biggest issue is that functions in python have their own scope. That is, when you create a variable or list in a function, it is not shared in other functions.
What you need to do instead, (i think you had the right idea), is to create the list outside the functions and pass a reference to it as a parameter to each function:
values = []
def programMenu(values):
print('This program will accept values until 0 is entered.')
choice = continueChoice()
if choice == 'Y':
temp = collectValues()
values += temp # Append new values elementwise
print('There are ', len(values), ' in the data set.')
print('The values are as follows:', end='')
print(values)
else:
return
def removeValues(values):
print(values)
print('Would you like to delete any entries? (Y to continue)')
while str(input()).upper() == 'Y':
print('Which ages would you like to remove')
delVal = (int(input()))
values.remove(delVal)
print('Would you like to delete any entries? (pressY to continue)')
else:
programMenu(values)
programMenu(values)
removeValues(values)
The above functions need a reference to the initial list in order to manipulate it. Finally, a small change, in the removeValues() function, i moved the input in the while loop so that the question persists.
def collectValues():
values = [] # Not the same "values" list (not passed from reference)
while True:
print ('Please enter each value:', end="")
valValue = (int(input()))
if (valValue ==0):
break
values.append(valValue)
return values
If you have noticed, the collectValues() function does not need a reference since it only gets new values and later adds them to the values list. Also, by creating a new list in collectValues(), the other list is not affected ( it is entirely independent).

Python: Checks user input guess any item

I am newbie, and I need help, please. I am asking user to guess any item, if it's not correct - keeps asking. However, I am trying to do many ways but cannot get the code right. Sometimes, it's just ask 1 time and stop even if the user input is wrong; or it does not recognize the answer right or wrong and keep asking.
Thank you!
animal = ['bird','dog','cat','fish']
while True:
guess = input('Guess my favorite animal: ')
if guess == animal:
print("You are right")
break
print('Try again!')
Your code won't work because you are comparing user input to a list.
guess == animal
Will be evaluated as:
guess == ['bird','dog','cat','fish'] # Evaluates to "false"
Testing if an element is in a list is simple:
# A set of animals
animals = ['bird','dog','cat','fish']
'bird' in animals # Returns True, because bird is in the list
>>> True
'cow' in animals # Returns False, because cow is not in the list
>>> False
Assuming each 'animal' or element of the list is unique, a set is a more efficient data structure to use.
Your code then becomes:
animal = {'bird','dog','cat','fish'}
while True:
guess = input('Guess my favorite animal: ')
if guess in animal:
print("You are right")
break
print('Try again!')

checking the position of an item in one list to another list

I am trying to make a trivia game, the only problem is I am having a hard time checking for the right answer. Here is my code for one of the questions
Question2 = random.choice(mylist)
print (Question2)
Userinput = input()
if(Question2.position == Question2answer.position):
print('Yes, that is correct!')
else:
print('Sorry, wrong answer')
mylist.remove(Question2)
I am trying to check if what the user put for question 2 was the answer to question 2 and not 4 by checking the positions in the list.
The easy solution is to use the right data type for the job.
For example, if your mylist were a list of (question, answer) pairs, instead of having two separate lists;
Question2, Answer2 = random.choice(mylist)
print(Question2)
Userinput = input()
if Userinput == Answer2:
print('Yes, that is correct!')
else:
print('Sorry, wrong answer')
mylist.remove((Question2, Answer2))
Or, alternatively, with a dictionary instead of a list:
Question2 = random.choice(mydict)
print(Question2)
Userinput = input()
if Userinput == mydict[Question2]:
print('Yes, that is correct!')
else:
print('Sorry, wrong answer')
del mylist[Question2]
Why is a dict better? Well, for one thing, with a list, you have to repeatedly search through the list to find the value you want—e.g., mylist.remove starts at the beginning and compares each element to your value until it finds the right one. Besides being slow, and overly complicated, this does the wrong thing if you can ever have duplicate values (e.g., try a = [1, 2, 3, 1], then value = a[0], then a.remove(value) and see what happens…).
But if you can't change the data structures, you can always use zip to zip up a pair of separate lists into a single list of pairs on the fly:
Question2, Answer2 = random.choice(zip(mylist, myanswers))
print(Question2)
Userinput = input()
if Userinput == Answer2:
print('Yes, that is correct!')
else:
print('Sorry, wrong answer')
mylist.remove(Question2)
myanswers.remove(Answer2)
You could use namedtuple as data container.
from collections import namedtuple
import random
Question = namedtuple('Question', ['question', 'answer'])
questions = [
Question('Question 1', 'Answer 1'),
Question('Question 2', 'Secret'),
Question('Question 3', '3'),
]
q = random.choice(questions)
print("%s ?" % q.question)
user_input = raw_input().strip()
if(q.answer == user_input):
print('Yes, that is correct!')
else:
print('Sorry, wrong answer')
questions.remove(q)

Categories

Resources