1

I am new to programming and I am re-creating a game and there are loops that I created a temp variable to do a check and after the loop is done, I del temp.

i.e.

temp = True
while temp:
    player_input = input('Do you want to start with 100 chips or 200 chips? [100 or 200]: ') # input is saved as str
    if player_input == '100':
        chips = 100
        temp = False
    elif player_input == '200':
        chips = 200
        temp = False
    else:
        print('That was invalid, try again.')
del temp

My question is, is this a good practice? I was thinking of using functions so I can use return 100 or return 200 but I will only do this once so it seems wasteful to keep a function in memory that I will only use once. I am not sure if keeping scrolling up and down on multiple functions for 1 setting at a time is readable, or switching between 2 different files (one main and one with all the functions) just for functions that will be used only once is readable either, but then again, this may not be readable to other as it is to me.

what would be the best practice to write the code above?

  • 1
    does this https://stackoverflow.com/q/39255371/13743233 answer your question? – Pablo C Jan 15 '21 at 05:52
  • There are temponary variables in terms of scope. So in your code snippet, chips would be deletet after the respective `if` or `elif` block, but probably it would be defined somewhere above. – Cadoiz Jan 15 '21 at 05:55
  • 2
    Yes, there are temporary variables, often referred to as *local* variables. As far as best practice is concerned, I'd go with write code which is easy to understand, and can be read quickly. Don't worry too much about your resource consumption unless you're feeling its impact. As you keep learning, you'll automatically start writing better performing code. – 4amvim Jan 15 '21 at 05:56
  • Pablo C: That is somewhat what I have been doing (I didn't know about gc.collect() ) Cadoiz: chips would still be used, only temp would be deleted codesPliff: ok, thanks for the advice – Tenshi Sora Jan 15 '21 at 06:08
  • If you're really worried about performance, then you'll be using a language that isn't python. `del` is almost never really necessary - just create variables where they're needed (note that if you create a 'local variable' inside a loop or conditional, it doesn't actually get reallocated every iteration, just reassigned, because python doesn't treat loops as their own scopes) and let the garbage collector get rid of them when the function finishes executing. – Green Cloak Guy Jan 15 '21 at 06:30

0 Answers0