Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

Reply
 
Thread Tools Display Modes
Old Nov 2nd, 2005, 10:37 PM   #1
Gunman
Programmer
 
Gunman's Avatar
 
Join Date: Oct 2005
Posts: 56
Rep Power: 3 Gunman is on a distinguished road
Comments?

Hey i just wrote my first phonebook but its in a mess and i would like to clear some doubts..

This is the full code:
#This is the phonebook
#Usernmae , password
def options():
    print "1.Print phone number"
    print "2.Add a phone number"
    print "3.Remove a phone number"
    print "4.Lookup a phone number"
    print "5.Edit a name" 
    print "6.Quit"


menu_choice = 0
numbers = {}

print options()

menu_choice = input("Pick an option from the menu(1-5) : ")

while menu_choice != 6:
    if menu_choice == 1:
        print "Telephone numbers:"
        for x in numbers.keys():
            print "Name: ",x,"\tNumber: ",numbers[x]
            print
    elif menu_choice == 2:
        name = raw_input("Enter the name you wanna add : ")
        number = input("Enter number : ")
        numbers[name] = number
        options()
        menu_choice = input("Pick an options from the menu(1-5) : ")
    elif menu_choice ==3:
        del_name = raw_input("Enter the name you would like to del : ")
        if numbers.has_key(del_name):
            del numbers[del_name]
        options()
        menu_choice = input("Pick an options from the menu(1-5) : ")
    elif menu_choice ==4:
        look_name = raw_input("Enter the number : ")
        if numbers.has_key(look_name):
            print numbers[look_name]
        options()
        menu_choice = input("Pick an options from the menu(1-5) : ")
    elif menu_choice ==5:
        change_name = raw_input("Whats the name you would like to change : ")
        for change_name in numbers.keys():
            new_name = raw_input("New name : ")
            numbers[change_name] = new_name
        else:
            print "Name cannot be found"
    elif menu_choice!=6:
        options()
        menu_choice = input("Pick an options from the menu(1-5) : ")

The printing the dict part i copied frm a site and don't really understand this part of the code:

for x in numbers.keys():
            print "Name: ",x,"\tNumber: ",numbers[x]
Can someone explain to me the use of the "x" here ..

My next problem is the edit function . Even though it doesn't print an error it goes to the else option even if the name is existant in the dict . Basically it doesn't work.. :o

This is the code :
for change_name in numbers.keys():
            new_name = raw_input("New name : ")
            numbers[change_name] = new_name  # <---I know this is worng 
        else:                                              #but don't know any other way
            print "Name cannot be found"

Ya thats all the rest all seem to be okay and thanx for helping .=))))
Gunman is offline   Reply With Quote
Old Nov 2nd, 2005, 11:22 PM   #2
Sane
Programming Guru
 
Sane's Avatar
 
Join Date: Apr 2005
Location: Waterloo, Ontario
Posts: 1,869
Rep Power: 5 Sane will become famous soon enough
Send a message via MSN to Sane
for x in numbers.keys():
            print "Name: ",x,"\tNumber: ",numbers[x]

numbers.keys() is a list of items. So assigning it to a for loop, where the identifier is x, the x then equals every item individually from the list one at a time.

So like

list = ['one', 'two', 'three']

for x in list: print x

will ouput:
one
two
three





This is the code :
for change_name in numbers.keys():
            new_name = raw_input("New name : ")
            numbers[change_name] = new_name  # <---I know this is worng 
        else:                                              #but don't know any other way
            print "Name cannot be found"

I don't see what's wrong with this. Have you added any items to the list yet?
Sane is offline   Reply With Quote
Old Nov 2nd, 2005, 11:29 PM   #3
Gunman
Programmer
 
Gunman's Avatar
 
Join Date: Oct 2005
Posts: 56
Rep Power: 3 Gunman is on a distinguished road
Ya i did . But isn't this code supposed to assign the new_name to change_name ?So the new_name becomes change_name's number .But this isn't what i want to do ..I would like to edit the name ..Correct me if i'm wrong . And it prints "Name cannot be found even though the name exists . Thanx for helping =)

for change_name in numbers.keys():
            new_name = raw_input("New name : ")
            numbers[change_name] = new_name  # <---I know this is worng 
        else:                                              #but don't know any other way
            print "Name cannot be found"
