2017-06-02 49 views
-3

如果我輸入一個愛好,例如gaming,如果我多次輸入相同的愛好,如何獲得提示?我不希望它接受重複的愛好如何在Python中輸入相同的答案時得到提示,如下面給出的輸入函數

我的代碼:

hobbies = [] 

chance=3 
while chance>0: 
    hobbie= input("What's your hobbie\n") 
    chance=chance-1 
    hobbies.append(hobbie) 

print (hobbies) 
+3

請張貼在這個問題你的代碼,而不是鏈接到外部網站。 –

+2

請將它作爲_text_發佈,而不是圖片。您可以突出顯示一個代碼塊,然後按Ctrl + K或單擊'{}'按鈕將其縮進四個空格,導致堆棧溢出將其呈現爲代碼。 – Chris

+0

謝謝指出。 –

回答

1

只需使用和if語句來檢查,如果有一定的愛好就是已經進入。如果它沒有將它添加到列表中,並且不更新你的循環計數器。把下面的代碼放在循環中,替換這兩行代碼。

hobbie = input("what's your hobbi\n") 
if hobbie not in hobbies: 
    chance -= 1 
    hobbies.append(hobbie) 
else: 
    print("Hobby already entered.") 
0

添加另一個while語句

hobbies = [] 

# Add your code below! 
change = 3 

while change > 0: 
    hobbie = raw_input("What's your hobbie\n") 
    while hobbie in hobbies: 
     hobbie = raw_input("Hobbie already in list. What's your hobbie\n") 
    change -=1 
    hobbies.append(hobbie) 

print hobbies 
+0

這使O(n)的複雜性正確嗎?爲什麼不在循環中使用條件而不是額外的循環? – Jeremy

+0

我認爲你的第二個條件是錯誤的。我認爲它也不會使複雜性翻番。您也可以在分配之前參考hobbie。 –

+0

@MarkBeilfuss有幾個錯誤 –

-1

商店的愛好在一組。輸入興趣愛好時,請檢查它是否在關鍵字in的集合中。

例子:

hobbies = set() 
done = False 
while not done: 
    hobby = input('What is your hobby? ') 
    if hobby.lower() not in hobbies: 
     hobbies.add(hobby.lower()) 
     done = True 
    else: 
     print('You've already entered that hobby! Try again.') 
+0

如果你打算低調回答,至少要禮貌地說出爲什麼它沒有幫助。 @MehulChaturvedi表示他們不希望數據中出現重複內容,因此使用一個集合是實現這一點最簡單和最有效的方法。 –

相關問題