[Tutor] Trying to select an input from another Python file & output that input in the main game program

Peter Otten __peter__ at web.de
Fri Jun 18 02:36:59 EDT 2021


On 17/06/2021 23:16, David Rock wrote:
> * D Rochester <rh at saintbedes.net> [2021-06-17 12:50]:
>> Good afternoon,
>>
>> The first file (Noels_Music_Game) is for authenticating the users and it
>> looks at a csv file called 'users'. I have added another player to this
>> file so that it now spans 4 columns with the 1st & 3rd entries being the
>> users and the 2nd & 4th entries being the passwords. This element of the
>> code works fine and gives access to the game using a simple IF statement
>> detailed below;
> 
> Just a quick observation/question first:
> 
> Why do you have the users.csv set up this way?  It would simplify your code a
> lot if you had only two columns: user and password
> 
> The list of users is begging to be a list of rows, one pair of information for
> each user, rather than trying to add horizontally.  What happens when you need
> to add a third user; a fourth?  It's not maintainable.
> 
> There's also a logic problem with doing it horizontally: the wrong password can
> match against the wrong user.  In other words, if you enter user2's name and
> user1's password, you will still authenticate.  I doubt that's your intention.
> 
> Try using the csv module and use the userids as keys to search against to
> compare the entered password.  That might help with the rest of the work.

David's comment is spot-on. If you are ambitious read the csv into a 
dict with usernames as keys and paswords as values. Then you can check a 
username/password pair with

lookup = {"jim": "secret", "jane": "wont-tell"}  # example, actual dict
                                                  # should be created at
                                                  # runtime
...
valid = lookup.get(username) == password

As to the problem you describe I recommend that you move the code in 
your first module into a function, let's call it 
get_authenticated_user(), with the following structure (pseudocode):

def get_authenticated_user():
     read csv
     while True:
         username = input("user name: ")
         password = input("password: ")
         check password/username pair
         if password is correct:
             return username
         print("wrong user or password")

Then change menu() to take a username argument

def menu(username):
     ...  # now you know the current user

and call it

menu(get_authenticated_user())

This approach can be generalized: avoid global variables, always try to 
pass state between functions explicitly as arguments.



More information about the Tutor mailing list