Gunman is offline   Reply With Quote
Old Nov 2nd, 2005, 11:36 PM   #4
Sane
Programming Guru
 
Sane's Avatar
 
Join Date: Apr 2005
Location: Waterloo, Ontario
Posts: 1,869
Rep Power: 5 Sane will become famous soon enough
Send a message via MSN to Sane
What this does is prompts you to change the value of every item in the list one at a time.

But I don't understand why you have that else block there. Since there's no way a name couldn't be found since it's controlled in the for loop.

If you want to edit the name of something you would go something like:

change_name = raw_input("Which name would you like to change? ")
new_name = raw_input("New Value? ")
numbers[change_name] = new_name
Sane is offline   Reply With Quote
Old Nov 2nd, 2005, 11:40 PM   #5
Gunman
Programmer
 
Gunman's Avatar
 
Join Date: Oct 2005
Posts: 56
Rep Power: 3 Gunman is on a distinguished road
Thanx =)
Gunman is offline   Reply With Quote
Old Nov 3rd, 2005, 8:07 PM   #6
hydroxide
Programmer
 
Join Date: Apr 2005
Posts: 73
Rep Power: 4 hydroxide is on a distinguished road
This is not exactly how I'd code it, but it's cleaner ;-)

# Functions can return values - if you're repeating code you should
# DEFINITELY use one. (repeated prints are somewhat bad but they 
# can stand for the moment)
#
# Always use raw_input() - input() is fragile and insecure.
def get_option():
    print
    print "1.Print phone number"
    print "2.Add a phone number"
    print "3.Remove a phone number"
    print "4.Lookup a phone number"
    print "5.Edit a name" 
    print "6.Quit"
    return raw_input("Pick an option from the menu(1-5) : ")

# Even when chunks of code aren't repeated, using a function can clarify
# your code by pulling out units of functionality.
# In Python, you almost never need to explicitly index
def print_number():
    print "Telephone numbers:"
    for name, number in numbers.items():
        print "    Name: %s\tNumber: %s" %(name, number)

def add_number():
    name = raw_input("Enter the name you wanna add : ")
    number = raw_input("Enter number : ")
    numbers[name] = number

# You can just use "obj in container" rather than "container.has_key(obj)"
# It works for lists as well as dicts.
def remove_number():
    del_name = raw_input("Enter the name you would like to del : ")
    if del_name in numbers:
        del numbers[del_name]

def lookup_number():
    look_name = raw_input("Enter the name : ")
    if look_name in numbers:
        print numbers[look_name]

# You want to replace the old name with the new name.
# This means that the old name needs to be removed.
# dict.pop() removes an object from the dict and returns it.
# the object that's returned is then allocated to new_name
def edit_name():
    change_name = raw_input("Whats the name you would like to change : ")
    if change_name in numbers:
        new_name = raw_input("New name : ")
        numbers[new_name] = numbers.pop(change_name)
    else:
        print "Name cannot be found"
    
numbers = {}

# Python has first class functions - this means that a function can be
# treated like any other object. You can thus put them in a lookup table
mytable = { "1": print_number,
            "2": add_number,
            "3": remove_number,
            "4": lookup_number,
            "5": edit_name }

# It's cleaner to loop infinitely and only have ONE call to get_option.
while True:
    menu_choice = get_option()

    # try to lookup the menu choice in the lookup table
    try:
        func = mytable[menu_choice]
    # If the lookup fails
    except KeyError:
        # break out of the infinite loop if choice is "6"
        if menu_choice == "6":
            break
        # Otherwise print an error message
        else:
            print "Incorrect value - must use 1 to 6 only."
    # the else clause will ONLY be called if no exceptions were raised
    else:
        # We can now call the function that we looked up
        func()
--OH.
hydroxide is offline   Reply With Quote
Old Nov 4th, 2005, 12:08 AM   #7
Gunman
Programmer
 
Gunman's Avatar
 
Join Date: Oct 2005
Posts: 56
Rep Power: 3 Gunman is on a distinguished road
Wow..Thanx for your help , I will try to code like that next time . Thanx again..=))))
Gunman is offline   Reply With Quote
Old Nov 4th, 2005, 1:53 AM   #8
Arevos
Programming Guru
 
