Quantcast

Advise of programming one of my first programs

classic Classic list List threaded Threaded
20 messages Options
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate
star

Advise of programming one of my first programs

Anatoli Hristov
Hi guys just wanted to share one of my first programs. Could you please tell me, do I use a right logic ?
It works fine what I wanted to do, but is it writen in the right way? My next step is to make it write the changes of the dictionary on the file :)


## DB
tbook = {'goodie':['Christian','Van Eckel','Bruxelles','Forest','02 344 33 33','This is a test note :)'],
         'osvaldo':['Osvaldo','Rios','Liege','Centrum','023758832',''],
         'ronaldo':['Diego','Aspanda','Brussels','Vorst','03 443 23 23','']}

## Edit selected nickname
def edit():
    sb = tbook[select]
    fn = raw_input('New name for ' + sb[0] + ' : ')
    sb[0] = fn
    ln = raw_input('New name for ' + sb[1] + ' : ')
    sb[1] = ln
    raw_input('\n\n\nPress <Enter> to return')
    details()


## Details of nickname
def details():
        sb = tbook[select]
        print 'Nickname: ', select, ' is selected\n'
        print 'First name:\t', sb[0], '\n'
        print 'Last name:\t', sb[1], '\n'
        print 'Country:\t', sb[2], '\n'
        print 'City:\t\t', sb[3], '\n'
        print 'Phone number:\t',sb[4], '\n'
        print 'Memos:\n'
        print sb[5]

        print '\n\n(E)dit\n\n'
        print '(B)ack to phonebook list\n\n'
        menu = raw_input('What you wana do? ')
        if menu == 'e':
                edit()
        if menu == 'b':
            listpb()

            
## Select nickname
def selectm():
    global select
    select = raw_input('Type nickname and press <Enter>: ')
    if select == '':
        listpb()
    if select in tbook:
        details()
    else:
        listpb()

## List all contacts        
def listpb():
    print '_' *45, ' Phonebook ', '_' *45,'\n\n\n'

    print 'Nick\t\tF.Name\t\tL.Name\t\tCity\t\t\tRegion\t\tTel'
    print '_' * 105,'\n','\t' * 13
    for val in tbook.keys():
            print val, '\t\t', tbook[val][0], '\t', tbook[val][1], '\t', tbook[val][2], '\t\t', tbook[val][3], '\t\t', tbook[val][4],'\t\t\n'
    print '_'*105,'\n\n'
    selectm()

## Call list names  
listpb()

                
        
Thanks a lot

Anatoli


--
http://mail.python.org/mailman/listinfo/python-list
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate
star

RE: Advise of programming one of my first programs

Prasad, Ramit-2

> Hi guys just wanted to share one of my first programs. Could you please
> tell me, do I use a right logic ?
> It works fine what I wanted to do, but is it writen in the right way? My
> next step is to make it write the changes of the dictionary on the file :)
>

When you do get that far, you should look at the pickle library.
It is amazing how easy it is to store data with Python.

