Home > other >  What can I do to make my code more efficient and not use global variables
What can I do to make my code more efficient and not use global variables

Time:04-08

So today I built a very simple number guessing game and the below code is what I wrote. I understand that it's incredibly inefficient and I use global too much, which is generally known as a bad practice. What advice would you give to me, a beginner in Python, to overcome this problem?

import random

print(logo)
print("Heya! Welcome to Bull's Eye Number!")

global lives
lives = 0
global game_ended
game_ended = False
global selected_number
selected_number = random.randint(1,100)
global player_guess
player_guess = 0

def select_difficulty():
  global lives
  player_difficulty = input("Alright! To start, select a difficulty,'Easy' or 'Hard': ")
  if player_difficulty == "Easy":
    lives = 10
  elif player_difficulty == "Hard":
    lives = 5

def make_a_guess():
  global player_guess
  player_guess = int(input("What do you think the number might be?:  "))

def adjust_lives():
  global selected_number
  global lives
  if not player_guess == selected_number:
    lives -= 1
    print(f"You now have {lives} lives left")

  
def check_game_ended():
  global game_ended
  global selected_number
  if lives == 0:
    game_ended = True
    print(f"Oh no! You didn't manage to guess it. The number was {selected_number}. Better luck next time!")
  elif player_guess == selected_number: 
    game_ended = True
    print(f"You guessed it right! The number was infact {selected_number}")

def evaluate_guess():
  global player_guess
  global selected_number
  if player_guess > selected_number:
    print("Your guess was a bit too High.")
  elif player_guess < selected_number:
    print("Your guess was a bit too Low")

select_difficulty()
print(f"You've got {lives} lives to start! ")
while game_ended == False:
  make_a_guess()
  evaluate_guess()
  adjust_lives()
  check_game_ended()

CodePudding user response:

What about:

def select_difficulty():
  player_difficulty = input("Select a difficulty,'Easy' or 'Hard': ")
  if player_difficulty == "Easy":
    return  10
  return 5

lives = select_difficulty()

Then pass lives as parameter to other functions.

CodePudding user response:

  • You don't need the global keyword at top-level code. The variables outside functions are global by default.
  • To make your code cleaner you can utilize modules and/or classes. But if you want to have everything in one file, I don't see a problem with your code. Also, you can pass your variables to the functions and make them return their modified values if you don't want to use global variables.
  • Related