What's the best way to implement this - reuse user input on menu?
Here's my sample code below:
def input():
user = raw_input('user: ')
passwd = getpass.getpass('passwd: ')
return (user,passwd)
def function1():
user, passwd, vcenter = input()
do something
def function2():
user, passwd, vcenter = input()
do something
def function3():
user, passwd, vcenter = input()
do something
def main():
while True:
if choice == 1:
function1()
elif choice == 2:
function2()
elif choice == 3:
function3()
else:
print 'Choose from the options only!'
break
I think i get what you mean, you want to use the input() once in the while loop, and not repeat calling it in every function. if so I suggest this solution:
def input():
user = raw_input('user: ')
passwd = getpass.getpass('passwd: ')
return (user,passwd)
def function1(param):
user, passwd = param
do something
def function2(param):
user, passwd = param
do something
def function3(param):
user, passwd = param
do something
def main():
while True:
if choice in [1,2,3]:
param = input()
if choice == 1:
function1(param)
elif choice == 2:
function2(param)
elif choice == 3:
function3(param)
else:
print 'Choose from the options only (1, 2, 3): '
break
hope this helps.
Related
The example code that I used
the main idea is when the user enters the wrong input, it will return a menu choice to let the user back to main_menu or continue
but when i want to enter data and choose back to main_menu and try to terminate it, the TenantID function still running
def TenantID():
while True:
error_list = []
tenant_id = str(input("1.Enter your Tenant ID: "))
if ValidateTenantID(tenant_id, error_list):
print(*error_list)
if MenuChoice() is True:
menu()
else:
continue
else:
break
return tenant_id
def MenuChoice():
Choice = input("\x1B[1m" + "Press M return to main menu or Any key
to continue: " + '\x1B[0m')
if Choice in ["M", "m"]:
return True
else:
return False
def ValidateTenantID(tenant_id, error_list):
returnValue = CheckLength(tenant_id)
if returnValue is True:
returnValue = CheckTenantID(tenant_id)
if returnValue is True:
returnValue = CheckDataIfExist(tenant_id)
if returnValue is not True:
error_list.append(returnValue)
else:
error_list.append(returnValue)
else:
error_list.append(returnValue)
return error_list
The problem
If you want to terminate from the menu function, then return from it and/or stop the loop that is running it.
For example,
running = True
def menu():
print('options...')
choice = input('> ')
if choice == '5':
global running
running = False
return # completely stop this function from doing other things
elif choice == '1':
tid = TenantID()
def TenantID():
valid = False
while not valid:
error_list = []
tenant_id = input("1.Enter your Tenant ID: ")
valid = ValidateTenantID(tenant_id, error_list)
print(*error_list)
if MenuChoice():
break
if not valid:
return None
else:
return tenant_id
while running: # can be changed from the menu function via global variable
menu()
print('bye')
def userQty():
name = input("Quantity: ")
return name
def userAdd():
add = input("What would you like to add do your cart? ")
return add
def userInfo():
data = {}
while True:
result = input(
"Make your shopping list. Please type (Show/Add/Delete/Clear/Quit). ")
if result.lower() == 'add':
data[userQty()] = userAdd()
elif result.lower() == 'show':
print(data)
elif result.lower() == 'delete':
print("Still working on that, use 'clear' for now please.")
# Could not figure out how to remove one item
elif result.lower() == 'clear':
dLi = input("Clear your list?: [y/n] ").lower()
if dLi in ["y", "yes"]:
data = {}
print("Your list has been cleared.")
print(data)
elif dLi in ["n", "no"]:
print("Action Abandoned.")
elif result.lower() == 'quit':
break
else:
print(
'Oops! Something went wrong. Please type "(Show/Add/Delete/Clear/Quit)"')
print(data)
return data
userInfo()
I am fairly new to programming as a whole so I'm sorry if the code is sloppy or if I am not being specific enough?
I tried adding:
def __init__(self):
return #something
I am lost as far as where to go from here.
You could add:
class Somthing():
def __init__(self):
code
and add the variables to self, like this:
self.name = name
also put (self): in the function parentheses.
One approach might be to make your different menu items methods on your object:
class ShoppingCart:
def __init__(self):
self.data = {}
def add(self):
i = input("What would you like to add to your cart? ")
self.data[i] = input("Quantity: ")
def clear(self):
if input("Clear your list? [y/n] ").lower().startswith("y"):
self.data = {}
print("Your list has been cleared.")
else:
print("Action abandoned.")
def delete(self):
print("Still working on that, use 'clear' for now please.")
def menu_loop(self):
while True:
i = input(
"Make your shopping list. "
"Please type (Show/Add/Delete/Clear/Quit). "
).lower()
if i == "quit":
break
try:
getattr(self, i)()
except AttributeError:
print(
'Oops! Something went wrong. '
'Please type "(Show/Add/Delete/Clear/Quit)"'
)
cart = ShoppingCart()
cart.menu_loop()
print(cart.data)
This question already has answers here:
Python: Name resolution; order of function def's
(5 answers)
Closed 5 years ago.
I'm not sure how to fix my code, could someone help!
It prints this --> "NameError: free variable 'info' referenced before assignment in enclosing scope", I don't know how to make info a global variable, i think that is the problem...Someone please help!
import time
import random
admincode = ["26725","79124","18042","17340"]
stulogin = ["NikWad","StanBan","ChrPang","JaiPat","JusChan","AkibSidd","VijSam"]
teachercode = ["KGV"]
def main():
def accesscontrol():
global teachercode, stulogin, admincode
print("Enter: Student,Teacher or Admin")
option = input("--> ")
if option == "Student":
info()
elif option == "Teacher":
print("Enter you teacher code(xxx)")
option = input
if option == teachercode:
print("Access Granted")
info()
else:
print("Please input the correct code!")
accesscontrol()
elif option == "Admin":
print("Enter your admin code(xxxxx)")
option = input("--> ")
if option == admincode:
print("access granted, my master!")
else:
accesscontrol()
accesscontrol()
def info():
print("Hello, enter your information below")
usname = input("Username: ")
pwname = input("Password: ")
done = False
while not done:
print("Is this the information correct?[Y/N]")
option = input("--> ")
if option == "Y":
print("Information saved")
print("Username :",usname,"\nPassword:",pwname)
done = True
else:
main()
return info()
info()
main()
The problem is that you define accesscontrol and info as local names relative to main. So when you call info inside accesscontrol it can't find it, because it's a name "owned" by in other words local to main.
Instead of having the functions like this:
def main():
def accesscontrol():
# ...
def info():
# ...
# ...
Move them out of main() like this:
def accesscontrol():
# ...
def info():
# ...
def main():
# ...
Thus keeping main() as simply:
def main():
accesscontrol()
info()
You need to define info() before it is called. Also you had an unnecessary call to info(), which I removed.
import time
import random
admincode = ["26725", "79124", "18042", "17340"]
stulogin = ["NikWad", "StanBan", "ChrPang", "JaiPat", "JusChan", "AkibSidd", "VijSam"]
teachercode = ["KGV"]
def main():
def info():
print("Hello, enter your information below")
usname = input("Username: ")
pwname = input("Password: ")
done = False
while not done:
print("Is this the information correct?[Y/N]")
option = input("--> ")
if option == "Y":
print("Information saved")
print("Username :", usname, "\nPassword:", pwname)
done = True
else:
main()
return info()
def accesscontrol():
global teachercode, stulogin, admincode
print("Enter: Student,Teacher or Admin")
option = input("--> ")
if option == "Student":
info()
elif option == "Teacher":
print("Enter you teacher code(xxx)")
option = input
if option == teachercode:
print("Access Granted")
info()
else:
print("Please input the correct code!")
accesscontrol()
elif option == "Admin":
print("Enter your admin code(xxxxx)")
option = input("--> ")
if option == admincode:
print("access granted, my master!")
else:
accesscontrol()
accesscontrol()
main()
I want to optimize my code to return well in a part of a code.
I know that I can do that with do while but I think it's maybe heavy with a lot of do while.
I identify where I want to return in comments
Can you suggest me a solution to solve my problem?
#return here 0
mainMenu()
choix = input()
if choix == 1:
print "Enter your username"
username = raw_input()
print "Enter your password"
password = raw_input()
createAccount.createAccount(username,password)
#return here 1
educatorMenu()
choix = input()
if choix == 1:
print "Enter his age"
ageChild = raw_input()
print "Enter his photo"
photoChild = raw_input()
educator.createChildAccount(ageChild, photoChild)
elif choix == 2:
childrenList = educator.seeChildrenList()
#Return to where it is written "return here 0"
elif choix == 3:
childrenList = educator.seeChildrenList()
print "Associate children?"
choixEnfant = input()
educator.associateChildren(childrenList,choixEnfant-1, educator.getIdEducator(username))
#Return to where it is written "return here 1"
Thanks a lot.
Note: I will not re-write/optimize your code, because I feel it should be a task for you to do so. Furthermore, there are quite some functions and references missing to rewrite it; you did not deliver an MWE.
Consequently, you may find this useful as a starting point and try to adapt this (very basic structure) to suit your needs. However, be warned: This also is far from being efficient, but it will help you to extend your knowledge of the basics.
def menu_main():
q = ['What would you like to do?',
'1: List educators',
'2: Create educator',
'3: Manage educator\'s children',
'4: Exit'].join('\n ')
return int(input(q).strip()[0])
def menu_educator_create():
usr = input('Enter username:').strip()
pwd = input('Enter password:').strip()
return (usr, pwd)
def menu_educator_manage():
q = ['What would you like to do?',
'1: List children',
'2: Add child',
'3: Return'].join('\n ')
return int(input(q).strip()[0])
if __name__ == '__main__':
edus = {}
exit = False
while not exit:
print('===')
cmd = menu_main()
if cmd == 1:
# List educators
pass
elif cmd == 2:
# Create educator
usr, pwd = menu_educator_create()
pass
elif cmd == 3:
# Manage children
# (should somehow obtain current educator first)
exit_edu = False
while not exit_edu:
subcmd = menu_educator_manage()
if subcmd == 1:
# List children
pass
elif subcmd == 2:
# Add child
pass
elif subcmd == 3:
# Return
exit_edu = True
else:
# None of the above
print('Unknown choice from educator menu.')
elif cmd == 4:
# Exit
exit = True
else:
# None of the above
print('Unknown choice from main menu.')
I am currently attempting to make a login/signup program on my computer that will allow for multiple sets of usernames and passwords. Right now anytime I sign up, it overwrites the previous login. I am using Python 3.4.
Is there a way I can prevent this?
My code is available below:
import os
import pickle
import sys
import time
user_name = 'default'
pass_word = '12345'
login = {'username' : user_name,
'password' : pass_word}
def cls():
os.system('cls')
def space():
print(' ')
def load():
with open('logins', 'rb') as f:
login = pickle.load(f)
def save():
with open('logins', 'wb') as f:
pickle.dump(login, f)
def MainMenu():
print('Select an Option.')
while True:
print('1) Login')
print('2) Signup')
user_input = input('Option #: ')
if user_input == '1':
cls()
login_user()
elif user_input == '2':
cls()
signup_user()
else:
cls()
continue
def signup_user():
user_chosen_name = input('Username: ')
login['username'] = user_chosen_name
user_chosen_password = input('Password: ')
login['password'] = user_chosen_password
space()
cls()
print('Setup complete. Please login.')
os.system('pause')
save()
cls()
login_user()
def login_user():
load()
while True:
print('Please Login.')
space()
user_input_name = input('Username: ')
user_input_password = input('Password: ')
if user_input_name == login['username'] and user_input_password == login['password']:
space()
print('Login Successful.')
else:
space()
print('Login Failed. Please Try Again.')
while True:
print('1) Try Again.')
print('2) Main Menu.')
user_cont = input('Continue?: ')
if user_cont == '1':
cls()
break
elif user_cont == '2':
cls()
MainMenu()
break
if __name__ == '__main__':
if os.path.isfile('logins') == False:
save()
else:
pass
MainMenu()
Here are two proposals for the login/password data model.
Use a dictionary, this is probably the simplest way ; I suggest using this.
# init with default
passwords = {user_name: pass_word}
# password look-up
if login in passwords:
print passwords[login]
else:
print 'User', login, 'is not registered'
# password set or update
password[login] = new_password
List of couples or list of dictionaries.
This may be closer to your current solution, but I would not recommend it.
I only show what the initialization would be.
# list of couples
logins = [(user_name, pass_word)]
# list of dictionaries
logins = [{'username' : user_name,
'password' : pass_word}]