pins = {"Mike":1234, "Joe":1111, "Jack":2222}
pin = int(input("Enter your pin: "))
if pin in pins.values():
nameinp = pins.get(pin)
print("Hello Mr." + nameinp)
fruit = input("Enter fruit: ")
print(find_in_file(fruit))
else:
print("Incorrect pin!")
print("This info can be accessed only by: ")
for key in pins.keys():
print(key)
input()
So the idea is to make greeting screen for the particular person who inserted his own pin code, tried to research didn't find the answer, hope you will help!
Answers to all of you
There is no error, there is a question:
how to make that when you put in password that is equal some value, and later when the system recognizes your password prints("Greetings" + value)
You have the order of the dictionary key-value pairs interchanged. So instead of
pins = {"Mike":1234, "Joe":1111, "Jack":2222}
you should do
user_from_pin = {1234:"Mike", 1111:"Joe", 2222:"Jack"}
I took the liberty to change the variable name to be more descriptive what it actually does: Given a pin it returns the username. For example: user_from_pin[1111] == "Joe". The rest of the script should be adapted a little bit to work with this definition:
user_from_pin = {1234:"Mike", 1111:"Joe", 2222:"Jack"}
pin = int(input("Enter your pin: "))
user = user_from_pin.get(pin)
if user:
print("Hello Mr." + user)
fruit = input("Enter fruit: ")
print(find_in_file(fruit))
else:
print("Incorrect pin!")
print("This info can be accessed only by: ")
for value in pins.values():
print(values)
input()
Related
I want to iterate over every instance i stored as a value to a number stored as a key in a dictionary. Where if I were to make an account named jason, it would be assigned 1, then if I were to make a new one, it would be assigned 2. That part is already done but the iteration part is very confusing for me. Why does it only go through the first key value pair in the dictionary?
Ps: I am new to oop this is my first oop thing where i did not follow any guides so that id would actually learn. Thank you <3
class Bank:
serialnum = 0
username = ""
email = ""
password = ""
bal = 0
def __init__(self,count):
self.serialnum = count
self.username = input("What's your username? \n")
self.email = input("What's your email? \n")
self.password = input("What's your password \n")
self.bal = input("How much balance do you have \n")
def withdraw(money):
self.bal= bal-money
print (bal)
global count
count = 0 #counts and is the serial num
accounts = {} #accounts dictionary
def accountcreate(): #gets called when account does not exist
global count
while True:
serial = int(count)
account = Bank(count)
print("The serial is {}".format(count))
count += 1
accounts[serial] = account
print("Your account has been created, please use the username registered. ")
break
accountaccess()
def accountverify(name):#if accountverify returns false, prompts the accountcreate function
username = ""
start = 0
balance = 0
if 0 in accounts: #essentially means if the first account has been made
for key in accounts: #loops through accounts in accounts dictionary
#sets the keys gotten and sets the un to the username attribute of every key
if hasattr((accounts[key]),"username") == name:
print("logged in as ", name, "Password is \n",
(getattr((accounts[key]), "password")),
"Account balance is ", getattr((accounts[key]), "bal"))
action = input("What do you want to do? \n -Withdraw \n -Deposit \n -Transfer \n -Make another account \n")
if "make" in action:
print("Making another account... \n Please enter your credentials")
makeaccount = accountcreate()
else: #if username does not exist
print("First item in list is ",(getattr((accounts[key]),"username")))
print(accounts)
accountask = input("Account does not exist, make a new account? Yes or No \n").lower()
if accountask == "yes":
makeAccount = accountcreate()
else: #makes first account
ask1 = (input("Account does not exist, would you like to make an account? Yes or No \n")).lower()
if ask1 == "yes":
makeAccount = accountcreate()
def accountaccess(): #accesses account
ask = (input("Do you want to access an account? Yes, or no. "))
if ask == "yes":
getname = (input("What is your username? ")).lower()
ver = accountverify(getname)
loop = False
loop = True
while loop == True: #mainloop
ask = (input("Do you want to access an account? Yes, or no. \n")).lower()
if ask == "yes":
getname = (input("What is your username? ")).lower()
ver = accountverify(getname)
loop = False
The replit link
It would also be helpful to know how to store the username as the name of the value since what is shown there is incredibly cryptic
In this image, every new username registered is a new instance of the Bank class. But the for loop only goes on the first one
The part of your code that is causing the issue is
if hasattr((accounts[key]),"username") == name:
print("logged in as ", name, "Password is \n",
(getattr((accounts[key]), "password")),
"Account balance is ", getattr((accounts[key]), "bal"))
The return from hasattr is a boolean and cannot be compared to name.
Try changing it too
if hasattr(accounts[key],"username"):
if accounts[key].username == name:
....
Also your use of getattr() is incorrect and unnecessary since you can simply access those attributes directly.
For example:
account = accounts[key]
print(account.username)
print(account.password)
print(account.bal)
with all of that in mind your accountsverify function should look more like this:
def accountverify(name):
start = 0
balance = 0
if 0 in accounts:
for key in accounts:
account = accounts[key]
if account.username == name:
print(f"logged in as {name} Password is \n {account.password} \n Account balance is {account.bal}")
action = input("What do you want to do? \n -Withdraw \n -Deposit \n -Transfer \n -Make another account \n")
if "make" in action:
print("Making another account... \n Please enter your credentials")
makeaccount = accountcreate()
else: #if username does not exist
print("First item in list is ",account.username)
print(accounts)
accountask = input("Account does not exist, make a new account? Yes or No \n").lower()
if accountask == "yes":
makeAccount = accountcreate()
As far as making the Bank class print the accounts name you just need to overwrite the __str__ method.
class Bank:
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
I am trying to create registration and login and forgot password functions.
this is my code
def regi():
global new, unname, answer, passcode
print('**New Registration**'.capitalize().center(100))
uname = input("Enter User Name: ")
passcode = input("Enter Password: ")
questn()
new = [name, uname, passcode, security]
print(f'Your Business {bname} has created.\nWelcome to Business World')
newbusiness()
def login():
chances = 5
global old
userid = input('Enter User Id: ')
password = input('Enter Password: ')
try:
if userid and password in new:
pass
else:
print('Wrong Credentials')
chances -= 1
login()
except NameError:
print('No Username found. Please register.')
time.sleep(2)
print('Redirecting to registration block.')
time.sleep(2)
regi()
def questn():
global security
questions = {
1: 'What is your favourite color?',
2: 'What is your mother tongue?',
3: 'What is your favourite place of weekend?'
}
for k, v in questions.items(): print(f'{k}: {v}')
qselct = input("Please select one security question: ")
answr = input('Enter your answer: ')
security = [qselct, answr]
def forgotpass():
questions = {
1: 'What is your favourite color?',
2: 'What is your mother tongue?',
3: 'What is your favourite place of weekend?'
}
for k, v in questions.items(): print(f'{k}: {v}')
comparequet = input("Select Security Quesion: ")
compareans = input("Enter your answer (Case Sensitive): ")
if comparequet and compareans in security:
passcode = input('Enter new password: ') # i stuck here
when i try to reassign 'Passcode' using input(), in pycharm its giving this
Shadows name 'passcode' from outer scope
so how can i update passcode in regi(), here in forgotpass().
Note: helpful if you suggest any improvements in above code. I am using learned subject in the above code. learned TRY used there.
I think you just have to bring in a
global passcode
before using this variable.
so, I'm getting a NameError on npc.name(and I imagine it will arise in all subsequent class method-linked variables I'm trying to redefine), also, I have an IndexError arising earlier.
I'll explain in more detail,but first, my code.
This is my full code, beware:
# import pickle
import pickle
npcs_pickle_file = 'NPCatt.pk'
npc_count = 200
class NPC:
def __init__(self, name="", occupation="", weakness="", need="", desire="", enemy="",
rumor="", secret="", passion="", redeeming_quality="",damning_quality="", happy="",
occ_desire="", occ_complication="", pc_opinion="", accomplishment="", magical_gear="",
political_influence="", resource="", intel="", research=""):
# Attributes
self.name = name
self.occupation = occupation
self.weakness = weakness
self.need = need
self.desire = desire
self.enemy = enemy
self.rumor = rumor
self.secret = secret
self.passion = passion
self.redeeming_quality = redeeming_quality
self.damning_quality=damning_quality
self.happy = happy
self.occ_desire = occ_desire
self.occ_complication = occ_complication
self.pc_opinion = pc_opinion
self.accomplishment = accomplishment
self.magical_gear = magical_gear
self.political_influence = political_influence
self.resource = resource
self.intel = intel
self.research = research
def __str__(self):
npc_output = "####NPC SUMMARY####\n"
for att, val in self.__dict__.items():
if val:
npc_output += (f"{att} = {val}\n")
return npc_output
# open a pickle file
# load your data back to memory when you need it
try:
with open(npcs_pickle_file, 'rb') as fi:
npcs = pickle.load(fi)
except FileNotFoundError as fne:
#file doesnt exist prob first time running so create a dict with the 170 npc id's
npcs = {id: None for id in range(npc_count)}
#select an NPC to modify / create
npc_id = None
while not npc_id:
try:
npc_id = int(input(f"Enter the id number of the NPC you wish to modify: "))
except ValueError as ve:
print("You must provide a numerical id")
if npc_id < 0 or npc_id >= npc_count:
npc_id = None
print(f"you must provide a value between 0 and {npc_count}")
if npcs[npc_id]:
npc = npcs[npc_id]
print(npc)
modify = input("This NPC already exists, do you want to continue and change them? (y/n): ")
if modify.lower() == "y":
name = input("Enter name of NPC: ")
occupation = input("Enter NPC occupation: ")
weakness= input("Enter Weakness: ")
need= input("Enter Need: ")
desire= input("Enter Desire: ")
enemy= input("Enter Enemy: ")
rumor= input("Enter Rumor: ")
secret= input("Enter Secret: ")
passion= input("Enter Passion: ")
redeeming_quality=input("Enter Redeeming Quality: ")
damning_quality=input("Enter Damning Quality: ")
happy= input("Enter, is this NPC happy?: ")
occ_desire= input("Enter an Occupational Desire: ")
occ_complication= input("Enter an Occupational Complication: ")
pc_opinion= input("Enter this NPC's disposition toward the PCs: ")
accomplishment= input("Enter an Accomplishment: ")
magical_gear= input("Enter Magical Gear: ")
political_influence=input("Enter Political Influence: ")
resource= input("Enter Resource Level: ")
intel= input("Enter Intel Tier: ")
research= input("Enter Research: ")
npc.name = name
npc.occupation = occupation
npc.weakness = weakness
npc.need = need
npc.desire= desire
npc.enemy= enemy
npc.rumor= rumor
npc.secret= secret
npc.passion= passion
npc.redeeming_quality= redeeming_quality
npc.damning_quality= damning_quality
npc.happy= happy
npc.occ_desire=occ_desire
npc.occ_complication=occ_complication
npc.pc_opinion=pc_opinion
npc.accomplishment=accomplishment
npc.magical_gear=magical_gear
npc.political_influence=political_influence
npc.resource=resource
npc.intel=intel
npc.research=research
else:
npcs[npc_id] = NPC(name=npc.name, occupation=npc.occupation,weakness=npc.weakness,need=npc.need,desire=npc.desire,\
enemy=npc.enemy,rumor=npc.rumor,secret=npc.secret,passion=npc.passion,redeeming_quality=npc.redeeming_quality,\
damning_quality=npc.damning_quality,happy=npc.happy,occ_desire=npc.occ_desire,\
occ_complication=npc.occ_complication\
,pc_opinion=npc.pc_opinion,accomplishment=npc.accomplishment,\
magical_gear=npc.magical_gear,political_influence=npc.political_influence,resource=npc.resource,\
intel=npc.intel,research=npc.research)
else:
name = input("Enter name of NPC: ")
occupation = input("Enter NPC occupation: ")
weakness= input("Enter Weakness: ")
need= input("Enter Need: ")
desire= input("Enter Desire: ")
enemy= input("Enter Enemy: ")
rumor= input("Enter Rumor: ")
secret= input("Enter Secret: ")
passion= input("Enter Passion: ")
redeeming_quality=input("Enter Redeeming Quality: ")
damning_quality=input("Enter Damning Quality: ")
happy= input("Enter, is this NPC happy?: ")
occ_desire= input("Enter an Occupational Desire: ")
occ_complication= input("Enter an Occupational Complication: ")
pc_opinion= input("Enter this NPC's disposition toward the PCs: ")
accomplishment= input("Enter an Accomplishment: ")
magical_gear= input("Enter Magical Gear: ")
political_influence=input("Enter Political Influence: ")
resource= input("Enter Resource Level: ")
intel= input("Enter Intel Tier: ")
research= input("Enter Research: ")
npc.name = name
npc.occupation = occupation
npc.weakness = weakness
npc.need = need
npc.desire= desire
npc.enemy= enemy
npc.rumor= rumor
npc.secret= secret
npc.passion= passion
npc.redeeming_quality= redeeming_quality
npc.damning_quality= damning_quality
npc.happy= happy
npc.occ_desire=occ_desire
npc.occ_complication=occ_complication
npc.pc_opinion=pc_opinion
npc.accomplishment=accomplishment
npc.magical_gear=magical_gear
npc.political_influence=political_influence
npc.resource=resource
npc.intel=intel
npc.research=research
with open(npcs_pickle_file, 'wb') as fi:
# dump your data into the file
pickle.dump(npcs, fi)
I'm a noob so the code structure was provided as an answer on my only other question so far on the site. I've expanded it for my purposes.
The thing is, the NPC indexed as [1], has been stored perfectly, shows up as needed, and is modifiable.
But when defining new NPCs, I get first an IndexError for new Indexable NPCs, which I caught with a
try: #the code for when the NPC has been previously defined
except IndexError:#the code on the last else block, for new indexes
in order to check whether the rest of the code worked,
and a NameError arises on the last else block where I define each attribute as
self.att=att
now, my best guess is that it has to do with local vs global variable definitions, but I have no idea how to solve either error.
Thank you if you read all the way through, and I'm sorry.
Please help, if you can and want to.
Your IndexError issue comes from unpickling a file created by the previous version of your script. If this file contains valuable data, just rename it for the moment, and once you'll get you script working and stable enough, it will be time to write a migration script to get your old data back. Else, well, just ditch it xD
wrt/ the NameError, it's in the last else block: you are trying to set attributes on a npc variable that is indeed not defined at this point - it's only defined in the if block:
if npcs[npc_id]:
npc = npcs[npc_id]
# way too much code here
else:
# repeated code here
# and here's the issue:
npc.something = something
You already noticed that "mashing together pieces of code without understanding them doesn't always work", which is a good start (at least you're aware of it, so there's still hope xD), now here's another enlightenment for you: "trying to understand messy code is hard". That's why good code structure is important. Also, short functions that only (or mostly) depend on their arguments are easier to understand (and test !) than long scripts with lots of conditionals and code blocks that depends on some variable being (or not) defined some 20+ lines away.
I usually don't do this, but it seems that in this case, you may benefit from seeing what a decently structured code looks like. It's far from perfect and could benefit from some improvements (like, when editing an existing npc, letting the user specify which attributes he wants to change instead of asking them to retype everything) but well, that's your job, not mine ;-)
import pickle
# coding conventions: pseudo-constants should be ALL_UPPER
NPCS_PICKLE_FILE = 'NPCatt.pk'
NPC_COUNT = 200
# coding convention: class names should be CamelCase
class Npc:
def __init__(self, name="", occupation="", weakness="", need="", desire="", enemy="",
rumor="", secret="", passion="", redeeming_quality="",damning_quality="", happy="",
occ_desire="", occ_complication="", pc_opinion="", accomplishment="", magical_gear="",
political_influence="", resource="", intel="", research=""):
# Attributes
self.name = name
self.occupation = occupation
self.weakness = weakness
self.need = need
self.desire = desire
self.enemy = enemy
self.rumor = rumor
self.secret = secret
self.passion = passion
self.redeeming_quality = redeeming_quality
self.damning_quality = damning_quality
self.happy = happy
self.occ_desire = occ_desire
self.occ_complication = occ_complication
self.pc_opinion = pc_opinion
self.accomplishment = accomplishment
self.magical_gear = magical_gear
self.political_influence = political_influence
self.resource = resource
self.intel = intel
self.research = research
def update(self, **values):
for key, val in values.items():
# make sure we're only accepted known attributes
if not hasattr(self, key):
raise AttributeError("Npc object has no attribute '{}'".format(key))
setattr(self, key, val)
def __str__(self):
# in Python, string concatenation is better done by
# building a list and joining it afterward
npc_output = ["####NPC SUMMARY####"]
for att, val in self.__dict__.items():
if val:
npc_output.append(f"{att} = {val}")
npc_output.append("") # so we have a last newline
return "\n".join(npc_output)
class InvalidDataFile(ValueError):
pass
def load_npcs_from_file():
with open(NPCS_PICKLE_FILE, 'rb') as fi:
try:
npcs = pickle.load(fi)
except EOFError as e:
raise InvalidDataFile(
"looks like {} is empy - expected a dict, got {}".format(NPCS_PICKLE_FILE, e)
)
# make sure we don't have incorrect data from
# the previous version where what was pickled was a list
if not isinstance(npcs, dict):
raise InvalidDataFile(
"looks like {} is obsolete or corrupted - expected a dict, got {}".format(NPCS_PICKLE_FILE, ncps)
)
# make sure we ALWAYS have `NPC_COUNT` npcs whatever
# (ie: in case the pickle didn't have as many entries as expected)
missing = NPC_COUNT - len(npcs)
if missing > 0:
for id in range(NPC_COUNT):
ncps.setdefault(id, None)
return npcs
def init_npcs():
return {id: None for id in range(NPC_COUNT)}
def load_npcs():
try:
return load_npcs_from_file()
except (FileNotFoundError, InvalidDataFile) as e:
# so you know what's happening...
print("got {} when trying to load npcs from file - creating a new dataset".format(e))
return init_npcs()
def save_npcs(npcs):
with open(NPCS_PICKLE_FILE, 'wb') as fi:
# dump your data into the file
pickle.dump(npcs, fi)
def get_npc_values():
# factor out common stuff
# XXX you definitly want to validate user inputs
values = {}
values["name"] = input("Enter name of NPC: ")
values["occupation"] = input("Enter NPC occupation: ")
values["weakness"] = input("Enter Weakness: ")
values["need"] = input("Enter Need: ")
values["desire"] = input("Enter Desire: ")
values["enemy"] = input("Enter Enemy: ")
values["rumor"] = input("Enter Rumor: ")
values["secret"] = input("Enter Secret: ")
values["passion"] = input("Enter Passion: ")
values["redeeming_quality"] = input("Enter Redeeming Quality: ")
values["damning_quality"] = input("Enter Damning Quality: ")
values["happy"] = input("Enter, is this NPC happy?: ")
values["occ_desire"] = input("Enter an Occupational Desire: ")
values["occ_complication"] = input("Enter an Occupational Complication: ")
values["pc_opinion"] = input("Enter this NPC's disposition toward the PCs: ")
values["accomplishment"] = input("Enter an Accomplishment: ")
values["magical_gear"] = input("Enter Magical Gear: ")
values["political_influence"] = input("Enter Political Influence: ")
values["resource"] = input("Enter Resource Level: ")
values["intel"] = input("Enter Intel Tier: ")
values["research"] = input("Enter Research: ")
return values
def update_npc(npc):
new_values = get_npc_values()
npc.update(**new_values)
def create_npc():
values = get_npc_values()
return Npc(**values)
def get_npc_id():
#select an NPC to modify / create
npc_id = None
while npc_id is None:
try:
npc_id = int(input(f"Enter the id number of the NPC you wish to modify: "))
except ValueError as ve:
print("You must provide a numerical id")
if npc_id < 0 or npc_id >= NPC_COUNT:
npc_id = None
print(f"you must provide a value between 0 and {NPC_COUNT}")
return npc_id
def edit_npc(npcs):
npc_id = get_npc_id()
# this should be safe now... theoretically at least
npc = npcs[npc_id]
if npc is None:
ok = input("This NPC doesn't exist yet, do you want to create it (y/n): ")
if ok.strip().lower() == 'y':
npcs[npc_id] = create_npc()
# let the caller know something was changed
return True
else:
ok = input("This NPC already exists, do you want to continue and change them? (y/n): ")
if ok.strip().lower() == "y":
update_npc(npc)
# let the caller know something was changed
return True
# let the caller know nothing was changed
return False
def show_npcs(npcs):
for id, npc in npcs.items():
print("{} : {}".format(id, npc))
print("") # add a blank line
def get_next_action():
while True:
print("what do you want to do ?")
print("S - show existing npcs")
print("E - edit a npc")
print("Q - quit")
action = input(">> ").strip().upper()
if action not in "SEQ":
print("sorry, I don't undertand '{}'".format(action))
return action
def main():
npcs = load_npcs()
while True:
nb_valids = len([_ for _ in npcs.values() if _])
print("we have {} valid npcs".format(nb_valids))
action = get_next_action()
if action == "Q":
break
elif action == "E":
if edit_npc(npcs):
print("saving data")
save_npcs(npcs)
elif action == "S":
show_npcs(npcs)
if __name__ == "__main__":
main()
I am trying to create a registrar system through Python with pickles. I have gotten the system to record user input, but it does not save it for future implementations of the program.
Here is the code that will start the program:
import datetime
import pandas as pd
import pickle as pck
import pathlib
from pathlib import *
from registrar import *
prompt = "Please select an option: \n 1 Create a new course \n 2 Schedule a new course offering \n 3 List this school's course catalogue \n 4 List this school's course schedule \n 5 Hire an instructor \n 6 Assign an instructor to a course \n 7 Enroll a student \n 8 Register a student for a course \n 9 List this school's enrolled students \n 10 List the students that are registered for a course \n 11 Submit a student's grade \n 12 Get student records \n 13 Exit"
farewell = "Thank you for using the Universal University Registrar System. Goodbye!"
print ("Welcome to the Universal University Registration System.")
print ("\n")
try: #As long as CTRL-C has not been pressed, or 13 not been input by user.
input_invalid = True
while input_invalid:
inst = input("Please enter the name of your institution. ").strip()
domain = input("Please enter the domain. ").strip().lower()
if inst == "" or domain == "":
print("Your entry is invalid. Try again.")
else:
input_invalid = False
schoolie = Institution(inst, domain)
if Path(inst + '.pkl').exists() == False:
with open(inst + '.pkl', 'r+b') as iptschool:
schoolie = pck.load(iptschool)
while True:
print (prompt)
user_input = input("Please enter your choice: ")
try:
user_input = int(user_input)
if user_input < 1 or user_input > 14: #UserInput 14: on prompt.
raise ValueError("Please enter a number between 1 and 13, as indicated in the menu.")
except ValueError:
print("Not a valid number. Please try again.")
if user_input == 1: #Create a new course
input_invalid2 = True #Ensure that the user actually provides the input.
while input_invalid2:
input_name = input("Please enter a course name: ").strip()
input_department = input("Please enter the course's department: ").strip()
input_number = input("Please enter the course's number (just the number, not the departmental prefix): ").strip()
try:
input_number = int(input_number)
except ValueError:
print ("Please print an integer. Try again.")
input_credits = input("Please enter the number of credits awarded for passing this course. Please use an integer: ").strip()
try:
input_credits = int(input_credits)
except ValueError:
print ("Please print an integer. Try again.")
if input_name != "" and input_department != "" and input_number and input_credits:
input_invalid2 = False #Valid input
else:
print("One or more of your entries is invalid. Try again.")
added_course = Course(input_name, input_department, input_number, input_credits)
for course in schoolie.course_catalog:
if course.department == input_department and course.number == input_number and course.name == input_name:
print("That course is already in the system. Try again.")
input_invalid2 == True
if input_invalid2 == False:
schoolie.add_course(added_course)
print ("You have added course %s %s: %s, worth %d credits."%(input_department,input_number,input_name, input_credits))
And here is the second option, which SHOULD reveal that it is stored, but it does not.
elif user_input == 2: #Schedule a course offering
input_invalid2 = True #Ensure that the user actually provides the input.
while input_invalid2:
input_department = input("Please input the course's department: ").strip()
input_number = input("Please input the course's number: ").strip()
course = None
courseFound = False
for c in schoolie.course_catalog:
if c.department == input_department and c.number == input_number: #Course found in records
courseFound = True
course = c
input_section_number = input("Please enter a section number for this course offering: ").strip()
input_instructor = input("If you would like, please enter an instructor for this course offering: ").strip()
input_year = input("Please enter a year for this course offering: ").strip()
input_quarter = input("Please enter the quarter in which this course offering will be held - either SPRING, SUMMER, FALL, or WINTER: ").strip().upper()
if input_course != "" and input_course in schoolie.course_catalog and input_section_number.isdigit() and input_year.isdigit() and input_quarter in ['SPRING', 'SUMMER', 'FALL', 'WINTER'] and input_credits.isdigit():
if input_instructor != "": #Instructor to be added later, if user chooses option 6.
added_course_offering = CourseOffering(c, input_section_number, None, input_year, input_quarter)
else:
added_course_offering = CourseOffering(c, input_section_number, input_instructor, input_year, input_quarter)
schoolie.add_course_offering(added_course_offering)
input_invalid2 = False #Valid input
print ("You have added course %s, Section %d: %s, worth %d credits."%(input_course,input_section_number,input_name, input_credits))
else:
print("One or more of your entries is invalid. Try again.")
if courseFound == False: #If course has not been found at the end of the loop:
print("The course is not in our system. Please create it before you add an offering.")
break
By the way, I think I have the system closing properly. Correct me if I'm wrong:
elif user_input == 13: #Exit
with open(inst + '.pkl', 'wb') as output:
pck.dump(schoolie, output, pck.HIGHEST_PROTOCOL)
del schoolie
print (farewell)
sys.exit()
except KeyboardInterrupt: #user pushes Ctrl-C to end the program
print(farewell)
I believe that there is something wrong with the way that I am setting up the pickles files. I'm creating them, but I seem not to be putting data into them.
I apologize for the long-winded nature of this question, but I hope that the details will help you understand the problems that I've been having. Thanks in advance for the help!
it seems you may have dump and load reversed: (from the docs)
Signature: pck.load(file, *, fix_imports=True, encoding='ASCII', errors='strict')
Docstring:
Read and return an object from the pickle data stored in a file.
Signature: pck.dump(obj, file, protocol=None, *, fix_imports=True)
Docstring:
Write a pickled representation of obj to the open file object file.
With all those lines of code, it does get a little confusing, but I don't see any code that is pickling and writing the objects to a file.
Before anything else, you should assign the file to a variable so you can reference it. To do this, you'll have code similar to this:MyFile = open("FileName.extension","wb"). MyFile can be any name you want, it will be what you use later to reference the file. FileName is the name of the file itself. This is the name it will have in File Explorer. .extension is the file's extension, specifying the type of file. You should use .dat for this. wb is the file access mode. "w" means write, and "b" means binary. (Pickled objects can only be stored in a binary file.)
To write the pickled objects, you'll need this code:pck.dump(object,MyFile). (Usually, you would use pickle.dump(object,MyFile), but you imported pickle as pck.)
After writing the data to the file, you'll want to retrieve it. To do this, the "wb" instance of MyFile needs to be closed like this:MyFile.close(). Then you'll need to re-open the file in read mode using the following code:MyFile = open("FileName.extension","rb") Then you would use this:object = pickle.load(MyFile) to read the data. In the preceding example, (the load function), your object must have the same name as when you pickled it using the dump function. (pck.dump(object,MyFile))
In the end, you'll end up with something similar to this:
if writing conditions are true:
MyFile = open("FileName.dat","wb")
pickle.dump(object,MyFile) # This will be repeated for each object.
MyFile.close()
if reading conditions are true:
MyFile = open("FileName.dat","rb")
object = pickle.load(MyFile) # This will be repeated for each object.
MyFile.close()
I'm sorry if this wasn't the answer you wanted. Because of all those lines of code, it is somewhat hard to understand. I need clarification to give a better answer.
First I'm sorry this might be a dumb question but I'm trying to self learn python and I can't find the answer to my question.
I want to make a phonebook and I need to add an email to an already existing name. That name has already a phone number attached. I have this first code:
phonebook = {}
phonebook ['ana'] = '12345'
phonebook ['maria']= '23456' , 'maria#gmail.com'
def add_contact():
name = raw_input ("Please enter a name:")
number = raw_input ("Please enter a number:")
phonebook[name] = number
Then I wanted to add an email to the name "ana" for example: ana: 12345, ana#gmail.com. I created this code but instead of addend a new value (the email), it just changes the old one, removing the number:
def add_email():
name = raw_input("Please enter a name:")
email = raw_input("Please enter an email:")
phonebook[name] = email
I tried .append() too but it didn't work. Can you help me? And I'm sorry if the code is bad, I'm just trying to learn and I'm a bit noob yet :)
append isn't working because the dictionary's values are not lists. If you make them lists here by placing them in [...]:
phonebook = {}
phonebook ['ana'] = ['12345']
phonebook ['maria'] = ['23456' , 'maria#gmail.com']
append will now work:
def add_contact():
name = raw_input("Please enter a name:")
number = raw_input("Please enter a number:")
phonebook[name].append(number)