ok this is more of a conceptual question, but if i have an array of strings, how can i make a condition where i have a program that tracks a chat and prints out the players name, how can i make a condition where i have a loop that prints the players name every time they chat once i turn on the program, but if they chat again, and my program recognizes the familiar name, it wont print their name out again, essentially only printing out that persons name once
userName = "ThePlayersName" # constantly changing
nameTracker = []
if userName not in nameTracker:
print(userName)
I understand the program is wrong, but just assume 'UserName' is constantly changing and the userName is being added to the array, or another way to print out the name only once
Instead of an array, you could use a set, which can contain only distinct elements. You can use nameTracker.add(userName) and it will only add the name if it's not already in the set.
What you have will work just fine.
userName = "ThePlayersName" # constantly changing
nameTracker = []
def printUser(name):
if name not in nameTracker:
print(name)
printUser(userName)
nameTracker.append(userName)
printUser("Player 2")
nameTracker.append("Player 2")
printUser("Player 2")
prints
ThePlayersName
Player 2
Related
I have a tkinter app where I have Labels, Entries and Button. Whenever I click the button, the entries get passed to a function where they are verified according to a format.
For example -
Two fields - Employee Name, Employee Id
Now, I wish to check if username starts with "EMP" or not. For that I have made some functions(like checks if alphanumeric or not etc). If the username does not start with "EMP", what I am doing now is showing an error box like this
def tracking_images(self,emp_id,emp_name):
emp_id, emp_name = emp_id.get(), emp_name.get()
if len(emp_id) == 0:
tk.messagebox.showerror("Field error", "Employee ID cannot be empty")
elif len(emp_name) == 0:
tk.messagebox.showerror("Field error", "Employee name cannot be empty")
if not ValidationConditions().first_three_chars(emp_id):
tk.messagebox.showerror("Field error", "Employee ID should start with EMP")
........
........
#Some more code which I don't want user to have until he/she fixes the error from above checks. <-------
Now, after the user clicks "Ok" to any prompt, The code which I don't want user to access still accesses.
How to not user process further until he fixes the errors from the above checks ?
You could approach this in a do-while manner (even if pyhton does not support this semantically)
Pseudo code would look like this:
while True:
ask the name
if the name passes the checks break out of the loop
show errors
code to go to when the name is valid
EDIT: I forgot to note that, as mentioned below, this would have to be done in an extra thread.
Another thing that might work is putting the dialogs in a method that calls itself if the name is invalid to start over.
But I never tried that and cannot test it since I am commuting right now.
I hope you're doing great! I would really appreciate if you help me with this problem of mine. I wrote this code that creates dictionary based on user's input, then updates it, sorts by keys and values, finds if the item is in the dictionary, counts the number of unique values and, finally, saves the original dictionary to the .txt file. The code itself works fine, but I wanted to present it as a menu so that user could choose what he/she would want to do next, but when I tried to just call the functions from the menu it didn't work and now I have no idea how to do it properly. Could you explain how I can do that? Thanks in advance!
1) Add a menu function, I only did the first three so that you can get the idea (you can do the rest of them), for example.
def menu():
print '1) Create a dictionary'
print '2) Update the dictionary'
print '3) Sort the dictionary'
task = raw_input('Enter the number to perform the corresponding task: ')
if task == '1':
user_dict = creating_dictionary()
elif task == '2':
try:
updating_dictionary(user_dict)
except UnboundLocalError:
print "A dictionary doesn't exist, you'll have to create one\n"
creating_dictionary()
elif task == '3':
try:
sorting_dictionary(user_dict)
except UnboundLocalError:
print "A dictionary doesn't exist, you'll have to create one\n"
creating_dictionary()
2) add menu() as your first statement in main()
3) at the end of every function add a call to menu()
4) If you set it up correctly then the only call you'll need in main() is menu(). You'll be able to delete all of the other function calls since at the end of every function you'll be calling menu().
So I'm trying to make a function that prompts the user for an option, and depending on which option it does something to the information.
Optionone() basically asks the user for information for a single contact, and every time this contact is filled out it creates a list in a list full of the diff contacts.
In optionthree() I am trying to ask a user for a contact they want to display. So once they type in the name of the contact, the code should display the entire list consisting of the contact's information (name, address, phone, email).
I've excluded the other options that are irrelevant to this problem.
contact = []
def optionone():
contactinfo = []
name = str(input("Name: "))
address = str(input("Address: "))
phone = str(input("Phone: "))
email = str(input("Email: "))
contactinfo.append(name)
contactinfo.append(address)
contactinfo.append(phone)
contactinfo.append(email)
contact.append(contactinfo)
contactinfo = []
This is the optionthree function.
def optionthree(contactinfo):
search = input("Name of contact: ")
if search in contactinfo:
print("This is what I'm trying to figure out")
else:
print("There is no contact with that name in your address book.")
return contactinfo
And the main menu function
def menu():
option = int(input("""
Menu Options:
1. Add new contact
2. Display address book
3. Search for contact
4. Modify contact
5. Delete contact
6. Exit
Choose an option: """))
if option == 1:
optionone()
elif option == 3:
info = optionthree(contactinfo)
main()
Right now, when I run this in terminal, it tells me that I'm referencing to the variable contactinfo before it is assigned. The whole concept of parameters and passing variables through functions is very confusing for me; what is wrong in this code?
you use contactinfo in the main function, but didn't define it in the main function. I notice you define a global variable "contact". Not sure if it is the same variable
It looks like you are attempting to reference contactinfo before it gets assigned any values. If you need to have executed option 1 before executing option 3, then you may want option 3 to first check if contactinfo exists. If it doesn't exist, I would suggest writing that line as the following:
info = optionthree(optionone())
Here at Stack Overflow, we handle one problem at a time. In this case, the immediate problem is the undefined variable. Please handle the info look-up in a separate posting, if you still can't figure it out.
I'm going to get rid of extra information for illustration. It's a good programming technique: take little steps. First, we're going to get a name only into the list and be able to find it. You have almost everything hooked up.
The basic principle to remember is that each function has its own "name space" (directory of variables and values). Functions communicate with each other through the parameter list and return values. Yes, there are global variables, too. For now, don't use them.
The purpose of option_one is to add a name to the info list, and make the change available to the main program. You forgot the last part: you have to send back the updated list when you're done:
def option_one(contact_list):
name = str(input("Name: "))
contact_list.append(name)
print("OPT 1 contact_list", contact_list) # trace what you do for debugging purposes.
return contact_list
def menu():
# Menu text omitted
master_list = []
if option == 1:
master_list = option_one(master_list)
print("MAIN ", master_list)
elif option == 3:
info = option_three(master_list)
menu()
Make your main program "own" the master list -- the option functions merely get a copy, do their "thing", and return the updated list (if needed). The main program has to initialize that list, master_list, and hand it off to each chosen function.
Each function has its own little world: what it got from the calling program, the local variables it creates, and what it hands back when it's done. Each routine can call that contact list by whatever local name it chooses; I've called it contact_list (as you did, but with "Pythonic" punctuation).
Output:
Choose an option: 1
Name: Mark
OPT 1 contact_list ['Mark']
MAIN ['Mark']
I have a file in which I have people listed as 'ID Name PhoneNumber Address', like this:
1 Mike 0752 Dallas Alley
2 John 0744 Square Avenue
3 Johnny 0923 Corner Street
Whenever I try to delete or modify a person it won't let me do so, unless I added the person during program execution. What I mean is, I run my program, and unless I add the person(via an add method I use) right then, I won't be able to modify my file.
I can add people to the file, like I said, but even then, it doesn't check if the ID already exists, even though I have this set up in my method.
I should mention that I have a class based program, with repository-controller-UI structure. The SAVE function that I have in my repository is:
def save(self, pers):
'''
Saves a person in class Persoana, returns ValueError if the ID already exists
'''
for i in self.__persList:
if(i.idPers == pers.idPers):
raise ValueError("ID already exists: " +str(i.idPers))
self.__persList.append(pers)
I use this function in my Controller, as follows:
def createPerson(self, idPers, nume, telefon, adresa):
'''
Creates a person as long as the data introduced is correct
'''
i = Persoana(idPers, nume, telefon, adresa)
self.__valiPers.validare(i) //checks if the data I put in is alright(name doesn't contain numbers etc.)
self.__repo.save(i)
I use inheritance to make a FileRepository file, which inherits methods/parameters from the initial Repository file.
class AgendaFileRepository(AgendaRepository):
def __init__(self, file_name):
self.__file_name = file_name
AgendaRepository.__init__(self)
self.__load_from_file()
def __write_to_file(self):
l=self.get_persoane()
f=open(self.__file_name,"w")
for person in l:
f.write(repr(person)+'\n')
f.close()
def __load_from_file(self):
try:
f=open(self.__file_name,"r")
linie=f.readline().rstrip('\n')
while linie!="":
attr=linie.split(" ")
a=Persoana(attr[0], attr[1], attr[2],attr[3])
AgendaRepository.save(self, a)
linie=f.readline().rstrip('\n')
f.close()
except IOError:
raise IOError("File cannot be open")
except ValueError:
raise ValueError("Can't read from file")
except IndexError:
raise IndexError("Can't read from file")
def save(self, pers):
AgendaRepository.save(self, pers)
self.__write_to_file()
The function that I have in my UI folder is:
def addPerson(self):
'''
Adds a person to the file, returns value error if the data isn't valid
'''
name=input("Name: ")
telnumber = input("Tel number: ")
adress = input("Adress: ")
idPers=int(input("Id:"))
try:
self.__ctrl.createPerson(idPers, name, telnumber, adress)
print("Added person successfully")
except ValueError as ex:
print(str(ex))
Anyway, I realise that this exercise can be done way easier/faster, but the professor wants to make us understand OOP I guess. Anyway, I can write stuff to the file, but it doesn't check if the ID of the person is there already, unless I added the person during program execution. I can't delete/modify people either, unless they have been added during program execution.
Been busting my brains for like 2 hours now with this, checking every line and everything, but I can't seem to crack it. What am I doing wrong?
Alright, I found the issue. The problem was that the type of i.idPers and pers.idPers wasn't the same. One was a string and the other was an integer, and the equality between them never happened, thus the program never entered the IF loop.
So, finally I'm getting to the end of LPTHW, and I'm creating my own text adventure type of game.
I want to incorporate a save function to the game (probably by using file write). Also, the game can give you hints based on your location in the game. What I basically need is following:
There will be lots of prompts for user input (raw_input) in while loops. I want to be able to type SAVE or HINT any time to trigger a function. How do I do this so I don't have to create the same conditional every time? (for example elif action == "HINT": print "...")
Is there a way to create some global expressions so that every time they're typed in the prompt, I can act on them? I will create a module with a dictionary that will reference a certain hint when the player is present in a certain location. I just want to avoid putting the same conditionals all over the place.
If you separate the input into a function, you can pass a hint and access save easily:
def user_input(prompt, hint):
while True:
ui = raw_input(prompt)
if ui.lower() == "hint":
print hint
elif ui.lower() == "save":
save()
else:
return ui
You could also add checking here that the user stays within specific choices (an additional argument), deal with any errors and only ever return valid input.
you should probably use a dictionary
def do_save(*args,**kwargs):
print "SAVE!"
def do_hint(*args,**kwargs):
print "HINT!"
def do_quit(*args,**kwargs):
print "OK EXIT!"
global_actions = {'SAVE':do_save,
'HINT':do_hint,
'QUIT':do_quit}
def go_north(*args,**kwargs):
print "You Go North"
def go_east(*args,**kwargs):
print "you go east"
def make_choice(prompt="ENTER COMMAND:",actions={},context_info={}):
choice = raw_input(prompt)
fn = actions.get(choice.upper(),lambda *a,**kw:sys.stdout.write("UNKOWN CHOICE!"))
return fn(some_context=context_info)
local_actions = {"NORTH":go_north,"EAST":go_east}
player_actions = dict(global_actions.items() + local_actions.items())
print "From Here You Can Go [North] or [East]"
result = make_choice(actions=player_actions,
context_info={"location":"narnia","player_level":5})
I don't know about the save feature but for hint you could just have;
If raw_input == hint:
print "whatever you want here"
Or if you need the hint to be different depending on your position you could have a variable for what the hint for that room is and have it update each time you enter a new room then have:
if raw_input == "hint":
print hintvariable
If this doesn't work then sorry, I'm new.