Странная проблема с вызовом функций в Python - PullRequest
0 голосов
/ 25 сентября 2018

Я просто пытаюсь написать код для себя, и у меня есть проблема с вызовом определенной функции в моем коде, и это странно, потому что у меня уже есть еще 2 функции, как эта, и они делают свою работу правильно, проверьте это

import random

name = ("aghayan","jafari","panahi","kashkool")
word = random.choice(names)
dash_guess = "-" * len(word)
guesses_left = 5
class hangman():
    def Entrance():
        print(" one of your python classmates was an undercover cop and set a ")
        print(" trap for our Boss Mohammad Esmaili!'THE CARTEL KING' so they arrest him .")
        print(" we just need that snitch name and your the only person of that")
        print(" class that we have access to , so your going to tell us the snitch")
        print(" name or i will hang you my self and you got only 5 chances to ")
        print(" tell me his or hers name or you'll die")
        print()
        def repeat():

            your_choice =input(" so will you help me or you want to die ? 'yes' or 'no' : ")

            if your_choice == "yes":
                print("Good it seems you have someone waiting for you and you want to ")
                print("see him/her again , you better be telling the truth or i,ll go ")
                print("and pay a visit to your love")
                core_game(guess)


            elif your_choice == "no":
                print("ok good choice , it will be my pleasure to kill you ")
                print("________      ")
                print("|      |      ")
                print("|      0      ")
                print("|     /|\     ")
                print("|     / \     ")
                print("|             ")
                print("Adios my friend , i hope you rest in peace in HELL")
                exit()

            else :
                print(" it seems the noose tightens around your neck and its getting")
                print(" hard to talk but i just need 'yes' or 'no' for answer")
                repeat()
        repeat()
    Entrance() 
    def core_game(guess):
         while guesses_left > 0 and not dash_guess == word:
             guess = input("so tell me that snitch name letter by letter : ")
         if guess != 1:
             print("NOPE , i need you to spell the name of that rat")

    core_game(guess)




game = hangman()

Это не завершено, но вопрос в том, что, когда я ввожу 'да', программа должна определить def core_game (), но это дает мне ошибку, что "core_game не определено".

1 Ответ

0 голосов
/ 25 сентября 2018

В этом разделе ваша проблема:

def core_game(guess):
     while guesses_left > 0 and not dash_guess == word:
         guess = input("so tell me that snitch name letter by letter : ")
     if guess != 1:
         print("NOPE , i need you to spell the name of that rat")

core_game(guess)

Отсутствие отступа в последней строке исключает вас из определения класса. Другими словами, вы звоните core_game из глобальной области видимости (где он не определен), а не из класса (там, где он определен).

Python требователен к отступам и форматированию;Я бы посоветовал вам потратить некоторое время на то, чтобы научиться правильно форматировать код для Python, что не только поможет вам уменьшить количество ошибок, но и значительно облегчит чтение кода для вас и всех остальных.

Ваше решение состоит в том, чтобы полностью удалить звонок core_game(guess).Вам это не нужно, потому что вы уже звоните Entrance(), и это вызывает core_game в нужных вам точках.

У вас также есть другая проблема - ваш метод core_game имеетпараметр guess, но в этом нет необходимости, и вам трудно правильно его назвать:

def core_game(guess):
    while guesses_left > 0 and not dash_guess == word:
        # On this line, you're overwriting the value of the guess parameter
        # before you've actually read it. Hence, you don't actually
        # need that parameter at all.
        guess = input("so tell me that snitch name letter by letter : ")
    if guess != 1:
        print("NOPE , i need you to spell the name of that rat")

И, где вы его называете:

if your_choice == "yes":
    print("Good it seems you have someone waiting for you and you want to ")
    print("see him/her again , you better be telling the truth or i,ll go ")
    print("and pay a visit to your love")

    # At this point, guess is not defined, so you're not passing anything
   # to the core_game function.
    core_game(guess)

Учитывая, что (а) вы ничего не передаете, и (б) вы на самом деле никогда не используете параметр, вы можете просто удалить его.

После всех предложений, приведенных выше, вот как выглядит ваш код:

import random

name = ("aghayan", "jafari", "panahi", "kashkool")
word = random.choice(names)
dash_guess = "-" * len(word)
guesses_left = 5

class Hangman():
    def entrance(self):
        print(" one of your python classmates was an undercover cop and set a ")
        print(" trap for our Boss Mohammad Esmaili!'THE CARTEL KING' so they arrest him .")
        print(" we just need that snitch name and your the only person of that")
        print(" class that we have access to , so your going to tell us the snitch")
        print(" name or i will hang you my self and you got only 5 chances to ")
        print(" tell me his or hers name or you'll die")
        print()

        def repeat():
            your_choice =input(" so will you help me or you want to die ? 'yes' or 'no' : ")

            if your_choice == "yes":
                print("Good it seems you have someone waiting for you and you want to ")
                print("see him/her again , you better be telling the truth or i,ll go ")
                print("and pay a visit to your love")
                core_game(guess)


            elif your_choice == "no":
                print("ok good choice , it will be my pleasure to kill you ")
                print("________      ")
                print("|      |      ")
                print("|      0      ")
                print("|     /|\     ")
                print("|     / \     ")
                print("|             ")
                print("Adios my friend , i hope you rest in peace in HELL")
                exit()

            else:
                print(" it seems the noose tightens around your neck and its getting")
                print(" hard to talk but i just need 'yes' or 'no' for answer")
                repeat()

        repeat()

    def core_game(self):
        while guesses_left > 0 and not dash_guess == word:
            guess = input("so tell me that snitch name letter by letter : ")
        if guess != 1:
            print("NOPE , i need you to spell the name of that rat")

game = Hangman()
game.entrance()

Я также применил некоторые стилистические исправления и исправил отступ здесь.У вас также есть логическая ошибка, но я оставлю это как упражнение для вас, чтобы разобраться.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...