Reputation:
newWord = print(input('Enter a word: '))
myList = ["apple", "mango"]
def ifWordAlreadyExists(str):
for x in myList:
if x == str:
index = index(x)
query = print(input('Word ', x ,'is already in index ', index , 'are you sure you want to include it? '))
if query == 'y':
return str
else:
return 0
myList.append(ifWordAlreadyExists(newWord))
print(myList)
Output
Enter a word: apple
apple
['apple', 'mango', None]
Why is query not showing and newWord not appending to myList? PS. I'm a beginner in Python so I would appreciate if someone could point put what I'm doing wrong :))
Upvotes: 0
Views: 91
Reputation: 1
You can use the count()
to find duplicates in a list.
def check_duplicates(lst: list):
for item in lst:
if lst.count(item) > 1:
return item
else:
return "No Duplicates!"
Upvotes: 0
Reputation: 770
Basically print()
returns None
and you don't need to place input()
method in print()
because input()
can also print something to the screen but accept an input.
You can change the code to:
myList = ["apple", "mango"]
newWord = input('Enter a word: ')
check = newWord in myList
if not check:
myList.append(newWord)
else:
print('Word', newWord ,'is already on the list are you sure you want to include it?', end=" ")
query = input().lower().startswith('y')
if query:
myList.append(newWord)
print(myList)
Output
Enter a word: apple
Word apple is already on the list are you sure you want to include it? yes
['apple', 'mango', 'apple']
Upvotes: 1
Reputation: 7676
newWord
is None
if you use newWord = print(input('Enter a word: '))
, it should be newWord = input('Enter a word: ')
. Besides, you don't have to use a for loop inside the function, the method index
of a python list can solve it directly, for example
newWord = input('Enter a word: ')
myList = ["apple", "mango"]
def ifWordAlreadyExists(to_check):
try:
idx = myList.index(to_check)
query = input('%s is already in the list, are you sure you want to include it? ' % to_check)
if query == 'y': return to_check
return 0
except ValueError:
return to_check
myList.append(ifWordAlreadyExists(newWord))
print(myList)
Upvotes: 0
Reputation: 719
The print function does not return any values
If you want to print the entered value, you must use print on the bottom line.
newWord = input("Word:")
print(newWord) #like this
myList = ["apple", "mango"]
def ifWordAlreadyExists(str):
for x in myList:
if x == str:
index = myList.index(x)
query = input("Word {0} is already in index {1} are you sure you want to include it:".format(str,index))
if query == 'y':
return str
else:
return 0
myList.append(ifWordAlreadyExists(newWord))
print(myList)
Upvotes: 0