Arevos's Avatar
 
Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 5 Arevos is on a distinguished road
Great code, hydroxide, though I'd have used sys.exit for function number 6, myself. That's probably entirely personal preference, though
import sys

mytable = { "1": print_number,
            "2": add_number,
            "3": remove_number,
            "4": lookup_number,
            "5": edit_name,
            "6": sys.exit }

# It's cleaner to loop infinitely and only have ONE call to get_option.
while True:
    # try to lookup the menu choice in the lookup table
    try:
        mytable[get_option()]()
    # If the lookup fails
    except KeyError:
        print "Incorrect value - must use 1 to 6 only."
Arevos is offline   Reply With Quote
Old Nov 4th, 2005, 2:34 AM   #9
bl00dninja
Programming Guru
 
bl00dninja's Avatar
 
Join Date: Oct 2004
Location: namespace std
Posts: 1,246
Rep Power: 5 bl00dninja is on a distinguished road
yeah, what they said...

as soon as i saw a bunch of elif's i thought "switch" (a C construct, i guess python calls it something else?) but yeah, a lot of problems have been worked out already and there are a lot of tools to help you focus more on the problem than on copying and pasting. (which is still awesome) :p
__________________
i put on my robe and wizard hat...

Have you ever heard of Plato, Aristotle, Socrates?...Morons.
bl00dninja is offline   Reply With Quote
Old Nov 4th, 2005, 3:03 AM   #10
Gunman
Programmer
 
Gunman's Avatar
 
Join Date: Oct 2005
Posts: 56
Rep Power: 3 Gunman is on a distinguished road
Whoo..Thanx for your help Arevos , but i haven't covered module much so can't really inderstand how it works . And i re coded the phonebook quite similars to hydroxide's(Thanx hydroxide!), but ohwell learned quite a number of things..=)) And this is the finished phonebook:

#This is a phonebook

number = {}

def menu():
    print "1.Print the phone book"
    print "2.Add a number"
    print "3.Delete a number"
    print "4.Edit a number"
    print "5.Lookup for a number"
    print "6.Quit"
    return raw_input("Pick an option(1-6) frm the menu : ")

def print_number():
    print "Telephone number:"
    if len(number) > 0:
        for name in number.keys():
            print "   Name : ",name ,"\tNumber : ",number[name]
            print "-"*48
    else:
        print "You have no numbers in your phonebook"
        print "-"*48
def add_number():
    print '+------------------Add number---------------------+'
    print
    add_name = raw_input("Name : ")
    add_number = raw_input("Number : ")
    number.setdefault(add_name,add_number)
    print add_name," has been added."
    print "-"*48
    

def del_number():
    print "+-----------------Del number----------------------+"
    print
    for name in number:
        print " Name : ",name,"\tNumber : ",number[name]
        print
        print "Pick a name frm the list to delete"
        del_name = raw_input("Name : ")
    if number.has_key(del_name):
        del number[del_name]
        print del_name," has been deleted."
        menu()
    else:
        print "Choose a name from the phonebook"
        del_name = raw_input("Name : ")
        menu()

def edit_number():
    print "+---------------Edit a number---------------------+"
    print
    for name in number.keys():
        print "Name : ",name,"\tNumber : ",number[name]
    edit_name = raw_input("Name : ")
    if number.has_key(edit_name) == 1:
        new_name = raw_input("What would be the new name : ")
        number[new_name] = number.pop(edit_name)
        print edit_name," has been chaged to ",new_name
        menu()
    else:
        edit_name = raw_input("Pick a name from the list : " )

def lookup_number():
    print "+-------------Lookup for a number----------------+"
    print
    lookup_name = raw_input("Whats the name your looking for : " )
    if number.has_key(lookup_name) == 1:
        for lookup_name in number.keys():
            print "Name : ",lookup_name," \t Number : ",number[lookup_name]
    else:
        print " The name isn't in your phonebook"




mytable = { "1" : print_number,
            "2" : add_number,
            "3" : del_number,
            "4" : edit_number,
            "5" : lookup_number,
            }

while 1==1:
    menu_choice = menu()

    try:
        func=mytable[menu_choice]
    except KeyError:
        if menu_choice == "6":
            break
        else:
            print "Pick a option frm (1-6) "
    else:
        func()
Gunman is offline   Reply With Quote
Reply

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 1:26 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC