这是python中`in`关键字的正确用法吗?

时间:2019-04-03 11:00:07

标签: python python-3.x

我正在尝试使用if / in检查来制作一个真正的基本的子手游戏,但是,代码没有响应玩家输入的变化。由于这是我第一次使用in关键字,因此我想问一问是否正确。

我尝试了其他一些方法,例如字符串查找和分别使字母成为字符串(那是一团糟),if / in似乎是完成任务的最有效方法。如果还有其他方法,请告诉我。

#put word into here, as a string :)

print("Welcome to Hangman")
word = ["a", "v", "a", "c" "a", "d", "o"]

wordLength = len(word) + 1
lives = wordLength * 2

print("lives:", lives)
print("Letters in word", wordLength)

guess = input("h")

while lives != 0:
    if guess in word:
        print("YES!")
        print(guess)
        index = word.index(guess)
        print(index)
    else:
        print("Wrong!")
        lives - 1
    pass
pass


while lives == 0:
    print("falied! try again")
pass

理想的结果是,当输入与上述字符串中的字母匹配时,控制台将显示“ YES!”。和字母,或者如果没有打印出“错误”并夺走生命。

2 个答案:

答案 0 :(得分:0)

请检查此代码是否适合您。我做了一点修改并添加了更多条件。

#put word into here, as a string :)

print("Welcome to Hangman")
word = ["a", "v", "a", "c", "a", "d", "o"]

wordLength = len(word) + 1
lives = wordLength * 2

print("lives:", lives)
print("Letters in word", wordLength)

guess = input("Enter the letter : ")

while lives != 0:
    if guess in word:
        print("YES!")
        print(guess)
        index = word.index(guess)
        #print("Index = ",index)
        del word[index]
    else:
        print("Wrong!")
        lives -=1
    print("lives:", lives)

    if len(word)==0 and lives > 0:
        print("Success!!")
        break
    guess = input("Enter the letter : ")



if lives == 0:
    print("falied! try again")

答案 1 :(得分:0)

  

这是python中in关键字的正确使用吗?

是的,使用in关键字检查序列中是否存在值(listrangestring等是正确的,但是您的示例代码包含其他几个错误,这些错误不在主要问题的范围之内,就像下面的游戏一样……


同时,我对问题感兴趣,并编写了一个带有标签定义的快速 StackOverflow Popular Tags Hangman 游戏,即:

import requests
from random import choice

# src https://gist.github.com/chrishorton/8510732aa9a80a03c829b09f12e20d9c
HANGMANPICS = ['''
  +---+
  |   |
      |
      |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
      |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
  |   |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
 /|   |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
 /|\  |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
 /|\  |
 /    |
      |
=========''', '''
  +---+
  |   |
  O   |
 /|\  |
 / \  |
      |
=========''']


# english word_list (big)
# word_list = requests.get("https://raw.githubusercontent.com/dwyl/english-words/master/words_alpha.txt").text.split("\n")
# you can use any word_list, as long as you provide a clean (lowered and sripped) list of words.

# To create a hangman game with the most popular tags on stackoverflow, you can use:
try:
    word_list = requests.get("https://api.stackexchange.com/2.2/tags?order=desc&sort=popular&site=stackoverflow").json()['items']
    word_list = [x['name'].lower() for x in word_list if x['name'].isalpha()] # filter tags with numbers and symbols
except:
    print("Failed to retrieve json from StackExchange.") # exit here

# function that returns a random word with/out length range , uses word_list
def rand_word(_min=1, _max=15):
    # filter word_list to words between _min and _max characters
    r_word = [x.strip() for x in word_list if _min <= len(x) <= _max] #
    return choice(r_word)

# tag definition from stackoverflow wiki
def tag_info(w):
    try:
        td = requests.get(f"https://api.stackexchange.com/2.2/tags/{w}/wikis?site=stackoverflow").json()['items'][0]['excerpt']
        return(td)
    except:
        pass
        print(f"Failed to retrieve {w} definition")

# game logic (win/loose)
def play(word):
    word_l = list(word) # list with all letters of word

    wordLength = len(word_l)
    lives = 7
    print("Lives:", lives)
    print("Letters in word", wordLength)
    place_holder = ["*" for x in word_l]
    used = [] # will hold the user input letters, so no life is taken if letter was already used.
    while 1:
        print("".join(place_holder))
        guess = input().lower().strip() # get user guess, lower it and remove any whitespaces it may have
        if not guess or len(guess) > 1: # if empty guess or multiple letters, print alert and continue
            print("Empty letter, please type a single letter from 'a' to 'z' ")
            continue

        if guess in word_l:
            used.append(guess) # appends guess to used letters
            print(guess, "Correct!", guess)
            for l in word_l: # loop all letters in word and make them visible
                if l == guess:
                    index = word_l.index(guess) # find the index of the correct letter in list word
                    word_l[index] = "." # use index to substitute the correct letter by a dot (.), this way, and if there are repeated letters, they don't  overlap on the next iteration. Small hack but it works.
                    place_holder[index] = guess # make the correct letter visible on place_holder. Replaces * by guess
        elif guess in used:
            print("Letter already used.")
            continue

        else:
            used.append(guess) # appends guess to used letters
            print(HANGMANPICS[-lives])
            lives -= 1 # removes 1 life
            print(f"Wrong! Lives: {lives}" )

        if lives == 0:
            print(f"You Lost! :-|\nThe correct word was:\n{word}\n{tag_info(word)}")
            #print(HANGMANPICS[-1])
            break

        # When there are no more hidden letters (*) in place_holder the use won.
        if not "*" in place_holder:
            print(f"You Won!!!\n{word}\n{tag_info(word)}")
            break

print("Welcome to StackTag Hangman")
while 1:
    play(rand_word(1, 15)) # creates a new game with a random word between x and x letters. play() can be simply be used as play("stackoverflow").
    pa = input("Try again? (y/n)\n").lower().strip() # Ask user if wants to play again, lower and cleanup the input for comparision below.
    if pa != "y": # New game only if user input is 'y', otherwise break (exit)
        print("Tchau!")
        break

注意:

  1. 您可以play with it
  2. Asciinema视频
  3. v2,约7k的计算机行话。