>
> ## DB
> tbook = {'goodie':['Christian','Van Eckel','Bruxelles','Forest','02 344 33
> 33','This is a test note :)'],
>          'osvaldo':['Osvaldo','Rios','Liege','Centrum','023758832',''],
>          'ronaldo':['Diego','Aspanda','Brussels','Vorst','03 443 23
> 23','']}
>
> ## Edit selected nickname
> def edit():
>     sb = tbook[select]
>     fn = raw_input('New name for ' + sb[0] + ' : ')
>     sb[0] = fn
>     ln = raw_input('New name for ' + sb[1] + ' : ')
>     sb[1] = ln
>     raw_input('\n\n\nPress <Enter> to return')
>     details()
>
>
> ## Details of nickname
> def details():
>         sb = tbook[select]
>         print 'Nickname: ', select, ' is selected\n'
>         print 'First name:\t', sb[0], '\n'
>         print 'Last name:\t', sb[1], '\n'
>         print 'Country:\t', sb[2], '\n'
>         print 'City:\t\t', sb[3], '\n'
>         print 'Phone number:\t',sb[4], '\n'
>         print 'Memos:\n'
>         print sb[5]
>
>         print '\n\n(E)dit\n\n'
>         print '(B)ack to phonebook list\n\n'
>         menu = raw_input('What you wana do? ')
>         if menu == 'e':
>                 edit()
>         if menu == 'b':
>             listpb()
>

Minor nitpick, but what if the user types 'B' or 'E' like in
your printed menu?

>
> ## Select nickname
> def selectm():
>     global select
>     select = raw_input('Type nickname and press <Enter>: ')
>     if select == '':
>         listpb()
>     if select in tbook:
>         details()
>     else:
>         listpb()


Remove all global variables when your program starts to work.
Instead pass them as arguments and return them from functions.
So do 'details( select )' instead of 'details()' and then in
details, you would do edit( select ).

>
> ## List all contacts
> def listpb():
>     print '_' *45, ' Phonebook ', '_' *45,'\n\n\n'
>
>     print 'Nick\t\tF.Name\t\tL.Name\t\tCity\t\t\tRegion\t\tTel'
>     print '_' * 105,'\n','\t' * 13
>     for val in tbook.keys():
>             print val, '\t\t', tbook[val][0], '\t', tbook[val][1], '\t',
> tbook[val][2], '\t\t', tbook[val][3], '\t\t', tbook[val][4],'\t\t\n'
>     print '_'*105,'\n\n'
>     selectm()
>
> ## Call list names
> listpb()

if __name__ == "__main__":
    listpb()

This way you can import the module and not run it on import; it is
useful when you start wanting to reuse functions from a different
project. It is better than copy-pasting functions everywhere because
when you improve the function all the programs will pick it up. Otherwise
you will have to go back to each pasted function and pick it up.


A few items I would work to improve:
1. Remove global variables (already mentioned above)

2. You should separate any menu / navigation from your application
code. details() should only print the details and not take the
next menu choice. You probably want 2 separate menu functions.
One that returns a 'select'-ed book and one that returns next choice.
This will also help you when you implement my next point.

3. You should also change the structure of your program to loop
instead of calling listpb each time you want to restart. It is a
much better practice and while it will not affect this program
unless you do not exit for 10s or 100s of thousands of details but if
you write something that *does* navigate that many times it can crash.
Looping is probably your next programming lesson anyway :)

4. This is more of a side note but instead of using \t\t all the
time, you would be better off  learning to use the string formatting
operations. It is a little more effort to learn, but tends to be
a lot more reliable on  different systems (and with different
data trying to be printed) than manually trying to align everything.

http://docs.python.org/library/string.html#format-string-syntax


Keep on working, you have made a good start and now it is time
to refactor (programming equivalent of rewriting an essay) and
make everything better!

Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

--


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
--
http://mail.python.org/mailman/listinfo/python-list
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate
star

Re: Advise of programming one of my first programs

Anatoli Hristov
Thank you Ramit for your advice`s. I`m reading a book ( Learning Python, Second Edition ) by Mark Lutz and David Ascher and now I just finished the Basic Function lesson :) I will keep in mind what you have advised me, but will implement it later when I have more experience with the book, because I don`t understand exactly what you mean by doing all dose changes :)
By the way I dont know why your mail was in my junk I just saw it.

And here is my last code I did for the phonebook:
Thanks

####### CODE #########

fileread = open('myfile.txt','r')
tbook = eval(fileread.read())
fileread.close()


## Edit selected nickname
def edit():
    sb = tbook[select]
    fn = raw_input('New name for ' + sb[0] + ' : ')
    sb[0] = fn
    ln = raw_input('New name for ' + sb[1] + ' : ')
    sb[1] = ln
    filewrite = open('myfile.txt','w')
    filewrite.write(str(tbook))
    filewrite.close()
    raw_input('\n\n\nPress <Enter> to return')
    details()


## Details of nickname
def details():
        sb = tbook[select]
        print 'Nickname: ', select, ' is selected\n'
        print 'First name:\t', sb[0], '\n'
        print 'Last name:\t', sb[1], '\n'
        print 'Country:\t', sb[2], '\n'
        print 'City:\t\t', sb[3], '\n'
        print 'Phone number:\t',sb[4], '\n'
        print 'Memos:\n'
        print sb[5]

        print '\n\n(E)dit\n\n'
        print '(B)ack to phonebook list\n\n'
        menu = raw_input('What you wana do? ')
        if menu == 'e' or 'E':
                edit()
        if menu == 'b' or 'B':
            listpb()

            
## Select nickname
def selectm():
    global select
    select = raw_input('Type nickname and press <Enter>: ')
    if select == '':
        listpb()
    if select in tbook:
        details()
    else:
        listpb()

## List all contacts        
def listpb():
    print '_' *45, ' Phonebook ', '_' *45,'\n\n\n'

    print 'Nick\t\tF.Name\t\tL.Name\t\tCity\t\t\tRegion\t\tTel'
    print '_' * 105,'\n','\t' * 13
    for val in tbook.keys():
            print val, '\t\t', tbook[val][0], '\t', tbook[val][1], '\t', tbook[val][2], '\t\t', tbook[val][3], '\t\t', tbook[val][4],'\t\t\n'
    print '_'*105,'\n\n'
    selectm()

## Call list names  
listpb()

                
        


On Tue, Mar 27, 2012 at 12:40 AM, Prasad, Ramit <[hidden email]> wrote:

> Hi guys just wanted to share one of my first programs. Could you please
> tell me, do I use a right logic ?
> It works fine what I wanted to do, but is it writen in the right way? My
> next step is to make it write the changes of the dictionary on the file :)
>

When you do get that far, you should look at the pickle library.
It is amazing how easy it is to store data with Python.

>
> ## DB
> tbook = {'goodie':['Christian','Van Eckel','Bruxelles','Forest','02 344 33
> 33','This is a test note :)'],
>          'osvaldo':['Osvaldo','Rios','Liege','Centrum','023758832',''],
>          'ronaldo':['Diego','Aspanda','Brussels','Vorst','03 443 23
> 23','']}
>
> ## Edit selected nickname
> def edit():
>     sb = tbook[select]
>     fn = raw_input('New name for ' + sb[0] + ' : ')
>     sb[0] = fn
>     ln = raw_input('New name for ' + sb[1] + ' : ')
>     sb[1] = ln
>     raw_input('\n\n\nPress <Enter> to return')
>     details()
>
>
> ## Details of nickname
> def details():
>         sb = tbook[select]
>         print 'Nickname: ', select, ' is selected\n'
>         print 'First name:\t', sb[0], '\n'
>         print 'Last name:\t', sb[1], '\n'
>         print 'Country:\t', sb[2], '\n'
>         print 'City:\t\t', sb[3], '\n'
>         print 'Phone number:\t',sb[4], '\n'
>         print 'Memos:\n'
>         print sb[5]
>
>         print '\n\n(E)dit\n\n'
>         print '(B)ack to phonebook list\n\n'
>         menu = raw_input('What you wana do? ')
>         if menu == 'e':
>                 edit()
>         if menu == 'b':
>             listpb()
>

Minor nitpick, but what if the user types 'B' or 'E' like in
your printed menu?

>
> ## Select nickname
> def selectm():
>     global select
>     select = raw_input('Type nickname and press <Enter>: ')
>     if select == '':
>         listpb()
>     if select in tbook:
>         details()
>     else:
>         listpb()


Remove all global variables when your program starts to work.
Instead pass them as arguments and return them from functions.
So do 'details( select )' instead of 'details()' and then in
details, you would do edit( select ).
>
> ## List all contacts
> def listpb():
>     print '_' *45, ' Phonebook ', '_' *45,'\n\n\n'
>
>     print 'Nick\t\tF.Name\t\tL.Name\t\tCity\t\t\tRegion\t\tTel'
>     print '_' * 105,'\n','\t' * 13
>     for val in tbook.keys():
>             print val, '\t\t', tbook[val][0], '\t', tbook[val][1], '\t',
> tbook[val][2], '\t\t', tbook[val][3], '\t\t', tbook[val][4],'\t\t\n'
>     print '_'*105,'\n\n'
>     selectm()
>
> ## Call list names
> listpb()

if __name__ == "__main__":
   listpb()

This way you can import the module and not run it on import; it is
useful when you start wanting to reuse functions from a different
project. It is better than copy-pasting functions everywhere because
when you improve the function all the programs will pick it up. Otherwise
you will have to go back to each pasted function and pick it up.


A few items I would work to improve:
1. Remove global variables (already mentioned above)

2. You should separate any menu / navigation from your application
code. details() should only print the details and not take the
next menu choice. You probably want 2 separate menu functions.
One that returns a 'select'-ed book and one that returns next choice.
This will also help you when you implement my next point.

3. You should also change the structure of your program to loop
instead of calling listpb each time you want to restart. It is a
much better practice and while it will not affect this program
unless you do not exit for 10s or 100s of thousands of details but if
you write something that *does* navigate that many times it can crash.
Looping is probably your next programming lesson anyway :)

4. This is more of a side note but instead of using \t\t all the
time, you would be better off  learning to use the string formatting
operations. It is a little more effort to learn, but tends to be
a lot more reliable on  different systems (and with different
data trying to be printed) than manually trying to align everything.

http://docs.python.org/library/string.html#format-string-syntax


Keep on working, you have made a good start and now it is time
to refactor (programming equivalent of rewriting an essay) and
make everything better!

Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: <a href="tel:713%20-%20216%20-%205423" value="+17132165423">713 - 216 - 5423

--


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.
--
http://mail.python.org/mailman/listinfo/python-list


--
http://mail.python.org/mailman/listinfo/python-list
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate
star

RE: Advise of programming one of my first programs

Prasad, Ramit-2
It is considered polite to post your reply either after the quoted text
or interspersed as I have done below.

> By the way I dont know why your mail was in my junk I just saw it.

Probably because I only reply back to the list and let the list
forward to you.

> And here is my last code I did for the phonebook:
> Thanks
>
> ####### CODE #########
> fileread = open('myfile.txt','r')
> tbook = eval(fileread.read())
> fileread.close()

The use of eval is dangerous if you are not *completely* sure what is
being passed in. Try using pickle instead:
http://docs.python.org/release/2.5.2/lib/pickle-example.html 


> Thank you Ramit for your advice`s. I`m reading a book ( Learning Python,
> Second Edition ) by Mark Lutz and David Ascher and now I just finished the
> Basic Function lesson :) I will keep in mind what you have advised me, but
> will implement it later when I have more experience with the book, because
> I don`t understand exactly what you mean by doing all dose changes :)

