我正在练习我的 Python 技能。我目前已进入第四周,并坚持完成一项特定任务。如果用户在我的 self.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()
最佳答案
您可以使用set
来获取唯一元素,然后将其长度与答案长度进行比较
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')
...
关于python - 如果用户在Python中输入相同的字符串两次,如何打印特定的消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65048234/