Skip to main content
 首页 » 编程设计

python之如何避免重复字符串

2025年05月04日31shangdawei

我的代码是:

import random 
WORDS = ('python', 'football', 'facebook', 'photo') #list of words that will be riddled 
word = random.choice(WORDS) 
correct = word 
jumble = '' 
hint = 'hint' 
score = 0 
while word: 
    position = random.randrange(len(word)) 
    jumble += word[position]  
    word = word[:position] + word[(position + 1):] #creating jumble of correct words 
print('Welcome to the game "Anagrams"') 
print('Here`s your anagram:', jumble) #Welcoming and giving a jumble to a player 
guess = input('\nTry to guess the original word: ') 
if guess == correct: 
    score += 5 
    print('You won! Congratulations!') #end of game in case of right answer 
if guess == hint: #situation if player asks a hint 
    if correct == WORDS[0]: 
        print('snake') 
    elif correct == WORDS[1]: 
        print('sport game') 
    elif correct == WORDS[2]: 
        print('social network') 
    elif correct == WORDS[3]: 
        print('picture of something') 
    score += 1 
while guess != correct and guess != '': #situation if player is not correct 
    print('Sorry, you`re wrong :(') 
    guess = input('Try to guess the original word: ') 
print('Thank you for participating in game.') 
print('Your score is', score) 
input('\nPress Enter to end') 

询问提示字符串时:

'Sorry, you`re wrong :('

重复。
看起来像:

Try to guess the original word: hint
sport game
Sorry, you`re wrong :(

如何让这个字符串只在猜错的情况下出现?

请您参考如下方法:

最后把你改成这样:

while guess != correct and guess != '': 
    guess = input("Sorry, you`re wrong:( ")