Reputation: 47
I am practicing my Python skills. I am currently on week 4 and stuck on doing a specific task. If a user enter the same string twice in my self.songs input I want to print a message saying "You can't enter the same song twice. Try again".
How can I do this? Also, is there a way for the user the use commas instead of white space to separate each string while inputing their favourite songs?
class User:
def __init__(self):
self.name = ''
self.songs = ()
self.movies = ()
self.sports = ()
def tops(self):
self.name = input("What's you're full name?:")
while True:
self.songs = input('Hi ' + self.name + ', what is your top 5 favorite songs?:').split()
if len(self.songs) > 5:
print('You entered more than 5 songs. Try again')
elif len(self.songs) < 5:
print('You entered less than 5 songs. Try again')
elif len(self.songs) == 5:
for song in self.songs:
print(song)
confirm_input = input('Do you confirm?')
if confirm_input == 'Yes':
print(type(self.songs))
print(self.songs)
break
elif confirm_input == 'No':
continue
quizUser = User()
quizUser.tops()
Upvotes: 2
Views: 1061
Reputation: 54148
You may use a set
to get unique element, then compare its length with the answer length
if len(set(self.songs)) != len(self.songs):
print("You can't enter the same song twice. Try again")
elif len(self.songs) > 5:
print('You entered more than 5 songs. Try again')
elif len(self.songs) < 5:
print('You entered less than 5 songs. Try again')
...
Upvotes: 2
Reputation: 2277
You can use set
to get no same elements, and compare it's length with the normal list by using !=
.
add this to your code:
elif len(set(self.songs)) != len(self.songs):
print('You can\'t enter the same song twice. Try again')
by the way, \'
means escaping '
.
The whole code:
class User:
def __init__(self):
self.name = ''
self.songs = ()
self.movies = ()
self.sports = ()
def tops(self):
self.name = input("What's you're full name?:")
while True:
self.songs = input('Hi ' + self.name + ', what is your top 5 favorite songs?:').split()
if len(self.songs) > 5:
print('You entered more than 5 songs. Try again')
elif len(self.songs) < 5:
print('You entered less than 5 songs. Try again')
elif len(self.songs) != len(set(self.songs)):
print('You can\'t enter the same song twice. Try again')
elif len(self.songs) == 5:
for song in self.songs:
print(song)
confirm_input = input('Do you confirm?')
if confirm_input == 'Yes':
print(type(self.songs))
print(self.songs)
break
elif confirm_input == 'No':
continue
quizUser = User()
quizUser.tops()
Upvotes: 1