2016-04-08 3 views
1

Мне нужен способ получить значение переменной, которая была определена в функции вне этой функции. Это не обязательно, но сделать мой код намного проще. До сих пор не найдено твердых ответов.Python: получение значения переменной, определенной в функции, вне этой функции

def pizzais(): 
    pizza = "yummy" 

pizzais() 
print(pizza) 

это вернет ошибку, говоря, что пицца не определена. Есть ли какой-нибудь хак, чтобы обойти это.

Слишком лучше понять мою ситуацию, вот мой код, я тоже применяю его.

def questions(): 
    user = input("What is your username?") #username 
    race = input("What is your race? (orc, human, elf, goblin)") #race 

#won't move on if the player fills an answer that is not an option 
    if race == "orc" or race == "human" or race == "elf" or race == "goblin": 
     pClass = input("What is your class? (archer, warrior, rogue or mage)") 


    else: 
     while race != "orc" and race != "human" and race != "goblin" and race != "elf": 
      race = input("What is your race? (orc, human, elf, goblin)") 
      if race == "orc" or race == "human" or race == "elf" or race == "goblin": 
       pClass = input("What is your class? (archer, warrior, rogue or mage)") 

#won't move on if the player fills an answer that is not an option    
    if pClass == "archer" or pClass == "warrior" or pClass == "rogue" or pClass == "mage": 
      correct = input("So you are " + user + ", the " + race + " " + pClass + "? (yes or no)") 

    else: 
     while pClass != "archer" and pClass != "warrior" and pClass != "rogue" and pClass != "mage": 
      pClass = input("What is your class? (archer, warrior, rogue or mage)") 
      if pClass == "archer" or pClass == "warrior" or pClass == "rogue" or pClass == "mage": 
       correct = input("So you are " + user + ", the " + race + " " + pClass + "? (yes or no)") 

    def correct_def(): 
     correct = input("So you are " + user + ", the " + race + " " + pClass + "? (yes or no)") 
     if correct == "yes": #if player likes their choices the game will begin 
      print("Enjoy the game " + user + "!") 

     elif correct == "no": #if player doesn't like their choices all questions are asked again 
      reAsk = input("What would you like to change?(username, race, class or all)") 

     else: 
      while correct != "yes" and correct != "no": 
       correct = input("So you are " + user + ", the " + race + " " + pClass + "? (yes or no)") 
      if correct == "yes": 
       print("Enjoy the game " + user + "!") 

      elif correct == "no": 
       questions() 

    if correct == "yes": #if player likes their choices the game will begin 
     print("Enjoy the game " + user + "!") 

    elif correct == "no": #if player doesn't like their choices all questions are asked again 
     reAsk = input("What would you like to change?(username, race, class or all)") 

     if reAsk == "username": 
      user = input("What is your username?") 
      correct_def() 

     elif reAsk == "race": 
      race = input("What is your race? (orc, human, elf, goblin)") 
      while race != "orc" and race != "human" and race != "goblin" and race != "elf": 
       race = input("What is your race? (orc, human, elf, goblin)") 
      correct_def() 

     elif reAsk == "class": 
      pClass = input("What is your class? (archer, warrior, rogue or mage)") 
      while pClass != "archer" and pClass != "warrior" and pClass != "rogue" and pClass != "mage": 
       pClass = input("What is your class? (archer, warrior, rogue or mage)") 
      correct_def() 

     elif reAsk == "all": 
      questions() 

     else: 
      while reAsk != "username" and reAsk != "race" and reAsk != "class" and reAsk != "all": 
       reAsk = input("What would you like to change?(username, race, class or all)") 
       if reAsk == "username": 
        user = input("What is your username?") 
        print("Enjoy the game " + user + "!") 

       elif reAsk == "race": 
        race = input("What is your race? (orc, human, elf, goblin)") 
        while race != "orc" and race != "human" and race != "goblin" and race != "elf": 
         race = input("What is your race? (orc, human, elf, goblin)") 
        print("Enjoy the game " + user + "!") 

       elif reAsk == "class": 
        pClass = input("What is your class? (archer, warrior, rogue or mage)") 
        while pClass != "archer" and pClass != "warrior" and pClass != "rogue" and pClass != "mage": 
         pClass = input("What is your class? (archer, warrior, rogue or mage)") 
        print("Enjoy the game " + user + "!") 

       elif reAsk == "all": 
        questions() 