Maybe I can help you more by giving you a somewhere to build from. Try
building the rest of the program given the new version of listpb below.
You will need to read the chapter on Function Arguments (chapter 18?).

 def listpb():
     tbook = load_book()
     print '_' *45, ' Phonebook ', '_' *45,'\n\n\n'
     print 'Nick\t\tF.Name\t\tL.Name\t\tCity\t\t\tRegion\t\tTel'
     print '_' * 105,'\n','\t' * 13
     for val in tbook.keys():
             print val, '\t\t', tbook[val][0], '\t', tbook[val][1], '\t',
 tbook[val][2], '\t\t', tbook[val][3], '\t\t', tbook[val][4],'\t\t\n'
     print '_'*105,'\n\n'
     while True:
          choice = get_menu_choice()
          if choice == 'e' or choice == 'E':
               book = get_book_to_edit()
               edit( tbook, book )
          elif choice == 'd' or choice == 'D':
               book = get_book_to_edit()
               details( tbook, book )
          elif choice =='Q' or choice == 'q':
               break # end loop to exit program
          else:
               print 'Selection {0} not understood.'.format( choice )

Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

--


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
--
http://mail.python.org/mailman/listinfo/python-list
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate
star

Re: Advise of programming one of my first programs

Tim Chase-4
On 03/27/12 10:32, Prasad, Ramit wrote:
>> fileread = open('myfile.txt','r')
>> tbook = eval(fileread.read())
>> fileread.close()
>
> The use of eval is dangerous if you are not *completely* sure what is
> being passed in. Try using pickle instead:
> http://docs.python.org/release/2.5.2/lib/pickle-example.html

Or, depending on the use, you might use ast.literal_eval()

A cursory glance at the OP's code suggests that this may simply
be a dict of values-to-lists of purely literals, so
literal_eval() should do the job.

-tkc


--
http://mail.python.org/mailman/listinfo/python-list
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate
star

Re: Advise of programming one of my first programs

Anatoli Hristov
In reply to this post by Prasad, Ramit-2
This was difficult, now I feel more confused it works, but I`m sure its not the way you wanted :)
 
The use of eval is dangerous if you are not *completely* sure what is
being passed in. Try using pickle instead:
http://docs.python.org/release/2.5.2/lib/pickle-example.html
 I`m sure about that I will use pickle nex time
 
Maybe I can help you more by giving you a somewhere to build from. Try
building the rest of the program given the new version of listpb below. 
That was hard :) 

You will need to read the chapter on Function Arguments (chapter 18?).
My book is translated in Bulgarian and it is chapter 13 should be the same in the original too. 
 
Here is the code now:

def load_book():
    load_book = open('c:/Python27/Toli/myfile.txt', 'r')
    load_book = eval(load_book.read())
    return load_book
def write_book(tbook):
    write_book = open('c:/Python27/Toli/myfile.txt', 'w')
    write_book.write(str(tbook))

def details(choice):
        sb = tbook[choice]
        print 'Nickname: ', choice, ' is selected\n'
        print 'First name:\t', sb[0], '\n'
        print 'Last name:\t', sb[1], '\n'
        print 'Country:\t', sb[2], '\n'
        print 'City:\t\t', sb[3], '\n'
        print 'Phone number:\t',sb[4], '\n'
        print 'Memos:\n'
        print sb[5]
        print '\n\n(E)dit\n\n'
        print '(B)ack to phonebook list\n\n'
        dmenu(choice)
        
def edit(choice):
    sb = tbook[choice]
    fn = raw_input('New name for ' + sb[0] + ' : ')
    sb[0] = fn
    ln = raw_input('New name for ' + sb[1] + ' : ')
    sb[1] = ln
    write_book(tbook)
##    filewrite = open('myfile.txt','w')
##    filewrite.write(str(tbook))
##    filewrite.close()
##    raw_input('\n\n\nPress <Enter> to return')
    details(choice)

def get_menu_choice():
choice = raw_input('input: ')
return choice



def listpb():
    global tbook
    tbook = load_book()
    print '_' *45, ' Phonebook ', '_' *45,'\n\n\n'
    print 'Nick\t\tF.Name\t\tL.Name\t\tCity\t\t\tRegion\t\tTel'
    print '_' * 105,'\n','\t' * 13
    for val in tbook.keys():
            print val, '\t\t', tbook[val][0], '\t', tbook[val][1], '\t', tbook[val][2], '\t\t', tbook[val][3], '\t\t', tbook[val][4],'\t\t\n'
    print '_'*105,'\n\n'
    mmenu()

def mmenu():
    while True:
        choice = get_menu_choice()
        if choice in tbook:
            details(choice)
        elif choice not in tbook:
            print choice + 'Not in the book.'
            mmenu()
        elif choice =='Q' or choice =='q':
            break
        else:
            print 'Selection {0} not understood.'.format(choice) ## This is something that I don`t understand yet
            
            
