[Python] How to get the return from a user's input in one python script file in another...

Discussão em 'Python' iniciado por Stack, Abril 16, 2025.

  1. Stack

    Stack Membro Participativo

    I am coding a battleships game and storing the data on google sheets (next module we learn about SQL databases). The data includes: Usernames, encrypted passwords (using bcrypt), saved game states, and leaderbaords

    In my user.py file I have some of the below code

    def login_credentials(username, password):
    """
    Verifying users login details with the google sheets database
    """
    users = user_logins_worksheet.get_all_records()
    for user in users:
    if user["Username"] == username:
    encrypt_pw = user["Password"].encode()
    if bcrypt.checkpw(password.encode(), encrypt_pw):
    return "Login successful"
    print("Invalid login credentials, please enter correct details.")
    user_choice()
    return "Invalid login credentials"


    def user_login():
    """
    Allows user to login and access a previous game state
    or start a new game from scratch or access the leaderbaord.
    """
    username = str(input("Username: "))
    password = str(input("Password: "))
    result = login_credentials(username, password)
    if result == "Login successful":
    print(f"Welcome back {username}! Time to play the game.")
    return username
    else:
    return None


    I then want to access the username from the return within user_login() in battleships.py file, so at various points it calls the player by name when I use an f string. For example see below in my update_game_status() I have two f strings with {user} in them. I want the user's username to be shown here.

    def update_game_status(
    self, user, computer, user_ships_hits, computer_ships_hits
    ):
    """
    Updates the game board after shots are taken
    """
    time.sleep(1.5)
    print("-" * 35)
    print("""Key:
    S = Ship
    H = Hit
    M = Miss
    """)
    print("-" * 35)
    print(f"{user} board:")
    computer.display_board(show_ships=True)
    print("-" * 35)
    print("Computer's board:")
    user.display_board(show_ships=False)
    print("-" * 35)
    time.sleep(1)
    print("-" * 35)
    print(f"{user} hits: {computer_ships_hits}/{computer.num_ships}")
    print(f"Computer hits: {user_ships_hits}/{user.num_ships}")
    print("-" * 35)
    time.sleep(1.5)


    But everytime I try to put user_login() into the battleships.py file it calls for the user to login again. Any help in how to do this?

    Happy to share the github repo if that would be easier.

    I have tried to create a function called fetch_username() wihtin the same class that needs the username retrieved in battleships.py. But stuck on how to compare the list of usernames within the database to the user's input from usre.py.

    class Game:
    """
    Class that runs the game, allowing user to place ships, randomly generates
    a computers board and then asks user to guess while randomly generating
    computers guesses and checks for hits and misses.
    """
    def __init__(self, ships_placed=0, ships_hit=0):
    self.ships_placed = ships_placed
    self.ships_hit = ships_hit
    self.username = None

    def fetch_username(self, username):
    """
    Fetches username from user login
    """
    usernames = user_logins_worksheet.col_values(1)
    if username in usernames:
    self.username = username
    return self.username
    else:
    return "User not found"

    Continue reading...

Compartilhe esta Página