#won't move on if the player fills an answer that is not an option 
    else: 
     while correct != "yes" and correct != "no": 
      correct = input("So you are " + user + ", the " + race + " " + pClass + "? (yes or no)") 
     if correct == "yes": 
      print("Enjoy the game " + user + "!") 

     elif correct == "no": 
      reAsk = input("What would you like to change?(username, race, class or all)") 

     if reAsk == "username": 
      user = input("What is your username?") 
      correct_def() 

     elif reAsk == "race": 
      race = input("What is your race? (orc, human, elf, goblin)") 
      while race != "orc" and race != "human" and race != "goblin" and race != "elf": 
       race = input("What is your race? (orc, human, elf, goblin)") 
      correct_def() 

     elif reAsk == "class": 
      pClass = input("What is your class? (archer, warrior, rogue or mage)") 
      while pClass != "archer" and pClass != "warrior" and pClass != "rogue" and pClass != "mage": 
       pClass = input("What is your class? (archer, warrior, rogue or mage)") 
      correct_def() 

     elif reAsk == "all": 
      questions() 

     else: 
      while reAsk != "username" and reAsk != "race" and reAsk != "class" and reAsk != "all": 
       reAsk = input("What would you like to change?(username, race, class or all)") 
       if reAsk == "username": 
        user = input("What is your username?") 
        print("Enjoy the game " + user + "!") 

       elif reAsk == "race": 
        race = input("What is your race? (orc, human, elf, goblin)") 
        while race != "orc" and race != "human" and race != "goblin" and race != "elf": 
         race = input("What is your race? (orc, human, elf, goblin)") 
        print("Enjoy the game " + user + "!") 

       elif reAsk == "class": 
        pClass = input("What is your class? (archer, warrior, rogue or mage)") 
        while pClass != "archer" and pClass != "warrior" and pClass != "rogue" and pClass != "mage": 
         pClass = input("What is your class? (archer, warrior, rogue or mage)") 
        print("Enjoy the game " + user + "!") 

       elif reAsk == "all": 
        questions() 
questions() 
+2

Зачем вам «взломать»? Это то, на что «возврат». – tzaman

+2

какую часть в стене кода мы должны смотреть, чтобы лучше понять ваш вопрос? Где ваша проблема? – Keatinge

+0

В основном я хочу использовать гонку, pClass, имя пользователя вне вопросов() – Shniper

ответ

2

Возможно, вы должны прочитать Tutorial section on functions - это примерно самая простая вещь, которую вы используете для функций для.

Ваш пример кода представляет собой гигантский беспорядок, но вот быстрый пример того, что вы, кажется, пытается сделать:

def ask_race(): 
    race = None 
    options = ['orc', 'human', 'elf', 'goblin'] 
    while race not in options: 
     race = input('What is your race? ({})'.format(','.join(options))) 
    return race 

Повторите для других вариантов, то вы можете сделать что-то вроде:

def questions(): 
    race = ask_race() 
    character_class = ask_class() 

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

+0

Да, я знаю, что это беспорядок, я научил себя js и вам нужно создать игру на питоне для одного из моих классов с очень ограниченными знаниями, полученными от профессора. Поэтому большинство из них - это игра с тем, как превратить js в python. Извините – Shniper

+1

Второй снипп недействителен, так как 'class' не является допустимым именем переменной –

+0

Oh derp, fixed. – tzaman

2

Два способа сделать это, один рекомендуется и один не так много. Вы не должны беспорядок вокруг с глобальными переменными, если вы не знаете, что делаете. То, что вы пытаетесь сделать, должно на 100% использовать возврат. Но чтобы быть включенным, я положил его, потому что мог теоретически выполнить то, что вы пытаетесь сделать.

Лучшие практики: Использование Return

def pizzais(): 
    return "yummy" 

pizza = pizzais() 
print(pizza) 

плохая идея: Использование глобальных переменных

pizza = "" 

def pizzais(): 
    global pizza 
    pizza = "yummy" 


pizzais() 

print(pizza) 

Повторные несколько переменных

def get_three_variables(): 
    var1 = "text1" 
    var2 = "text2" 
    var3 = "text3" 
    return (var1, var2, var3) 


response = get_three_variables() 
print(response) 
#this prints: ('text1', 'text2', 'text3') 

print(response[0]) 
#this prints text1 

print(response[1]) 
#this prints text2 
+0

поэтому, если у меня есть несколько переменных в функции и возвращаю каждую переменную в функции, как я могу получить значение каждой из этих переменных вне функции? – Shniper

+0

возвращает кортеж из нескольких переменных – Keatinge

+2

Технически «глобальный» - это противоположность - он использует переменную, определенную * снаружи * внутри нее. – tzaman

0

Вы пытаетесь напечатать pizza, но что такое пицца? Вы не определили его нигде, кроме как в своей функции, и вы ничего не возвращаете. Это local переменная, тогда как при попытке распечатать пиццу вне сферы действия вашей функции ищет переменную global. Вы можете проверить это question для локальных и глобальных переменных. Вы можете установить pizza = pizzais(), а затем сделать print(pizza), если вы установили return "yummy" в конце вашей функции. Без использования return в конце вашей функции он будет возвращать None по умолчанию.

1
  1. возвращать несколько значений в виде кортежа return x, y, z и распаковывать возвращаемое значение как x, y, z = func().
  2. Вы можете использовать глобальные переменные. Устанавливая значения внутри функции, сначала объявляйте global x, а затем x = something.Но лучше избегать глобальных переменных .
  3. Если вы обнаружите, что меняете глобальное состояние много, использование class является более подходящим.
  4. Вы можете использовать блокировочные устройства для поддержания состояния. Но для этого нужен другой дизайн, и вы должны это сделать, если вам удобнее выполнять функции более высокого порядка. Закрытия в принципе легкие и намного быстрее, чем классы (Beazly).
Смежные вопросы