def dmenu(choice):
    while True:
        choicem = get_menu_choice()
        if choicem == 'e' or choicem == 'E':
              edit(choice)
        elif choicem == 'd' or choicem == 'D':
              book = get_book_to_edit()
              details( tbook, book )
        elif choicem =='Q' or choicem == 'q':
              break # end loop to exit program
        else:
              print 'Selection {0} not understood.'.format( choicem )

listpb()



--
http://mail.python.org/mailman/listinfo/python-list
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate
star

Re: Advise of programming one of my first programs

Anatoli Hristov
In reply to this post by Tim Chase-4
Thanks, but I`m still far from for dose details I thing:)

Regards

Anatoli

On Tue, Mar 27, 2012 at 5:53 PM, Tim Chase <[hidden email]> wrote:
On 03/27/12 10:32, Prasad, Ramit wrote:
fileread = open('myfile.txt','r')
tbook = eval(fileread.read())
fileread.close()

The use of eval is dangerous if you are not *completely* sure what is
being passed in. Try using pickle instead:
http://docs.python.org/release/2.5.2/lib/pickle-example.html

Or, depending on the use, you might use ast.literal_eval()

A cursory glance at the OP's code suggests that this may simply be a dict of values-to-lists of purely literals, so literal_eval() should do the job.

-tkc


--
http://mail.python.org/mailman/listinfo/python-list


--
http://mail.python.org/mailman/listinfo/python-list
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate
star

Re: RE: Advise of programming one of my first programs

Evan Driscoll-3
In reply to this post by Prasad, Ramit-2
On 01/-10/-28163 01:59 PM, Prasad, Ramit wrote:
>> ####### CODE #########
>> fileread = open('myfile.txt','r')
>> tbook = eval(fileread.read())
>> fileread.close()
>
> The use of eval is dangerous if you are not *completely* sure what is
> being passed in. Try using pickle instead:
> http://docs.python.org/release/2.5.2/lib/pickle-example.html

Um, at least by my understanding, the use of Pickle is also dangerous if
you are not completely sure what is being passed in:

   Warning: The pickle module is not intended to be secure
   against erroneous or maliciously constructed data. Never
   unpickle data received from an untrusted or unauthenticated
   source.
             - http://docs.python.org/library/pickle.html


Evan
--
http://mail.python.org/mailman/listinfo/python-list
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate
star

RE: Advise of programming one of my first programs

Prasad, Ramit-2
In reply to this post by Anatoli Hristov
> def load_book():
>     load_book = open('c:/Python27/Toli/myfile.txt', 'r')
>     load_book = eval(load_book.read())
>     return load_book
> def write_book(tbook):
>     write_book = open('c:/Python27/Toli/myfile.txt', 'w')
>     write_book.write(str(tbook))
>
> def details(choice):
>         sb = tbook[choice]
>         print 'Nickname: ', choice, ' is selected\n'
>         print 'First name:\t', sb[0], '\n'
>         print 'Last name:\t', sb[1], '\n'
>         print 'Country:\t', sb[2], '\n'
>         print 'City:\t\t', sb[3], '\n'
>         print 'Phone number:\t',sb[4], '\n'
>         print 'Memos:\n'
>         print sb[5]
>         print '\n\n(E)dit\n\n'
>         print '(B)ack to phonebook list\n\n'
>         dmenu(choice)
>
> def edit(choice):
>     sb = tbook[choice]
>     fn = raw_input('New name for ' + sb[0] + ' : ')
>     sb[0] = fn
>     ln = raw_input('New name for ' + sb[1] + ' : ')
>     sb[1] = ln
>     write_book(tbook)
> ##    filewrite = open('myfile.txt','w')
> ##    filewrite.write(str(tbook))
> ##    filewrite.close()
> ##    raw_input('\n\n\nPress <Enter> to return')
>     details(choice)
>
> def get_menu_choice():
> choice = raw_input('input: ')
> return choice
>
>
>
> def listpb():
>     global tbook
>     tbook = load_book()
>     print '_' *45, ' Phonebook ', '_' *45,'\n\n\n'
>     print 'Nick\t\tF.Name\t\tL.Name\t\tCity\t\t\tRegion\t\tTel'
>     print '_' * 105,'\n','\t' * 13
>     for val in tbook.keys():
>             print val, '\t\t', tbook[val][0], '\t', tbook[val][1], '\t',
> tbook[val][2], '\t\t', tbook[val][3], '\t\t', tbook[val][4],'\t\t\n'
>     print '_'*105,'\n\n'
>     mmenu()
>
> def mmenu():
>     while True:
>         choice = get_menu_choice()
>         if choice in tbook:
>             details(choice)
>         elif choice not in tbook:
>             print choice + 'Not in the book.'
>             mmenu()
>         elif choice =='Q' or choice =='q':
>             break
>         else:
>             print 'Selection {0} not understood.'.format(choice) ## This is
> something that I don`t understand yet
>
>
> def dmenu(choice):
>     while True:
>         choicem = get_menu_choice()
>         if choicem == 'e' or choicem == 'E':
>               edit(choice)
>         elif choicem == 'd' or choicem == 'D':
>               book = get_book_to_edit()
>               details( tbook, book )
>         elif choicem =='Q' or choicem == 'q':
>               break # end loop to exit program
>         else:
>               print 'Selection {0} not understood.'.format( choicem )
>
> listpb()

