Правильно передавая переменные в функции - PullRequest
2 голосов
/ 10 ноября 2019

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

Я попытался возиться с вкладками и изменить некоторые переменные, но мне не повезло.

Текущее сообщение об ошибке:

Traceback (most recent call last):

  File "C:/Users/iamep/Desktop/Python Projects/RockPaperScissors.py", line 96, in <module>
        main()
      File "C:/Users/iamep/Desktop/Python Projects/RockPaperScissors.py", line 90, in main
        runGame(rounds)
    NameError: name 'rounds' is not defined

Код:

#display Welcome Message
def welcomeMsg():
    print ("Welcome to Rock Paper Scissors")

#User Inputs Number of Rounds
def roundChoice():
    user_input = input('Enter Number of Rounds: ')          
    try:
            rounds = int(user_input)
    except ValueError:
            print('Not a number')
    return rounds
def runGame(rounds):

    import random                         #imports a random module for the computer.
    game = ["ROCK", "PAPER", "SCISSORS"]  #sets the game answers.
    count = 0                             #game count is set to zero.
    score = 0                             #player score is set to zero.
    computerscore =0                      #computers score is set to zero.

    while count == 0:                                       #starts game if count is zero.
      for i in range (rounds):                              #repeats the turns to the user specified rounds
        answer = input ("Pick rock, paper or scissors: ")   #users input their choice

        print (answer.upper())                               #prints the users answer
        computer= random.choice(game)                        #computer picks randomly

        print ("Computer picks",computer)                            #Display Computer Option
        if answer.upper() == "ROCK" and computer == "ROCK":          #This whole set of code sets the game that what beats what.
          print ("Its a tie!")                                       # prints after each response that who won.
          count +=1                                                  #the count variable is increased.

        elif answer.upper() == "PAPER" and computer == "PAPER":
          print ("Its a tie!")
          count +=1

        elif answer.upper() == "SCISSORS" and computer == "SCISSORS":
          print ("Its a tie!")
          count +=1

        elif answer.upper() == "PAPER" and computer == "ROCK":
          print ("You win!")
          count +=1
          score +=1                                                 #If User Wins Score is Added

        elif answer.upper() == "PAPER" and computer == "SCISSORS":
          print ("You lose!")
          count +=1
          computerscore +=1                                         #IF Computer Wins computerscore is added
        elif answer.upper() == "ROCK" and computer == "PAPER":
          print ("You lose!")
          count +=1
          computerscore +=1

        elif answer.upper() == "ROCK" and computer == "SCISSORS":
          print ("You win!")
          count +=1
          score +=1

        elif answer.upper() == "SCISSORS" and computer == "ROCK":
          print ("lose!")
          count +=1
          computerscore +=1

        elif answer.upper() == "SCISSORS" and computer == "PAPER":
          print ("You win!")
          count +=1
          score +=1
        return score, computerscore

def gameResults(score, computerscore):
    if score < computerscore:                      #Display round results
      print ("Your score is", score)
      print ("Computers score is",computerscore)
      print ("Computer wins!.")

    if score > computerscore:
      print ("Your score is", score)
      print ("Computers socre is",computerscore)
      print ("You win!.")

    if score == computerscore:
      print ("Your score is", score)
      print ("Computers socre is",computerscore)
      print ("Its a tie!!.")
def main():
    welcomeMsg()
    roundChoice()
    runGame(rounds)
    gameResults(score, computerscore)

1 Ответ

2 голосов
/ 10 ноября 2019

У вас нет rounds в вашей основной, поэтому это вызывает ошибку. Вы возвращаете rounds из roundChoice(), но не присваиваете ему какую-либо переменную. Я назначил его и передал runGame() для ожидаемого поведения. Ваша main реализация должна быть:

def main():
    welcomeMsg()
    rounds=roundChoice()
    runGame(rounds)
    gameResults(score, computerscore) 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...