Below is the output that I receive, and below that is my code. Any reasons why I'm getting this memory reference? BTW - indentation is correct in my program but I had difficulty posting it in stackoverflow
>>>Welcome to the Main Menu, Richard.
>>>Please select from the following options:
>>>(1)Punch In
>>>(2)Punch Out
>>>(3)Exit
>>>(type 1, 2, or 3)
>>><__main__.PunchCard instance at 0x7f5c2b799ea8>
And the code
import xlrd
import sys
data = xlrd.open_workbook('data.xls')
sheetname = data.sheet_names()
employee_sheet = data.sheet_by_index(0)
uid_list = [c.value for c in employee_sheet.col(0)]
last_list = [c.value for c in employee_sheet.col(1)]
first_list = [c.value for c in employee_sheet.col(2)]
username_list = [c.value for c in employee_sheet.col(3)]
password_list = [c.value for c in employee_sheet.col(4)]
class PunchCard:
def idle_screen(self):
sys.stderr.write("\x1b[2J\x1b[H")
print "Press Enter to start PunchClock"
raw_input()
return self.user_login()
def user_login(self):
sys.stderr.write("\x1b[2J\x1b[H")
userinput = raw_input("Please enter your username.\n> ")
if userinput in username_list:
user_index = username_list.index(userinput)
self.user_first = first_list[user_index]
user_password = raw_input("Welcome %s, please enter your password.\n> " % self.user_first)
else:
print "That is an incorrect username."
raw_input("Press enter to re-enter your username.")
return self.user_login()
if user_password == password_list[user_index]:
return self.main_menu()
else:
sys.stderr.write("\x1b[2J\x1b[H")
print "You have entered an incorrect password.\nPress enter to try again, or type QUIT to return to previous menu."
raw_input()
return self.user_login()
def main_menu(self):
sys.stderr.write("\x1b[2J\x1b[H")
print "Welcome to the Main Menu, %s.\nPlease select from the following options:\n (1)Punch In\n (2)Punch Out\n (3)Exit\n\n(type 1, 2, or 3)" % self.user_first
menu_input = raw_input(self)
if menu_input == '1':
print "punched in"
raw_input("You clocked in at XX. Press enter to continue.")
return self.main_menu()
elif menu_input == '2':
print "punched out"
raw_input("You clocked out at XX. Press enter to continue.")
return self.main_menu()
elif menu_input == '3':
return self.idle_screen()
else:
return self.main_menu()
s = PunchCard()
s.idle_screen()
Ok, based on your comment, I'll answer in more detail then. But please note, I am providing an example based on the your code (there are better ways to achieve the same result, but you'll just have to bite down and read the docs).
The high-level flow of your application is the following infinite loop: idle screen -> user login -> main menu -> idle screen. So this should be expressed directly:
s = PunchCard()
while True:
s.idle_screen()
s.user_login()
s.main_menu()
Then, idle_screen should simply wait for input and return (exit method):
def idle_screen(self):
sys.stderr.write("\x1b[2J\x1b[H")
print "Press Enter to start PunchClock"
raw_input()
# method returns to caller at this point
user_login() should loop until a valid login occurs and return (exit method):
def user_login(self):
While True:
sys.stderr.write("\x1b[2J\x1b[H")
userinput = raw_input("Please enter your username.\n> ")
if userinput in username_list:
user_index = username_list.index(userinput)
self.user_first = first_list[user_index]
user_password = raw_input("Welcome %s, please enter your password.\n> " % self.user_first)
else:
print "That is an incorrect username."
raw_input("Press enter to re-enter your username.")
continue # start of the beginning of the loop again
if user_password == password_list[user_index]:
return # exit method
else:
sys.stderr.write("\x1b[2J\x1b[H")
print "You have entered an incorrect password.\nPress enter to try again, or type QUIT to return to previous menu."
raw_input()
# do nothing here (will loop again)
# Note your prompt mentions "QUIT" but you don't handle it ;)
# Current logic means the login loop continues until a valid login occurs
Finally, main_menu loops until the user quits and the method returns (and everything starts over with the top-level loop):
def main_menu(self):
While True:
sys.stderr.write("\x1b[2J\x1b[H")
print "Welcome to the Main Menu, %s.\nPlease select from the following options:\n (1)Punch In\n (2)Punch Out\n (3)Exit\n\n(type 1, 2, or 3)" % self.user_first
menu_input = raw_input(self)
if menu_input == '1':
print "punched in"
raw_input("You clocked in at XX. Press enter to continue.")
elif menu_input == '2':
print "punched out"
raw_input("You clocked out at XX. Press enter to continue.")
elif menu_input == '3':
return
Hope that helps.
But still, bite down and read the docs :)
Related
I'm creating a simple login program. It asks you for a username, then the password. If you type the correct password, you're in, else, you get a genial request to repeat your password. here is the code:
while True:
turns= 5
turns= turns-1
print ("Username")
L_username= input ("")
print ("Authorising...")
time.sleep(2)
if(L_username)==("test#test.test"):
for x in range (5):
print ("Please enter the password")
passwordlogin= input("")
if passwordlogin == ("beta123"):
print ("Hello, developer.")
break
break
else:
print ("Incorrect. You have",turns," more turns")
now the thing is, it gives me an error message: incorrect syntax for else: print ("incorrect... I know this is meant an issue because I wrote two 'breaks', the latter out of the for loop... which means it will break the while True loop at the start whether or not I go into the loop... which means the 'else' statement is out of the loop (sorry, I am not the best explainer at these things)... which gives the error message. But I don't understand how I should fix this problem... can anyone help?
I hope you understood me!
This could be triviallized by using a function and returning from it once you reach that if statement.
def func():
while True:
turns= 5
turns= turns-1
print ("Username")
L_username= input ("")
print ("Authorising...")
time.sleep(2)
if(L_username)==("test#test.test"):
for x in range (5):
print ("Please enter the password")
passwordlogin= input("")
if passwordlogin == ("beta123"):
print ("Hello, developer.")
return
else:
print ("Incorrect. You have",turns," more turns")
However, if you insist on not having a function, you can basically have a flag in your code that you set to true inside that if block. Before continuing the outer loop, you should check if this flag is set to True, if it is, you can safely break.
while True:
success = False
turns= 5
turns= turns-1
print ("Username")
L_username= input ("")
print ("Authorising...")
time.sleep(2)
if(L_username)==("test#test.test"):
for x in range (5):
print ("Please enter the password")
passwordlogin= input("")
if passwordlogin == ("beta123"):
print ("Hello, developer.")
success = True
break
else:
print ("Incorrect. You have",turns," more turns")
if success:
break
Note should be taken for nested loops and such intense nesting for what is essentially a trivial problem. Please try to use a singular loop with your conditions.
You need to swap the else and break and change the break's indentation. If the user gets the correct username you want to test the password at most 5 times and then quit
while True:
turns= 5
print ("Username")
L_username= input ("")
print ("Authorising...")
time.sleep(2)
if(L_username)==("test#test.test"):
for x in range (5):
print ("Please enter the password")
passwordlogin= input("")
if passwordlogin == ("beta123"):
print ("Hello, developer.")
break
else:
turns -= 1
print ("Incorrect. You have",turns," more turns")
break
So in this case you run the for loop and then break
Well I have written your concept in my own way. Hope this works for you
turns = 5
while turns != 0:
username = input('Enter Username: ')
password = input(f'Enter password for {username}: ')
if username == 'test#test.test' and password == 'beta123':
print('Hello developer')
turns = 0 # Breaking while loop if user get access within number of "turns"
else:
turns = turns - 1 # Or turns -= 1
print('Incorrect username or password')
print(f'You have {turns} turns for gaining access')
I am trying to finish off my program my adding a menu that allows the user to select a few options that allow the user to store website names and passwords in lists. But there was a problem as soon as I have appended some website names and passwords into their respective vaults where whenn I try to select an option after appending the website names and passwords, "1" for example is the expected input to call the viewapp() function to see the websites and passwords stored so far. The thing is it takes more than twice to call the viewapp() function, where it rejects the first expected input but accepts the 2nd one strangely. Also when I select the 3rd option for the purpose to call summary(), the whole printed summary would print out twice, which is a similar pattern to the menu only accepting the 2nd expected input. The program is doing what I want except for this annoying bug where selecting those four options makes it ask for input a second time when it's supposed to straight away jump to that function. Help would be appreciated.
appvault = []
passvault = []
def logged():
print("----------------------------------------------------------------------\n")
print("Hello, welcome to the password vault console. ")
modea = input("""Below are the options you can choose from in the password vault console:
##########################################################################\n
1) Find the password for an existing webiste/app
2) Add a new website/app and a new password for it
3) Summary of the password vault
4) Exit
##########################################################################\n
> """).strip()
return modea
def viewapp():
if len(appvault) > 0:
for app in appvault:
print("Here is the website/app you have stored:")
print("- {}\n".format(app))
if len(passvault) > 0 :
for code in passvault:
print("Here is the password you have stored for the website/app: ")
print("- {}\n".format(code))
else:
print("You have no apps or passwords entered yet!")
def addapp():
while True:
validapp = True
while validapp:
new_app = input("Enter the new website/app name: ").strip().lower()
if len(new_app) > 20:
print("Please enter a new website/app name no more than 20 characters: ")
elif len(new_app) < 1:
print("Please enter a valid new website/app name: ")
else:
validapp = False
appvault.append(new_app)
validnewpass = True
while validnewpass:
new_pass = input("Enter a new password to be stored in the passsword vault: ")
if not new_pass.isalnum():
print("Your password for the website/app cannot be null, contain spaces or contain symbols \n")
elif len(new_pass) < 8:
print("Your new password must be at least 8 characters long: ")
elif len(new_pass) > 20:
print("Your new password cannot be over 20 characters long: ")
else:
validnewpass = False
passvault.append(new_pass)
validquit = True
while validquit:
quit = input("\nEnter 'end' to exit or any key to continue to add more website/app names and passwords for them: \n> ")
if quit in ["end", "End", "END"]:
logged()
else:
validquit = False
addapp()
return addapp
def summary():
if len(passvault) > 0:
for passw in passvault:
print("----------------------------------------------------------------------")
print("Here is a summary of the passwords stored in the password vault:\n")
print("The number of passwords stored:", len(passvault))
print("Passwords with the longest characters: ", max(new_pass for (new_pass) in passvault))
print("Passwords with the shortest charactrs: ", min(new_pass for (new_pass) in passvault))
print("----------------------------------------------------------------------")
else:
print("You have no passwords entered yet!")
while True:
chosen_option = logged()
print(chosen_option)
if chosen_option == "1":
viewapp()
elif chosen_option == "2":
addapp()
elif chosen_option == "3":
summary()
elif chosen_option == "4":
break
else:
print("That was not a valid option, please try again: ")
print("Goodbye")
This happens because you call logged() when exiting addapp():
if quit in ["end", "End", "END"]:
logged()
Then, the choice you enter is returned by logged(), and thrown away as it isn't assigned to anything.
You're now back at the end of the previous block in addapp(), and the next instruction is return addapp, that will bring you back to your main loop, where you'll be sent to logged() again by chosen_option = logged()
Note that in return addapp, you return the addapp function itself, which is certainly not what you want to do. So, as you don't need a return value for addapp(), just use return, or nothing at all, Python will automatically return at the end of the function.
So, to solve your problem: directly return when you're done entering sites:
if quit in ["end", "End", "END"]:
return
Note also that you recursively call addapp() from itself when you add more sites.
You should generaly avoid that unless you really want to use some recursive algorithm, and rather use a loop as you did in your main loop. By default, Python limits you to 1000 recursion levels - so you could even crash your app by entering more than 1000 sites in a row ;)
The summary problem is only caused by the unnecessary for loop in summary()
You are nearly there. The issue is in the addapp() function at line 63:
if quit not in ["end", "End", "END"]:
logged()
if you replace
logged()
with
pass
Then everything will work a ok.
You are not handling the result of the logged function here anyway.
You also do not need to process the logged function here. The addapp will exit and the logged function will be called and handled in the while loop the addapp function was called from.
Alright so here's the code
def user_password():
input('Please Enter Password: ')
#profiles
def intercept():
user_password()
if user_password == "intercept":
print("this is working so far")
else:
print("Incorect Password")
def Jimmy():
user_password()
if user_password == "Jimmy":
print("this is working so far")
else:
print("Incorect Password")
def Tommy():
user_password()
if user_password == "Tommy":
print("this is working so far")
else:
print("Incorect Password")
#login
user_functions = dict(
intercept=intercept,
Jimmy=Jimmy,
Tommy=Tommy,
# ...
)
user_input = input("Input function name: ")
if user_input in user_functions:
user_functions[user_input]()
else:
print("Error: Unknown function.")
PROBLEMS:
My code always starts with asking for the password even though I don't want it
to.
When I change the first variable to a function it fixes this
Why does it execute when I'm just setting the variable. I'm pretty sure I shouldn't have to use a function instead of a variable
No matter what it always ends up as Incorrect Password even if I give the correct password
I think you are trying to write something like that:
def get_user_password():
return input('Please Enter Password: ')
def Jimmy():
user_password = get_user_password()
if user_password == "Jimmy":
print("this is working so far")
Here is my code:-
f= open("Passes.py", "a+")
m=open("money.py","a+")
passes= {}
init={}
initial=0
import time
print "Welcome to the virtual banking system"
user=raw_input("Would you like to create a new account? 'Y/N'").lower()
if user== "y":
new_user= raw_input("Create a username:")
new_pass= raw_input("Create a password:")
p= passes[new_user]= new_user + ":" + new_pass
f.write("\n"+p)
ask=raw_input("Would you like to sign into your account? 'Y/N'").lower()
if ask=="y":
user_in=raw_input("Enter your username:")
if user_in==new_user:
pass_in=raw_input("Enter your password:")
if pass_in==new_pass:
print "Welcome to your account" + " " + new_user
**useropt=raw_input("Would you like to view your balance- enter 1, deposit money- enter 2, withdraw money- enter 3 or exit- enter 4:")**
if useropt=="1":
print "Your balance is:", initial
m.write(str(initial)+"\n")
if useropt=="2":
amountdep= int(raw_input("How much money would you like to deposit?:"))
initial+=amountdep
print "Thanks. Your new balance is:", initial
m.write(str(initial)+"\n")
if useropt=="3":
amountwith=int(raw_input("How much would you like to withdraw?:"))
initial-=amountwith
print "Your balance is:", initial
m.write(str(initial)+"\n")
else:
print "Password not valid"
else:
print "Username does not exist"
else:
print "Thanks for using the virtual bank."
else:
user2=raw_input("Do you have an existing account? 'Y/N'").lower()
if user2=="y":
existing_user=raw_input("Enter your username:")
exisitng_pass=raw_input("Enter your password:")
for passwords in f:
if passwords==existing_user+":"+exisitng_pass:
print "Welcome to your account" + " " + existing_user
with open("money.py", "r") as m:
info= int(m.readline().strip())
useropt2=raw_input("Would you like to view your balance- enter 1, deposit money- enter 2, withdraw money- enter 3 or exit- enter 4:")
if useropt2=="1":
print "Your balance is:", info
if useropt2=="2":
amountdep= int(raw_input("How much money would you like to deposit?:"))
a=info+int(amountdep)
print "Your new balance is:", a
with open("money.py", "w") as m:
m.write(str(a))
if useropt2=="3":
amountwith=int(raw_input("How much would you like to withdraw?:"))
t=info-int(amountwith)
print "Your balance is:", t
with open("money.py", "w") as m:
m.write(str(t))
I would like to know how I can create a loop to ask the user if he/she would like to choose another operation, such as the useropt variable after each time, one operation is complete. For instance at the end of each if statement where the user chooses a certain operation to do, I would like to know how I can ask the user again, if they would like to do another operation. Thanks.
After you import time you could do:
running = True
while running:
print "Welcome to the virtual banking system"
#the rest of your code, indented by one.
continue = raw_input("Would you like to do another operation? 'Y/N'").lower()
running = continue == "y"
This will give the user an option to quit after every operation, but restart otherwise.
Your code should be structured otherwise, using a while loop and a function to handle input.
General example :
# this code should go after creating a new account/entering an existing one
while True:
Ans = raw_input("what would you like to do? 1... 2... , -1 to exit")
int code = ProcessAns(int(Ans))
if code == -1:
print "bye!"
break
# and here the function that will be called every time
def ProcessAns(ans):
if ans == 1:
# do stuff
elif ans == 2:
# do other stuff
# include a way to get out
elif ans == -1:
return -1
return 1
Hi I have this project of Mad libs but I donĀ“t know how to make a function that ask the user what level of difficulty between easy, medium or hard they want, and depending on their answer redirect them to the desired level of mad libs. This is what I have so far. Thanks.
parts_of_speech_words = ["VERB","PLACE","ADJECTIVE","NOUN","PLURALNOUN","ADVERB"]
level_easy = """I __VERB__ to go to the __PLACE__
but I don't go in the __ADJECTIVE__
I am __ADJECTIVE__ of the __NOUN__
and getting __VERB__ by a __NOUN__."""
level_medium = """Begging to hear __NOUN__
My ears remain __ADJECTIVE__
__NOUN__ for signs
my __NOUN__ remain __VERB__
Yet __NOUN__still VERB."""
level_hard = """I __VERB__ you without __NOUN__
how, or when, or from where,
I love you __ADVERB__,
without __PLURALNOUN__ or pride;
So I love you because I know
no other way that this:
Where I does not VERB, nor you,
so close that your NOUN
on my chest is my hand,
so close that your NOUN close
as I fall ADJECTIVE."""
greeting = raw_input ("Welcome to mad libs, What's your name? ")
prompt = raw_input ("Select your level: easy, medium or hard: ")
def entry_level_prompt (variable_level):
easy = level_easy
medium = level_medium
hard = level_hard
for e in variable_level:
if prompt == easy:
return level_easy
print level_easy
if prompt == medium:
return level_medium
print level_medium
if prompt == hard:
return level_hard
print lever_hard
print "Ok %s you chose the %s level" % (greeting , prompt)
print entry_level_prompt (variable_level)
def parts_of_speech (words_string, list_of_part_of_speech):
for pos in list_of_part_of_speech:
if pos in words_string:
return pos
return None
def play_mad_libs (split_string, list_of_part_of_speech):
replaced = []
split_string = split_string.split ()
for words_string in split_string:
replacement = parts_of_speech (words_string, list_of_part_of_speech)
if replacement != None:
user_input = raw_input ("Type in a: " + replacement + " ")
words_string = words_string.replace (replacement, user_input)
replaced.append(words_string)
else:
replaced.append(words_string)
replaced = " ".join(replaced)
return replaced
print play_mad_libs (entry_level_prompt, parts_of_speech_words)
You have a bug in your code. You are calling entry_level_prompt(variable_level) but variable_level does not exist outside of the method scope.
To control the difficulty, you can create a method called get_difficulty()
def get_difficulty():
choice = ""
while choice not in ('easy', 'medium', 'hard'):
choice = raw_input("choose your difficulty: ")
if choice == "easy":
return level_easy
elif choice == "medium":
return level_medium
elif choice == "hard":
return level_hard
else:
print("Invalid choice...")
You've confused the selector -- "easy", "medium", or "hard" -- with the variable you want to return -- level_easy, level_medium, or level_hard. You cannot use the variable prompt for both purposes at the same time.
I recommend that you keep variable prompt as you started: it holds the user input. Then, simply test it and return the needed script:
if prompt == "easy":
return level_easy
elif prompt == "medium"
return level_medium
elif prompt == "hard"
return level_hard
else:
"Please enter easy, medium, or hard for the level."