> This was difficult, now I feel more confused it works, but I`m sure its not
> the way you wanted :)

You are correct it is not. :) You code is overly complex making it harder
to understand. Try and reduce the problem to the least number of tasks you need.
>From the Zen of Python, "Simple is better than complex." It is a good programming
mentality.

1. function that returns the loaded book
def load_book():
    load_book = open('c:/Python27/Toli/myfile.txt', 'r')
    load_book = eval(load_book.read())
    return load_book!

2. A system to navigate your program.
def mmenu():
    # load tbook here
    while True:
        choicem = get_menu_choice()
        if choicem == 'e' or choicem == 'E':
              book = get_book_name()
              edit( tbook, book )
        elif choicem == 'd' or choicem == 'D':
              book = get_book_name()
              details( tbook, book )
        elif choicem =='Q' or choicem == 'q':
              break # end loop to exit program
        else:
              print 'Selection {0} not understood.'.format( choicem )I have given you more functions

3. function to write an edited book
def write_book(tbook):
    write_book = open('c:/Python27/Toli/myfile.txt', 'w')
    write_book.write(str(tbook))
    # I think repr would be more accurate than str here.

4. Function to print the entire book
def listpb( tbook ):
    print '_' *45, ' Phonebook ', '_' *45,'\n\n\n'
    print 'Nick\t\tF.Name\t\tL.Name\t\tCity\t\t\tRegion\t\tTel'
    print '_' * 105,'\n','\t' * 13
    for val in tbook.keys():
            print val, '\t\t', tbook[val][0], '\t', tbook[val][1], '\t', tbook[val][2], '\t\t', tbook[val][3], '\t\t', tbook[val][4],'\t\t\n'
    print '_'*105,'\n\n'

5. Get input from user
def get_menu_choice():
    choice = raw_input('input: ')
    return choice

6. A function to get book name from user
def get_book_name(tbook):
    # write this and do not use global

6. A function to print an entry from the book
def details( tbook, choice ):
    # write this, no menu interaction allowed

7. A function to edit an entry from the book
def edit( tbook, choice ):
    # write this, no menu interaction allowed
    # you can ask the user what you need to change the values

I do not think you need any other functions. Now you just need to finsh all the functions
and put it all together.


Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

--


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
--
http://mail.python.org/mailman/listinfo/python-list
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate
star

Re: Advise of programming one of my first programs

Tim Chase-4
In reply to this post by Anatoli Hristov
On 03/27/12 16:53, Anatoli Hristov wrote:

> On Tue, Mar 27, 2012 at 5:53 PM, Tim Chase wrote:
>>> On 03/27/12 10:32, Prasad, Ramit wrote:
>>>> fileread = open('myfile.txt','r')
>>>> tbook = eval(fileread.read())
>>>> fileread.close()
>>>
>>>
>>> The use of eval is dangerous if you are not *completely* sure what is
>>> being passed in. Try using pickle instead:
>>
>> Or, depending on the use, you might use ast.literal_eval()
>
> Thanks, but I`m still far from for dose details I thing:)

[reordered to make the commenting inline instead of top-posted]

To make it safer, just change eval(fileread.read()) to
ast.literal_eval(fileread.read()) and insert "import ast" at the
top of your script.

-tkc



--
http://mail.python.org/mailman/listinfo/python-list
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate
star

Re: RE: Advise of programming one of my first programs

Devin Jeanpierre
In reply to this post by Evan Driscoll-3
On Tue, Mar 27, 2012 at 5:59 PM, Evan Driscoll <[hidden email]> wrote:
>> The use of eval is dangerous if you are not *completely* sure what is
>> being passed in. Try using pickle instead:
>> http://docs.python.org/release/2.5.2/lib/pickle-example.html
>
>
> Um, at least by my understanding, the use of Pickle is also dangerous if you
> are not completely sure what is being passed in:

Oh goodness yes. pickle is exactly as unsafe as eval is. Try running this code:

from pickle import loads
loads("c__builtin__\neval\n(c__builtin__\nraw_input\n(S'py>'\ntRtR.")

-- Devin
--
http://mail.python.org/mailman/listinfo/python-list
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate
star

RE: RE: Advise of programming one of my first programs

Prasad, Ramit-2
> >> The use of eval is dangerous if you are not *completely* sure what is
> >> being passed in. Try using pickle instead:
> >> http://docs.python.org/release/2.5.2/lib/pickle-example.html
> >
> >
> > Um, at least by my understanding, the use of Pickle is also dangerous if
> you
> > are not completely sure what is being passed in:
>
> Oh goodness yes. pickle is exactly as unsafe as eval is. Try running this
> code:
>
> from pickle import loads
> loads("c__builtin__\neval\n(c__builtin__\nraw_input\n(S'py>'\ntRtR.")

It might be as dangerous, but which is more likely to cause problems in
real world scenarios?

Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

--


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
--
http://mail.python.org/mailman/listinfo/python-list
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate
star

Re: Advise of programming one of my first programs

Anatoli Hristov
In reply to this post by Prasad, Ramit-2
 
You are correct it is not. :) You code is overly complex making it harder
to understand. Try and reduce the problem to the least number of tasks you need.
>From the Zen of Python, "Simple is better than complex." It is a good programming
mentality.
 
Complex is better than complicated. :p


2. A system to navigate your program.
def mmenu():
   # load tbook here
   while True:
       choicem = get_menu_choice()
       if choicem == 'e' or choicem == 'E':
             book = get_book_name()
             edit( tbook, book )
       elif choicem == 'd' or choicem == 'D':
             book = get_book_name()
             details( tbook, book )
       elif choicem =='Q' or choicem == 'q':
             break # end loop to exit program
       else:
             print 'Selection {0} not understood.'.format( choicem )I have given you more functions
With the main navigation menu I will only have the option to select a nickname and when a nickname is selected then it loads Details of the contact and from loaded details I can choice Edit or back to main screen, like I did it the first time, or else I can do it => when 'e' pressed to ask for a nickname and then edit it.
 
3. function to write an edited book
def write_book(tbook):
   write_book = open('c:/Python27/Toli/myfile.txt', 'w')
   write_book.write(str(tbook))
   # I think repr would be more accurate than str here.
I`m not that far as you already know :)  I hope I will learn everything as soon as I can as I`m not capable to read python everyday.
 
I do not think you need any other functions. Now you just need to finsh all the functions
and put it all together.

I will finish it just need to understand more the functions and complex arguments.


Thanks

Anatoli


--
http://mail.python.org/mailman/listinfo/python-list
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate
star

Re: RE: Advise of programming one of my first programs

Anatoli Hristov
In reply to this post by Prasad, Ramit-2


> > Um, at least by my understanding, the use of Pickle is also dangerous if
> you
> > are not completely sure what is being passed in:
>
> Oh goodness yes. pickle is exactly as unsafe as eval is. Try running this
> code:
>
> from pickle import loads
> loads("c__builtin__\neval\n(c__builtin__\nraw_input\n(S'py>'\ntRtR.")

It might be as dangerous, but which is more likely to cause problems in
real world scenarios?

Guys this is really something  that is not that important at this time for me

--
http://mail.python.org/mailman/listinfo/python-list
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate
star

Re: RE: Advise of programming one of my first programs

Chris Angelico
 Thu, Mar 29, 2012 at 9:36 AM, Anatoli Hristov <[hidden email]> wrote:

>> > > Um, at least by my understanding, the use of Pickle is also dangerous
>> > > if you are not completely sure what is being passed in:
>> >
>> > Oh goodness yes. pickle is exactly as unsafe as eval is. Try running
>> > this code:
>> >
>> > from pickle import loads
>> > loads("c__builtin__\neval\n(c__builtin__\nraw_input\n(S'py>'\ntRtR.")
>>
>> It might be as dangerous, but which is more likely to cause problems in
>> real world scenarios?
>
> Guys this is really something  that is not that important at this time for
> me

