Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Global vs local variable
#1
Hi I'm a teacher and I just began learning Python so I can show some tips to my students. I code a little math game and I have an issue with global vs local variable.

I'm trying to define 2 games and launch the first one and the second on a condition (bonne == 3), but I don't know how to do this.

(I'm a french speaking teacher, so sorry for my poor english)
Thank you


import random
import time
print ('Bienvenue')

def GAME() :
  bonne = 0
  mauvaise = 0
  jeu = 0
  while True :
    a= int(random.randint (0,10))
    b = int(random.randint (0,10))
    reponse = a+b
    
    print (str(a) + '+' + str(b) + '=' + '?')
    joueur = input ('Quelle est la bonne réponse ?')
    time.sleep (0.5)
    
    if int(joueur) == reponse :
      print ('Bravo')
      bonne = bonne + 1
      time.sleep(0.3)
      print ('Tu as ' + str(bonne) + ' bonnes réponses et ' + str(mauvaise) + ' mauvaises réponses') 
    
    else :
      print ('VRAIMENT !!!')
      mauvaise = mauvaise + 1
      time.sleep(0.3)
      print ('Tu as ' + str(bonne) + ' bonnes réponses et ' + str(mauvaise) + ' mauvaises réponses') 
    
    if bonne == 3 :
      print ('Tu as complété le jeu avec ' + str(mauvaise) + ' mauvaise réponse')
      jeu = jeu + 1
      break
    
    if mauvaise == 3 :
      print ('Trop de mauvaises réponses')
      time.sleep (0.5)
      print ('GAME OVER')
      break

def GAME2(): << def of GAME 2
  
  
if jeu == 0 : << play the fisrt game
  GAME()

if jeu == 1 : << play the second game if you succeed the first one
  GAME2()
Reply
#2
jeu is not global, it's local to the GAME function.

While you could define jeu in the "global" namespace (i.e., outside GAME), the better solution would be for the GAME function to return True/False or 0/1 to indicate that it was completed successfully.

https://docs.python.org/3/tutorial/contr...-functions
Reply
#3
I think it is time to start using classes and string formatting. I suggest to start from here

import random
import time
import sys
print ('Bienvenue')

class Game:
    def __init__(self): 
        self.bonne = 0
        self.mauvaise = 0
        self.statut = None

    def run(self):
        while True :
            a = int(random.randint (0,10))
            b = int(random.randint (0,10))
            reponse = a+b
            print('{} + {} = ?'.format(a, b)) 
            joueur = input ('Quelle est la bonne réponse ?')
            time.sleep (0.5)            
            if int(joueur) == reponse :
                print ('Bravo')
                self.bonne += 1
                time.sleep(0.3)
                print ('Tu as {} bonnes réponses et {} mauvaises réponses'.format(self.bonne, self.mauvaise))             
            else :
                print ('VRAIMENT !!!')
                self.mauvaise += 1
                time.sleep(0.3)
                print ('Tu as {} bonnes réponses et {} mauvaises réponses'.format(self.bonne, self.mauvaise))             
                
            if self.bonne == 3 :
                print ('Tu as complété le jeu avec {} mauvaise réponse'.format(self.mauvaise))
                self.statut = "succès"
                break
            if self.mauvaise == 3 :
                print ('Trop de mauvaises réponses')
                time.sleep (0.5)
                self.statut = "échec"
                print ('GAME OVER')
                break
 
class Game2: # << def of GAME 2
   def __init__(self):
       pass
   def run(self):
       pass
   
jeu = Game()
jeu.run()
if jeu.statut != 'succès':
    sys.exit(0)
jeu = Game2()
jeu.run()
(french speaker here too!)
Please indent python code with 4 space characters! You can configure your editor to input 4 spaces when you hit the TAB key.
Reply
#4
Quote:I think it is time to start using classes
Why? What benefit is gained by using classes here instead of methods?
Reply
#5
(Jan-12-2018, 06:47 PM)mpd Wrote: Why? What benefit is gained by using classes here instead of methods?
There are two immediate benefits:

  1. Classes is the tool that generally avoids struggling with global variables management. Using instances creates a new space where names can be defined and shared between different functions.
  2. I guess @mquesnel's project is to add new features to his/her games and it's going to be much easier if one uses classes from the beginning.

If you look at the code, you notice that I achieve the OP's objective to play the second game if the first one succeeds, and I do this by using an instance member, and no global statement. You can do the same with a value returned, as you suggested, but it is less extensible.
Reply
#6
(Jan-12-2018, 07:13 PM)Gribouillis Wrote:
(Jan-12-2018, 06:47 PM)mpd Wrote: Why? What benefit is gained by using classes here instead of methods?
There are two immediate benefits:

  1. Classes is the tool that generally avoids struggling with global variables management. Using instances creates a new space where names can be defined and shared between different functions.
  2. I guess @mquesnel's project is to add new features to his/her games and it's going to be much easier if one uses classes from the beginning.

If you look at the code, you notice that I achieve the OP's objective to play the second game if the first one succeeds, and I do this by using an instance member, and no global statement. You can do the same with a value returned, as you suggested, but it is less extensible.

The OP doesn't have a "global variables management" problem. He/she is simply trying to get the success/fail status back to the caller. If the OP doesn't know about or understand return statements, are classes an appropriate topic to bring up?

Regarding extensibility... you can have simple, extensible examples without using classes. And if the OP is doing something simple with kids, it's probably better to not use classes at first anyway.
Reply
#7
(Jan-12-2018, 07:33 PM)mpd Wrote: If the OP doesn't know about or understand return statements, are classes an appropriate topic to bring up?
Well, I don't think classes are difficult to understand and to use. On the contrary, they help structure the code and keep it simple. They are not advanced components in a python program, on the contrary, they are the building blocks.

(Jan-12-2018, 07:33 PM)mpd Wrote: you can have simple, extensible examples without using classes.
It may be true, but this is for expert programmers, and there is little benefit in not using classes. I was very impressed in the past when I read pieces of C code written in the 70s just before everybody started OOP, and you see that the better C code at that time has exactly the same structure as OOP, that is to say a bunch of functions manipulating a structure. Classes appeared naturally as the component everybody needed.
Reply
#8
I vote for classes. See:
https://jeffknupp.com/blog/2014/06/18/im...ogramming/
Reply
#9
(Jan-12-2018, 08:31 PM)Gribouillis Wrote:
(Jan-12-2018, 07:33 PM)mpd Wrote: you can have simple, extensible examples without using classes.
It may be true, but this is for expert programmers, and there is little benefit in not using classes.

I think you've lost track of the OP's goals:
Quote:I'm a teacher and I just began learning Python so I can show some tips to my students.

I'm not suggesting the OP build an extensible game framework without using classes. I am suggesting that, when writing small programs to "show tips to students", you can -- and probably should -- do it without classes. After all, if the students have not seen a computer program before (the OP wasn't clear about that but I'm guessing this is the case), they're going to have to learn what a variable is, what s function is, what a loop is, etc.

Why add classes to that out of the gate when you don't have to?

Quote:Well, I don't think classes are difficult to understand and to use.
Neither do I but when I was a CS teaching assistant and tutor I encountered a lot of people for whom classes were very difficult to wrap their heads around.
Reply
#10
(Jan-12-2018, 10:59 PM)mpd Wrote: I am suggesting that, when writing small programs to "show tips to students", you can -- and probably should -- do it without classes.
We'll wait until the OP tell us more about his/her students. I understand that the OP wants to learn some python, then show some tips to the students. I'm addressing the 'learn some python' part of it, and this will be easier by using classes right away (I don't mean inheritance, which is for advanced class usage).
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  It's saying my global variable is a local variable Radical 5 1,098 Oct-02-2023, 12:57 AM
Last Post: deanhystad
  Delete all Excel named ranges (local and global scope) pfdjhfuys 2 1,691 Mar-24-2023, 01:32 PM
Last Post: pfdjhfuys
  Global variables or local accessible caslor 4 985 Jan-27-2023, 05:32 PM
Last Post: caslor
  How to use global value or local value sabuzaki 4 1,106 Jan-11-2023, 11:59 AM
Last Post: Gribouillis
  UnboundLocalError: local variable 'wmi' referenced before assignment ilknurg 2 1,859 Feb-10-2022, 07:36 PM
Last Post: deanhystad
  Global vs. Local Variables Davy_Jones_XIV 4 2,598 Jan-06-2021, 10:22 PM
Last Post: Davy_Jones_XIV
  Variable scope - "global x" didn't work... ptrivino 5 2,980 Dec-28-2020, 04:52 PM
Last Post: ptrivino
  Global - local variables Motorhomer14 11 4,130 Dec-17-2020, 06:40 PM
Last Post: Motorhomer14
  Spyder Quirk? global variable does not increment when function called in console rrace001 1 2,159 Sep-18-2020, 02:50 PM
Last Post: deanhystad
  from global space to local space Skaperen 4 2,269 Sep-08-2020, 04:59 PM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020