Найти - Пользователи
Полная версия: Помогите с кодом
Начало » Python для новичков » Помогите с кодом
1
Samscara
Привет ребята, учу питон по книжке доусона, и все вроде бы шло нормально, пока не встретилась вот эта задача:
# Hangman Game
#
# The classic game of Hangman.  The computer picks a random word
# and the player wrong to guess it, one letter at a time.  If the player
# can't guess the word in time, the little stick figure gets hanged.
# imports
import random
# constants
HANGMAN = (
"""
 ------
 |    |
 |
 |
 |
 |
 |
 |
 |
----------
""",
"""
 ------
 |    |
 |    O
 |
 |
 |
 |
 |
 |
----------
""",
"""
 ------
 |    |
 |    O
 |   -+-
 | 
 |   
 |   
 |   
 |   
----------
""",
"""
 ------
 |    |
 |    O
 |  /-+-
 |   
 |   
 |   
 |   
 |   
----------
""",
"""
 ------
 |    |
 |    O
 |  /-+-/
 |   
 |   
 |   
 |   
 |   
----------
""",
"""
 ------
 |    |
 |    O
 |  /-+-/
 |    |
 |   
 |   
 |   
 |   
----------
""",
"""
 ------
 |    |
 |    O
 |  /-+-/
 |    |
 |    |
 |   | 
 |   | 
 |   
----------
""",
"""
 ------
 |    |
 |    O
 |  /-+-/
 |    |
 |    |
 |   | |
 |   | |
 |  
----------
""")
MAX_WRONG = len(HANGMAN) - 1
WORDS = ("OVERUSED", "CLAM", "GUAM", "TAFFETA", "PYTHON")
# initialize variables
word = random.choice(WORDS)   # the word to be guessed
so_far = "-" * len(word)      # one dash for each letter in word to be guessed
wrong = 0                     # number of wrong guesses player has made
used = []                     # letters already guessed
print("Welcome to Hangman.  Good luck!")
while wrong < MAX_WRONG and so_far != word:
    print(HANGMAN[wrong])
    print("\nYou've used the following letters:\n", used)
    print("\nSo far, the word is:\n", so_far)
    guess = input("\n\nEnter your guess: ")
    guess = guess.upper()
    
    while guess in used:
        print("You've already guessed the letter", guess)
        guess = input("Enter your guess: ")
        guess = guess.upper()
    used.append(guess)
    if guess in word:
        print("\nYes!", guess, "is in the word!")
        # create a new so_far to include guess
        new = ""
        for i in range(len(word)):
            if guess == word[i]:
                new += guess
            else:
                new += so_far[i]              
        so_far = new
    else:
        print("\nSorry,", guess, "isn't in the word.")
        wrong += 1
if wrong == MAX_WRONG:
    print(HANGMAN[wrong])
    print("\nYou've been hanged!")
else:
    print("\nYou guessed it!")
    
print("\nThe word was", word)
input("\n\nPress the enter key to exit.")

задача сама по себе не сложная, но вот эта часть повергает меня в ступор:
   if guess in word:
        print("\nYes!", guess, "is in the word!")
        # create a new so_far to include guess
        new = ""
        for i in range(len(word)):
            if guess == word[i]:
                new += guess
            else:
                new += so_far[i]              
        so_far = new
    else:
        print("\nSorry,", guess, "isn't in the word.")
        wrong += 1
То есть понятно, мы создаем новую переменную, которой будем приписывать новое значение новое значение so_far, затем запускаем функцию range, а вот дальше я не очень понимаю, что происходит, может кто-нибудь объяснить?
ZerG
if guess in word:
        print("\nYes!", guess, "is in the word!")
        # create a new so_far to include guess
        new = ""
        for i in range(len(word)):
            if guess == word[i]:
                print('guess = ', guess, 'word= ', word[i])
                new += guess
            else:
                new += so_far[i]
        so_far = new
        print('so_far=', so_far)
    else:
        print("\nSorry,", guess, "isn't in the word.")
        wrong += 1

Другими словами учимся понимать - ставим принты промежуточные и смотрим что зашло - что вышло. Анализируем.
allcaponne
Все просто ;-) range это последовательность цифр от 0 до того значения что указан в скобках, len показывает количество символов переменной word, т.е если у вас переменной word присвоено значение ‘hello’ ,то это равносильно range(5)
Samscara
allcaponne
Это понимаю) мне не совсем понятна последующие условия if/else
allcaponne
по русски это звучит так, если guess равна каждому итерируемому значению переменной word, то вывести в консоль ‘guess = ’, guess, ‘word= ’, word и к переменной new добавить значение guess
если условие if не выполняется то переходим к блоку else, в данном блоке к переменной word добавлем значение so_far
после окончания цикла переменной so_far присваиваем значение new и выводим в консоль ‘so_far=’, so_far
далее если не выполнилось первое условие if guess in word в консоль выводим “\nSorry,”, guess, “isn't in the word.” и увеличиваем переменную wrong на одну единицу
ZerG
Сомневаюсь что он вас понял
Пусть ставит принты и учится
Samscara
allcaponne
так гораздо лучше, спасибо!)
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB