y="Peter Email: peter#rp.com Phone: 91291212"
z="Alan Email: alan#rp.com Phone: 98884444"
w="John Email: john#rp.com Phone: 93335555"
add_book=str(y) ,"" + str(z) ,"" + str(w)
**I am trying to add a contact into my address book but I am not sure how to add the string "details" into the add_book. I also found that I cannot use append because its a tuple.
details = raw_input("Enter name in the following format: name Email: Phone:")
print "New contact added"
print details
if details in add_book:
o=add_book+details
print "contact found"
print details
print add_book
address_book = {}
address_book['Alan'] = ['alan#rp.com, 91234567']#this is what I was supposed to do:
#but when I print it out, the output I get is:
{'Alan': ['alan#rp.com, 91234567']} #but I want to remove the '' and {}
I am still an amateur in programming with python so I really need all the help I can get, thanks:)!!
A simple fix would be to use a list instead of a tuple. You can do this by changing your initialization of add_book from:
add_book=str(y) ,"" + str(z) ,"" + str(w)
to:
add_book = [y,z,w]
#No need to call str() every time because your data are already strings
However, wouldn't it make more sense to organize your data as a list of dictionaries? For example:
contacts = ["Peter", "Alan", "John"]
addr_book = [len(contacts)]
for i in range(len(contacts)):
contact = contacts[i]
email= raw_input(contact+"'s email: ")
phone= raw_input(contact+"'s phone: ")
addr_book[i] = {'name':contact, 'email':email, 'phone':phone}
FURTHERMORE:
If I understood your question correctly, you have specific requirements as to how the output of your program should look. If you use the above data format, you can create whatever output you like. for example, this code
def printContact(contact):
print contact['name']+': ['+contact[email]+','+contact[phone]+']'
will output something like:
Alan: [alan#email.com,555-555-5555]
Of course you can change it however you like.
firstly [] is a list. a tuple is (,);
so what you want is
address_book['Alan'] = ('alan#rp.com', '91234567')
But this seems quite odd. What i would do is create a class
class Contact(object):
name = "Contact Name"
email = "Contact Email"
ph_number = "00000000"
def __str__(self):
return "%S: %s, %s" % (self.name, self.email, self.ph_number)
then
address_book = []
contact_alan = Contact()
contact_alan.name = "Alan"
contact_alan.email = "alan#rp.com"
contact_alan.ph_number = "91234567"
print contact
(not next to a machine with python so it might be slightly wrong. Will test it when i can get to one.)
EDIT:- as Paul pointed out in his comment:
class Contact(object):
def __init__(self, name, email, ph_number):
self.name = name
self.email = email
self.ph_number = ph_number
contact_alan = Contact(name="Alan", email = "alan#rp.com", ph_number="91234567")
Related
I've written the following code:
class User:
def __init__(self, first_name, last_name, gender, location):
self.first_name = first_name
self.last_name = last_name
self.gender = gender
self.location = location
def describe_user(self):
print(f"User {self.first_name} {self.last_name} is a "
f"{self.gender} from {self.location}")
def greet_user(self):
print(f"Hello there {self.first_name}, you come from the "
f"{self.last_name} family. You currently reside in "
f"{self.location}. Oh, I forgot to mention that you're "
f"a {self.gender}. Have a nice day!")
This works, but I don't think it looks very clean.
The way I initially tried to accomplish this, which seemed most natural to me was like this:
def describe_user(self):
print(f"User {self.first_name} {self.last_name} is a
{self.gender} from {self.location}")
But unfortunately that didn't work. Is there a better way to do this?
I think what you have looks fairly clean, but for an alternative, you could add format-able strings together and format them in a separate step if you'd like, really this comes down to a matter of opinion:
class User:
def __init__(self, first_name, last_name, gender, location):
self.first_name = first_name
self.last_name = last_name
self.gender = gender
self.location = location
def greet_user(self):
output = ("Hello there {}, you come from the " +
"{} family. You currently reside in " +
"{}. Oh, I forgot to mention that you're " +
"a {}. Have a nice day!")
output = output.format(self.first_name, self.last_name,
self.location, self.gender)
print(output)
first_name = 'Bob'
last_name = 'Joe'
gender = 'Robot'
location = 'Jupiter'
x = User(first_name, last_name, gender, location)
x.greet_user()
# Output:
Hello there Bob, you come from the Joe family. You currently reside in Jupiter. Oh, I forgot to mention that you're a Robot. Have a nice day!
New to Python and am working on a task my friend gave me. The objective for this portion is to find user information that was previously added to a dictionary. I am trying to find a way that if the user is searching for a particular user, only that user's info will be returned. So far this is the code I have for this portion of the project:
selection = input('Please select an option 1 - 4:\t')
if selection == '1':
print('Add user - Enter the information for the new user:\t')
first_name = input('First name:\t')
last_name = input('Last name:\t')
hair_color = input('Hair color:\t')
eye_color = input('Eye color:\t')
age = input('Age:\t')
user_info = {}
user_info['First name'] = first_name
user_info['Last name'] = last_name
user_info['Hair color'] = hair_color
user_info['Eye color'] = eye_color
user_info['Age'] = age
Skipping code for sake of space on post
if selection == '3':
print('\nChoose how to look up a user')
print('1 - First name')
print('2 - Last name')
print('3 - Hair color')
print('4 - Eye color')
print('5 - Age')
print('6 - Exit to main menu\n')
search_option = input('Enter option:\t')
if search_option == '1' or search_option == 'First name' or search_option == 'first name':
input('Enter the first name of the user you are looking for:\t')
Any and all help is much appreciated!!
Depending on your project, using a dictionary might be difficult in the future. Let's not go down a dark road. Take a moment and assess the situation.
We know that we want to collect some information from the user, such as:
first name
last name
hair color
...etc
We also want to store the User object to retrieve later based on a particular ID. In your code, you search for other users based on attributes, but what if two or more users share the same attribute, for example, first name?
What your asking for are attributes associated with a particular user. Why not create a class called User?
class User:
def __init__(self, id, first_name, last_name, hair_color):
# You can also check if any attributes are blank and throw an exception.
self._id = id
self._first_name = first_name
self._last_name = last_name
self._hair_color = hair_color
# add more attributes if you want
# a getter to access the self._id property
#property
def id(self):
return self._id
def __str__(self):
return f"ID: {self._id} Name: {self._first_name} {self._last_name}
Hair Color: {self._hair_color}"
In your main function, you can now ask for the user details and store them in a class which you can append to a List.
from User import User
def ask_for_input(question):
answer = input(question)
return answer.strip() # strip any user created white space.
def main():
# Store our users
users = []
# Collect the user info
id = ask_for_input(question = "ID ")
first_name = ask_for_input(question = "First Name ")
last_name = ask_for_input(question = "Last Name ")
hair_color= ask_for_input(question = "Hair Color ")
# Create our user object
user = User(id=id, first_name=first_name, last_name=last_name, hair_color=hair_color)
print(user)
# accessing the id property
print(user.id)
users.append(user)
if __name__ == '__main__':
main()
You may also want to improve on the above class, for example, error checking, and adding type hints to make the code more readable.
If you're just storing the user information, a data class might be more appropriate.
If your looking for a broad suggestion, you could use mongob, it makes a great way to store data to be retrieved later, here is an example i built for another question. The prerequisites is that you'd have to get the mongod server running before you can use the pip install:
Here is an example of how to get it going and how easy it easy to retrieve data like yours
pip3 install pymongo
from pymongo import MongoClient
client = MongoClient()
client = MongoClient('localhost', 27017)
db = client.pymongo_test
posts = db.posts
post_data = {
'title': 'The title of this post',
'content': 'pymongo is awesome',
'author': 'Bill'
}
result = posts.insert_one(post_data)
print('One post: {0}'.format(result.inserted_id))
bills_post = posts.find_one({'author': 'Bill'})
print(bills_post)
#One post: 5dc61c0cc2b75ebc458da31f
#{'_id': ObjectId('5dc61bf76071bde943ca262b'), 'title': 'The title of this post', 'content': 'pymongo is awesome', 'author': 'Bill'}
I am writing an email application to send mass emails. In the body of the email I want to insert the first name from a list of names. But I can't seem to figure out why this code isn't working. Any suggestions are most appreciated.
first_name = " "
body = """\
Dear {},
Here is new email.
Thanks.
Mike """.format(first_name)
def send_test_email(body):
first_name = 'mike'
print(body)
send_test_email(body)
Output:
Dear ,
Here is new email.
Thanks.
Mike
You have already assigned what body is. So even if you change value of parameter (first_name) in format later, it does not affect the original body.
first_name = " "
body = """\
Dear {},
Here is new email.
Thanks.
Mike """
def send_test_email(body):
first_name = 'mike'
print(body.format(first_name))
send_test_email(body)
# Dear mike,
# Here is new email.
# Thanks.
# Mike
so I'm making an agenda.
The attribute of agenda that manages the dictionary is : self.ContactList = {}
Inside this I have the telephone number as key for a contact (which is a class).
The Contact class has an attribute called telephone and other ones including the contact name.
I want a function that lists the contacts in the agenda, however I wanna list them by alphabetical order of the Contacts it contains.
Right now I'm using this to print the contacts (already have overriden the ____str____ of the contact class to allow this):
def listcontacts(self, agenda):
print("Contact List\n")
for tel, contact in agenda.ContactList.items():
print(contact,"\n"*2)
How to sort self.ContactList by the contact's attribute "name"?
EDIT: The contact class is as follows
class Contact:
def __init__(self, name, adress, zipcode, telephone):
self.name = name
self.adress = adress
self.zipcode = zipcode
self.telephone = telephone
def __str__(self):
return ( "Name: " + self.name + "\nAdress: " + self.adress + "\nZipCode: " + self.zipcode
+ "\nTelephone: " + self.telephone)
If you want to sort a list, use the sorted() function. If you want the sort to use an interesting ordering criterion, use the key= keyword:
for tel, contact in sorted(agenda.ContactList.items(), key=lambda x: x[1].name):
In python xmpp module, I'm able to retrieve the nickname of any contacts as follows:
self.connection.auth(userJid.getNode(), self.password)
self.roster = self.connection.getRoster()
name = self.roster.getName(buddyJid)
..where buddyJid is of the form user#gmail.com.
Now, I need to retrieve the nickname of the user who authenticates the connection (userJid). I cannot find the name using the above method.
Which method can I use retrieve the name of the current user?
This information is not in the roster. You will need to query the clients individually and get their vCard by sending this IQ :
<iq from='stpeter#jabber.org/roundabout'
id='v1'
type='get'>
<vCard xmlns='vcard-temp'/>
</iq>
Thank you nicholas_o, this is a sample function I put together based your suggestion. (The XML logic isn't ideal, but it was sufficient for the simple task I needed this for)
def vcard(disp, jid):
msg = xmpp.protocol.Iq()
msg.setType('get')
msg.setTo(jid)
qc = msg.addChild('vCard')
qc.setAttr('xmlns', 'vcard-temp')
rep = disp.SendAndWaitForResponse(msg)
# to see what other fields are available in the XML output:
# print rep
userid=fname=lname=title=department=region=None
for i in rep.getChildren():
for j in i.getChildren():
if j.getName() == "TITLE":
title = j.getData().encode('utf-8')
for k in j.getChildren():
if k.getName() == "GIVEN":
fname = k.getData().encode('utf-8')
if k.getName() == "FAMILY":
lname = k.getData().encode('utf-8')
if k.getName() == "ORGUNIT":
department = k.getData().encode('utf-8')
if k.getName() == "REGION":
region = k.getData().encode('utf-8')
return fname, lname, title, department, region