Python Forum
Output prints Account.id at the end?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Output prints Account.id at the end?
#1
First off, I appreciate anyone who takes a look at this code. I did my best to read the rules here on the forums and I am trying my best to follow them. I am a new user here so please pardon me if I make a mistake and please don't hesitate to let me know how I can improve as a forum member. I would hope to become a contributing member here on the forums myself now that I am pretty familiar with the python language and I would also like to really start rounding out my overall knowledge.

Secondly, this is just a junk script that I have coded to improve my overall OOP abilities for RPG programming. I know there are privative methods here and probably things I am doing completely wrong and that is okay, don't worry about that. Any pointers to proper documentation I should be reading is always appreciated as there is so much vast information to absorb it is always nice to have suggestions and go back to the references I may have missed or forgotten. The main objective here is to help me understand what I am missing on the current level I am at. I assumed I knew enough of this language to read every line and find this out, I have done some searching and I cant quite find a post that matches. Maybe I just need a fresh pair of eyes on here and it's super obvious, we will see. I only managed to discover what the output was referenced to and not where or why it is being printed in my output.
_________________________

The Question: Why does the Account.id get printed/returned to the very end of my console output after player is created and login is successful?

Output:
[Account Creation Menu] Username: Guest Password: 123 [Account Information & Details] User ID: 1 Username: Guest Password: (Hidden) VIP Rank: None [Updating Table Entry] {'ID': 1, 'Username': 'Guest', 'Password': '***', 'Rank': None} --Table Entry Updated Successfully!-- [.:: Please Login ::.] Username: Guest Password: 123 --[Logging Into System]-- Login Successful... 1
import time
import random
import json
cache = None

class Account:
    
    Accounts = {'ID': None,
                'Username': None,
                'Password': None,
                'Rank': None}
    
    i = 0
    def __init__(self,
                 id,
                 username,
                 password,
                 rank):
        
        self.id = id
        self.username = username
        self.password = password
        self.rank = rank
        self.__str__()

    def __str__(self):
        return ('\n\n[Account Information & Details]\n\nUser  ID:  {}\nUsername:  {}\nPassword: (Hidden)\nVIP Rank:  {}'.format(self.id,
                                                                                                                                self.username,
                                                                                                                                self.rank))

    def create_new(self, amt):
        while Account.i < amt:
            global cache
            Account.i += 1
            print('\n[Account Creation Menu]\n')
            account = Account(Account.i,
                              input('\nUsername: '),
                              input('Password: '),
                              None)
            
            cache = [account.id,
                     account.username,
                     account.password,
                     account.rank]
            
            Account.Accounts.update({'ID': account.id,
                                     'Username': account.username,
                                     'Password': '*'*len(account.password),
                                     'Rank': account.rank})
            
            print(account,'\n\n[Updating Table Entry]\n',Account.Accounts)
            self.write_file()
            print('--Table Entry Updated Successfully!--')
            print('\n\n[.:: Please Login ::.]\n')
            account.login(input('Username: '),
                          input('Password: '))

    def login(self,
              username,
              password):
        
        global cache
        print('\n--[Logging Into System]--\n')
        time.sleep(2)
        if username == cache[1] and password == cache[2]:
            print('Login Successful...')
            del cache[2]
            
        else:
            print('\nInvalid Login, please try again!\n')
            self.login(input('Username: '),
                       input('Password: '))
    def write_file():
        with open('Accounts_Table.txt', 'a') as file: #change 'w' to 'a' to solve the file overwriting issue.
                 file.write('\r'+json.dumps(Account.Accounts))

class Player():

    def __init__(self, name):
        self.name = name
        self.inventory = [Currency('Gold', 1)]
        self.hp = int(random.randrange(250, 500))

    def __str__(self):
        print('\nPlayer Name: {}\nHealth: {}\n'.format(self.name, self.hp, self.print_inventory))

    def print_inventory(self):
        print(self)
        print('Here is a list of your items:\n')
        for item in self.inventory:
            print(item,'\n')

          
class Item():

    currency = ['Gold']

    def __init__(self,
                 name,
                 description,
                 value):
        
        print(cache[0])
        self.name = name
        self.description = description
        self.value = value
        
    def __str__(self):
        return('Name: {}\nDescription: {}\nValue: {}\n'.format(self.name,
                                                               self.description,
                                                               self.value))

class Container(Item):

    def __init__(self,
                 name,
                 description,
                 value,
                 contents,
                 slots_left,
                 max_slots):
        
        self.contents = contents
        self.slots_left = slots_left
        self.max_slots = max_slots
        super().__init__(name, description, value)

    def __str__(self):
        return('Name: {}\nDescription: {}\nValue: {}\n\n[Contents: {}]\nAvailable Slots: {}/{}'.format(self.name,
                                                                                                       self.description,
                                                                                                       self.value,
                                                                                                       self.contents,
                                                                                                       self.slots_left,
                                                                                                       self.max_slots))

class Currency(Item):
    
    def __init__(self, ctype, val):
        self.ctype = ctype
        self.val = val
        if ctype.capitalize() in Item.currency:
            if ctype.capitalize() == Item.currency[0]:
                super().__init__(name = ctype.capitalize(),
                                 description = 'A shiny gold coin. It appears to be expensive',
                                 value = val)

        elif ctype not in Item.currency:
            print('|Invalid| - Item \'{}\' is not a valid currency item!'.format(ctype))
            
        else:
            print('|Unhandled Exception| Critical Error - Contact Developer!')

    def __str__(self):
        return('Currency Type: {}\nDescription: {}\nValue: {}'.format(self.ctype,
                                                                      self.description,
                                                                      self.val))

while __name__ == '__main__':
    Account.create_new(Account, 1)
    player = Player(cache[1])
    break
Thank you again to anyone who offers some advice or any help. I wish you a very Merry Christmas and happy holidays throughout this upcoming New Year!
Reply
#2
When I run your code locally, I don't get anything after the "Login Successful..." output. I wonder if you have something else in your environment that is generating it.
Reply
#3
(Dec-14-2020, 04:15 AM)bowlofred Wrote: When I run your code locally, I don't get anything after the "Login Successful..." output. I wonder if you have something else in your environment that is generating it.

Weird, I wonder what it is then. For a moment I thought I was crazy that I couldn't find out why.. However, as always computers never cease to amaze me. Basically I am just using the standard Python Interpreter v3.9.0 Shell to run my code example. I will try to run it in CMD and a 3rd party compiler to see if I get a different result. If anyone knows why the interpreted would do such a thing? I haven't missed any code I am sure of it, maybe there are some settings I am not aware of that effect this.

Thank you for your reply Bowlofred, it's greatly appreciated!

UPDATE: Just ran the code on 2 separate compilers. 1 On my pc, one 3rd party web-based so there would be nothing on the web-based environment to cause this. I am absolutely stumped on where this reference is being called and printed from.
Reply
#4
print(cache[0]) in item is printing the "1".
LastStopDEVS likes this post
Reply
#5
(Dec-14-2020, 05:28 AM)deanhystad Wrote: print(cache[0]) in item is printing the "1".

Awesome, what a beast. I knew it just needed a fresh pair of eyes. Thanks good sir, I hope to return the favor one day. I will also provide some +Rep if possible. Not sure if my account rank is allowed to or if that is a feature.

I need to pay more attention to my __init__ methods.
Reply
#6
not related to your question and you said "I know, don't worry about it", but there is so much of really weird/plainly wrong stuff going on in your code that I had to mention it.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  python prints none in function output chairmanme0wme0w 3 190 Jul-07-2021, 05:18 PM
Last Post: deanhystad
  Try/Exept prints only ones tester_V 11 844 Nov-03-2020, 02:38 AM
Last Post: tester_V
  Different results of code with local account and technical account dreyz64 7 1,147 Mar-05-2020, 11:50 AM
Last Post: dreyz64
  Visual Studio Code does not print desired output but only prints "..." vincentolivers 11 3,431 Sep-09-2019, 12:58 PM
Last Post: vincentolivers
  What for a file that prints nothing sylas 1 1,014 Sep-12-2018, 01:18 PM
Last Post: gruntfutuk

Forum Jump:

User Panel Messages

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