python - 如果用户在Python中输入相同的字符串两次,如何打印特定的消息?

标签 python python-3.x

我正在练习我的 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/

相关文章:

python - 从 python 中的位和生成校验和

python打字模块: Mixin

python - 通过列表理解简化函数中的嵌套 ifs

python - 网络摄像头无法在 Ubuntu 12.04 上使用 OpenCV 2.4 的 python 接口(interface)

python - 如何在 for 循环中创建多个复选框?

python-3.x - 将特定范围内的所有BGR值转换为白色(255,255,255)

Python 康威生命游戏实现

python - 列表理解同时迭代两个变量

python - 在 python 3 中使用 boto

python - 如何在 Python (Mac) 中将扫描的 PDF 转换为可搜索的 PDF?例如OCRMYPDF模块