Maybe not, but it's still worth being aware of. Even if today your
strings will never include apostrophes, it's still important to
understand the risks of SQL injection and properly escape them before
inserting them into an SQL statement. Just docket the information in
the back of your mind "Don't use pickle with untrusted data" and move
on. :)

ChrisA
--
http://mail.python.org/mailman/listinfo/python-list
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate
star

RE: RE: Advise of programming one of my first programs

Prasad, Ramit-2
In reply to this post by Anatoli Hristov

From: Anatoli Hristov [mailto:[hidden email]]
Sent: Wednesday, March 28, 2012 5:36 PM
To: Prasad, Ramit
Cc: [hidden email]
Subject: Re: RE: Advise of programming one of my first programs

 

 

>>> > Um, at least by my understanding, the use of Pickle is also dangerous if
>>>> you
>>> > are not completely sure what is being passed in:
>>>
>>> Oh goodness yes. pickle is exactly as unsafe as eval is. Try running this
>>> code:
>>>
>>> from pickle import loads
>>> loads("c__builtin__\neval\n(c__builtin__\nraw_input\n(S'py>'\ntRtR.")

>>It might be as dangerous, but which is more likely to cause problems in
>>real world scenarios?

 

>Guys this is really something  that is not that important at this time for me

 

“My Eyes! The goggles do nothing!”

 

Ramit

 

 

Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology

712 Main Street | Houston, TX 77002

work phone: 713 - 216 - 5423

 

--

 

This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email.


--
http://mail.python.org/mailman/listinfo/python-list
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate
star

RE: Advise of programming one of my first programs

Prasad, Ramit-2
In reply to this post by Anatoli Hristov

 

>>From the Zen of Python, "Simple is better than complex." It is a good programming

mentality.

>Complex is better than complicated. :p

 

Absolutely! Too bad your version would be considered the more “complicated” version ;)

 

>With the main navigation menu I will only have the option to select a nickname and when a nickname is selected then it loads Details of the contact and from loaded details I can choice Edit or back to main screen, like I did it the first time, or else I can do it => when 'e' pressed to ask for a nickname and then edit it.

 

I was trying to simplify it to “guide” you to a more correct solution without feeding you the answer. Maybe I should have given you the explanation first to explain why you should be doing it a different way.

 

Going back to your original program (and your modifications to it), the original menu can cause crashing in more complicated programs and thus is considered a bad style. It was basically using recursion (I will touch on this later) but without any of the benefits. It was endlessly branching instead of a simple loop. Sort of like the following Menu/submenu example.

 

Menu

    submenu

         Menu

              submenu

                      Menu

                            __ad infinitum__

 

How does this matter? Let’s look at some simpler code below.

 

print ‘start’

function_a() # a function is called

    print ‘a’    # code inside the function

    print ‘b’    # code inside the function

a = ‘ something ‘

print a

function_b() # another function call

    print ‘c’     # code inside a different function

    print ‘d’     # code inside a different function

print ‘end’

 

Let us pretend we are the computer who executes one line at a time and so basically goes through a list of commands. The list we are going to execute is the following:

 

print ‘start’

function_a()

print ‘a’

print ‘b’

a = ‘ something ‘

print a

function_b()

print ‘c’

print ‘d’

print ‘end’

 

How does the computer know to execute “a = ‘ something ‘” after “print ‘b’”? It does it by storing the location where it was before it proceeds to the function call. That way when the end of the function is reached it returns to the previous spot. In essence:

 

print ‘start’

function_a()

__store this location so I can come back__

print ‘a’

print ‘b’

__return to previous location__

a = ‘ something ‘

print a

function_b()

__store this location so I can come back__

print ‘c’

print ‘b’

__return to previous location__

print ‘end’

 

Now what happens if “function_a” calls “function_a”? By the way, the term for this type of call is recursion.

 

print ‘start’

function_a()

__store this location so I can come back__

        print ‘a’

        print ‘b’

      function_a()

       __store this location so I can come back__

            print ‘a’

            print ‘b’

             function_a()

           __store this location so I can come back__

                print ‘a’

                print ‘b’

              function_a()

               __store this location so I can come back__

                    print ‘a’

                    print ‘b’

                  function_a()

                   __store this location so I can come back__

                       print ‘a’

                        print ‘b’

                      function_a()

                       __store this location so I can come back__

                            *until the program ends*

 

Now each __store__ action takes up memory and when the computer (or your program) runs out of memory your computer crashes. Your application is trivial and more likely to be ended by the user instead of going through the tens of thousands if not hundreds of thousands that Python will let you take, but it is a bad practice and a habit to avoid. A real world program would use more memory and quit even faster than yours. Recursion has its place in programming, but not in this case! What you need is a simple loop. That is why I provided you with the menu I did.

 

The following menu sounds like what you want; there were a couple different ways I could have done this.  In this version, if you type anything when asked for a menu choice that is not ‘e’ or ‘q’, the program will automatically ask you for the next book choice.

 

def mmenu():

   # load tbook here

   while True:

       book = get_book_choice()

       details( tbook, book )

       choicem = get_menu_choice()

       if choicem == 'e' or choicem == 'E':

             edit( tbook, book )

             # save tbook here

       elif choicem =='Q' or choicem == 'q':

             break # end loop to exit program

 

 

Ramit

 

 

Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology

712 Main Street | Houston, TX 77002

work phone: 713 - 216 - 5423

 

--

This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email.


--
http://mail.python.org/mailman/listinfo/python-list
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate
star

Re: Advise of programming one of my first programs

Anatoli Hristov

 

Absolutely! Too bad your version would be considered the more “complicated” version ;)

I`m sure about that, but I`am also sure that every beginner passed true that way. 

 

>With the main navigation menu I will only have the option to select a nickname and when a nickname is selected then it loads Details of the contact and from loaded details I can choice Edit or back to main screen, like I did it the first time, or else I can do it => when 'e' pressed to ask for a nickname and then edit it.

 

I was trying to simplify it to “guide” you to a more correct solution without feeding you the answer. Maybe I should have given you the explanation first to explain why you should be doing it a different way.

 

Going back to your original program (and your modifications to it), the original menu can cause crashing in more complicated programs and thus is considered a bad style. It was basically using recursion (I will touch on this later) but without any of the benefits. It was endlessly branching instead of a simple loop. Sort of like the following Menu/submenu example.

 

Menu

    submenu

         Menu

              submenu

                      Menu

                            __ad infinitum__

 

How does this matter? Let’s look at some simpler code below.

 

print ‘start’

function_a() # a function is called

    print ‘a’    # code inside the function

    print ‘b’    # code inside the function

a = ‘ something ‘

print a

function_b() # another function call

    print ‘c’     # code inside a different function

    print ‘d’     # code inside a different function

print ‘end’

 

Let us pretend we are the computer who executes one line at a time and so basically goes through a list of commands. The list we are going to execute is the following:

 

print ‘start’

function_a()

print ‘a’

print ‘b’

a = ‘ something ‘

print a

function_b()

print ‘c’

print ‘d’

print ‘end’

 

How does the computer know to execute “a = ‘ something ‘” after “print ‘b’”? It does it by storing the location where it was before it proceeds to the function call. That way when the end of the function is reached it returns to the previous spot. In essence:

 

print ‘start’

function_a()

__store this location so I can come back__

print ‘a’

print ‘b’

__return to previous location__

a = ‘ something ‘

print a

function_b()

__store this location so I can come back__

print ‘c’

print ‘b’

__return to previous location__

print ‘end’

 

Now what happens if “function_a” calls “function_a”? By the way, the term for this type of call is recursion.

 

print ‘start’

function_a()

__store this location so I can come back__

        print ‘a’

        print ‘b’

      function_a()

       __store this location so I can come back__

            print ‘a’

            print ‘b’

             function_a()

           __store this location so I can come back__

                print ‘a’

                print ‘b’

              function_a()

               __store this location so I can come back__

                    print ‘a’

                    print ‘b’

                  function_a()

                   __store this location so I can come back__

                       print ‘a’

                        print ‘b’

                      function_a()

                       __store this location so I can come back__

                            *until the program ends*

 

Now each __store__ action takes up memory and when the computer (or your program) runs out of memory your computer crashes. Your application is trivial and more likely to be ended by the user instead of going through the tens of thousands if not hundreds of thousands that Python will let you take, but it is a bad practice and a habit to avoid. A real world program would use more memory and quit even faster than yours. Recursion has its place in programming, but not in this case! What you need is a simple loop. That is why I provided you with the menu I did.

 

The following menu sounds like what you want; there were a couple different ways I could have done this.  In this version, if you type anything when asked for a menu choice that is not ‘e’ or ‘q’, the program will automatically ask you for the next book choice.

 

def mmenu():

   # load tbook here

   while True:

       book = get_book_choice()

       details( tbook, book )

       choicem = get_menu_choice()

       if choicem == 'e' or choicem == 'E':

             edit( tbook, book )

             # save tbook here

       elif choicem =='Q' or choicem == 'q':

             break # end loop to exit program

 I`m focusing on what you say and will try to follow your instructions for which - Thank you I really appreciate it...

Just before I read you mail I`ve finished my book ver. 12 with this code, ver 13 will have all the modifications and all remarks I have from you:

import ast
fname = 0
lname = 1
country = 2
city = 3
tel = 4
notes = 5

## Read data from file

def load_book():
    load_book = open('c:/Python27/Toli/myfile.txt', 'r')
    load_book = ast.literal_eval(load_book.read())
    return load_book

## Write data to file

def write_book(tbook):
    write_book = open('c:/Python27/Toli/myfile.txt', 'w')
    write_book.write(repr(tbook))

## Menu choice input

def get_menu_choice():
choice = raw_input('input: ')
return choice

## List data contacts

def listpb():
    tbook = load_book()
    print '_' *45, ' Phonebook ', '_' *45,'\n\n\n'
    print 'Nick\t\tF.Name\t\tL.Name\t\tCountry\t\t\tCity\t\tTel'
    print '_' * 105,'\n','\t' * 13
    for val in tbook.keys():
            print val, '\t\t', tbook[val][fname], '\t', tbook[val][lname], '\t', tbook[val][country], '\t\t', tbook[val][city], '\t\t', tbook[val][tel],'\t\t\n'
    print '_'*105,'\n\n\n\n'
    print 'Type nickname and press <Enter> or type <Q> to exit.\n\n\n'
    mmenu(tbook)

## Main menu

def mmenu(tbook):
    while True:
        choice = get_menu_choice()
        if choice in tbook:
            details(choice,tbook)
        elif choice == 'q' or choice == 'Q':
            break
        else:
            print 'Selection {0} not understood.'.format(choice)

## Details menu
            
def dmenu(choice, tbook):
    while True:
        choicem = get_menu_choice()
        if choicem == 'e' or choicem == 'E':
              edit(choice, tbook)
        elif choicem == 'b' or choicem == 'B':
             listpb()
        elif choicem =='Q' or choicem == 'q':
              break # end loop to exit program
        else:
              print 'Selection {0} not understood.'.format( choicem )



## Contact details

def details(choice, tbook):
    sb = tbook[choice]
    print 'Nickname: ', choice, ' is selected\n'
    print 'First name:\t', sb[fname], '\n'
    print 'Last name:\t', sb[lname], '\n'
    print 'Country:\t', sb[country], '\n'
    print 'City:\t\t', sb[city], '\n'
    print 'Phone number:\t',sb[tel], '\n'
    print 'Memos:\n'
    print sb[notes]
    print '\n\n(E)dit\n\n'
    print '(B)ack to phonebook list\n\n'
    dmenu(choice, tbook)


## Edit contact

def edit(choice, tbook):
    sb = tbook[choice]
    fn = raw_input('New name for ' + sb[fname] + ' : ')
    if fn == '':
        pass
    else:
        sb[fname] = fn
    ln = raw_input('New name for ' + sb[lname] + ' : ')
    if ln == '':
        pass
    else:
        sb[lname] = ln
    write_book(tbook)
    details(choice, tbook)

listpb()
 

 

Ramit

 

 

Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology

712 Main Street | Houston, TX 77002

work phone: 713 - 216 - 5423

 

--

This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email.


--
http://mail.python.org/mailman/listinfo/python-list



--
http://mail.python.org/mailman/listinfo/python-list
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate
star

Re: Advise of programming one of my first programs

Anatoli Hristov
Ramit,

This seems to be more logic now "I hope" :)
#########################################
import ast
fname = 0
lname = 1
country = 2
city = 3
tel = 4
notes = 5

## Read data from file

def load_book():
    load_book = open('c:/Python27/Toli/myfile.txt', 'r')
    load_book = ast.literal_eval(load_book.read())
    return load_book

## Write data to file

def write_book(tbook):
    write_book = open('c:/Python27/Toli/myfile.txt', 'w')
    write_book.write(repr(tbook))

## Menu choice input

def get_menu_choice(text):
choice = raw_input(text)
return choice

## List data contacts

def listpb():
    ##tbook = load_book()
    print '_' *45, ' Phonebook ', '_' *45,'\n\n\n'
    print 'Nick\t\tF.Name\t\tL.Name\t\tCountry\t\t\tCity\t\tTel'
    print '_' * 105,'\n','\t' * 13
    for val in tbook.keys():
            print val, '\t\t', tbook[val][fname], '\t', tbook[val][lname], '\t', tbook[val][country], '\t\t', tbook[val][city], '\t\t', tbook[val][tel],'\t\t\n'
    print '_'*105,'\n\n\n\n'
    print 'Type nickname and press <Enter> or type <Q> to exit.\n\n\n'

## Main menu

def mmenu(tbook):
    listpb()
    while True:
        text = 'Type your option: '
        choice = get_menu_choice(text)
        if choice == 'e' or choice == 'E':
            text = 'Type nickname and press <Enter> to edit: '
            choicen = get_menu_choice(text)
            if choicen in tbook:
                edit(choicen, tbook)
        elif choice == 'b' or choice == 'B':
            listpb()
        elif choice == 'd' or choice == 'D':
            text = 'Type nickname and press <Enter> for details: '
            choicen = get_menu_choice(text)
            if choicen in tbook:
                details(choicen, tbook)
        elif choice == 'q' or choice == 'Q':
            break
        else:
            print 'Selection {0} not understood.'.format(choice)

## Contact details

def details(choicen, tbook):
    sb = tbook[choicen]
    print 'Nickname: ', choicen, ' is selected\n'
    print 'First name:\t', sb[fname], '\n'
    print 'Last name:\t', sb[lname], '\n'
    print 'Country:\t', sb[country], '\n'
    print 'City:\t\t', sb[city], '\n'
    print 'Phone number:\t',sb[tel], '\n'
    print 'Memos:\n'
    print sb[notes]
    print '\n\n(E)dit\n\n'
    print '(B)ack to phonebook list\n\n'

## Edit contact

def edit(choicen, tbook):
    sb = tbook[choicen]
    fn = raw_input('New name for ' + sb[fname] + ' : ')
    if fn == '':
        pass
    else:
        sb[fname] = fn
    ln = raw_input('New name for ' + sb[lname] + ' : ')
    if ln == '':
        pass
    else:
        sb[lname] = ln
    write_book(tbook)
    details(choicen, tbook)
tbook = load_book()
mmenu(tbook)

#######################################

What you thing?

Regards

Anatoli

--
http://mail.python.org/mailman/listinfo/python-list
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate
star

RE: Advise of programming one of my first programs

Prasad, Ramit-2
> Ramit,
>
> This seems to be more logic now "I hope" :)
> #########################################
> import ast
> fname = 0
> lname = 1
> country = 2
> city = 3
> tel = 4
> notes = 5
>
> ## Read data from file
>
> def load_book():
>     load_book = open('c:/Python27/Toli/myfile.txt', 'r')
>     load_book = ast.literal_eval(load_book.read())
>     return load_book
>
> ## Write data to file
>
> def write_book(tbook):
>     write_book = open('c:/Python27/Toli/myfile.txt', 'w')
>     write_book.write(repr(tbook))

Either use write_book.close() or a context manager instead. I suggest
the context manager approach but it only works on Python 2.6+

Otherwise, there is a chance that the file might not get written out.

>
> ## Menu choice input
>
> def get_menu_choice(text):
> choice = raw_input(text)
> return choice
>
> ## List data contacts
>
> def listpb():
>     ##tbook = load_book()
>     print '_' *45, ' Phonebook ', '_' *45,'\n\n\n'
>     print 'Nick\t\tF.Name\t\tL.Name\t\tCountry\t\t\tCity\t\tTel'
>     print '_' * 105,'\n','\t' * 13

tbook should be passed in. This is currently using the global variable
which is generally discouraged.

>     for val in tbook.keys():
>             print val, '\t\t', tbook[val][fname], '\t', tbook[val][lname],
> '\t', tbook[val][country], '\t\t', tbook[val][city], '\t\t',
> tbook[val][tel],'\t\t\n'
>     print '_'*105,'\n\n\n\n'


The following looks like menu choices and should instead be printed
along with the menu text.

>     print 'Type nickname and press <Enter> or type <Q> to exit.\n\n\n'
>
> ## Main menu
>
> def mmenu(tbook):
>     listpb()
>     while True:
>         text = 'Type your option: '
>         choice = get_menu_choice(text)
>         if choice == 'e' or choice == 'E':
>             text = 'Type nickname and press <Enter> to edit: '
>             choicen = get_menu_choice(text)
>             if choicen in tbook:
>                 edit(choicen, tbook)
>         elif choice == 'b' or choice == 'B':
>             listpb()
>         elif choice == 'd' or choice == 'D':
>             text = 'Type nickname and press <Enter> for details: '
>             choicen = get_menu_choice(text)
>             if choicen in tbook:
>                 details(choicen, tbook)
>         elif choice == 'q' or choice == 'Q':
>             break
>         else:
>             print 'Selection {0} not understood.'.format(choice)
>
> ## Contact details
>
> def details(choicen, tbook):
>     sb = tbook[choicen]
>     print 'Nickname: ', choicen, ' is selected\n'
>     print 'First name:\t', sb[fname], '\n'
>     print 'Last name:\t', sb[lname], '\n'
>     print 'Country:\t', sb[country], '\n'
>     print 'City:\t\t', sb[city], '\n'
>     print 'Phone number:\t',sb[tel], '\n'
>     print 'Memos:\n'
>     print sb[notes]

Again, the following menu options should be printed where you
call get_menu_choice.

>     print '\n\n(E)dit\n\n'
>     print '(B)ack to phonebook list\n\n'
>
> ## Edit contact
>
> def edit(choicen, tbook):
>     sb = tbook[choicen]
>     fn = raw_input('New name for ' + sb[fname] + ' : ')
>     if fn == '':
>         pass
>     else:
>         sb[fname] = fn
>     ln = raw_input('New name for ' + sb[lname] + ' : ')
>     if ln == '':
>         pass
>     else:
>         sb[lname] = ln
>     write_book(tbook)
>     details(choicen, tbook)
> tbook = load_book()
> mmenu(tbook)
>
> #######################################
>
> What you thing?
>
> Regards
>
> Anatoli

Looks better. Instead of having global variables (fname, lname,
tel) why not just use a string in 'last_name', 'first_name', and
'telephone #'? That would be more self explanatory when looking at
the data file and reading the code.

References like
    sb[lname]
would become
    sb['last_name']

Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

--

This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
--
http://mail.python.org/mailman/listinfo/python-list
Loading...