Mar-28-2017, 05:43 PM
So I understand little about classes and functions. I know how to create simple classes and functions but I still need much help and learning. I am trying to create a login file for a game that I will start working on as soon as my login modules are finished and working properly. This code is examples of what I've created and learned while making simple classes:
from random import randint class Die: def __init__(self, sides, roll=0): self.sides = sides self.roll = roll def roll_die(self): if self.sides==6: while self.roll < 6: print("You roll a six sided die: " + str(randint(1, 6))) self.roll += 1 elif self.sides==10: while self.roll < 6: print("You roll a ten sided die: " + str(randint(1, 10))) self.roll += 1 elif self.sides==20: while self.roll < 6: print("You roll a twenty sided die: " + str(randint(1, 20))) self.roll += 1 else: print("Mistakes have been made!") six_sided_die = Die(6) six_sided_die.roll_die() print('') ten_sided_die = Die(10) ten_sided_die.roll_die() print('') twty_sided_die = Die(20) twty_sided_die.roll_die()
class User(): def __init__(self, first_name, last_name, username): self.first_name = first_name self.last_name = last_name self.username = username def describe_user(self): print("\nThis is the information for " + self.username + ":\n-- Last name, First name --\n\t* " + self.last_name.title() + ", " + self.first_name.title()) def greet_user(self): print("\nHello, " + self.username + "!") user_1 = User('joshua', 'mitchum', 'Broodwar1998') user_2 = User('loki', 'thor', 'Godz') user_1.describe_user() user_1.greet_user() user_2.describe_user() user_2.greet_user()Ok so that's my knowledge as far as classes go... Now what I need help with is turning this next code into a class. I know how to make classes without taking in user input. I do not know how to implement user input into classes. For example this code:
prompt_message = "Enter the username you wish to create. \nType \'quit\' if you wish to exit: " prompt_username = "" while prompt_username.lower() != 'quit': prompt_username = input(prompt_message) if prompt_username.lower() == 'quit': break else: print("Welcome to a whole new world, " + prompt_username) breakI understand I need to create a list of usernames input and save it to a txt file or json file as a dictionary so i can recall it everytime a username is created in order to check if the username is available and passwords match also length restrictions and password hashing... But for now I just need to understand how to turn this into a simple class if that's possible? To make this more efficient code I guess?