Member Avatar for revellution

Hi everyone, I just started learning Python 3.1 (never done programming before). I just wrote this useless little program. It seems to work but I would just like a little bit of feedback as to how well I executed the idea. Basically I want to know if I am making things hard for myself by going the long way about it or if it looks pretty efficient. Thanks guys, I promise I will help you too when I actually know what I'm doing :?:

import time

def addNames():
    while True:
        userInput = input('Please type a name to add to the list or "Q" when you are done...')
        if userInput == 'q':
            break
        elif userInput == 'Q':
            print('\n')
            break
        else:
            names.append(userInput)

def printNames():
    if not names:
        print('\nThere are no names in the list...\n')
    else:
        print('\n'.join(names), "\n")

names = []
while True:
    userInput = str.lower(input('What would you like to do?\nA) Add names?\nB) Print names?\nC) Quit\n'))
    if userInput == 'a':
        print('\n')
        addNames()
    elif userInput == 'b':
        printNames()
    elif userInput == 'c':
        print('\nNow quitting program...')
        time.sleep(3)
        break
    else:
        print('\nPlease enter "A", "B" or "C"\n')

Recommended Answers

All 10 Replies

I have to say that's pretty good for your first little program. I just have one little suggestion: You don't need to do print('\n') to print a new line, you can simply use print to print a new line (correct me if I am wrong about 3.x, but this is true for 2.6).

The only other thing I can say is...expand it. First, try adding a menu option of deleting a name from the list. Next, allow the user to also enter a phone number for the name (hint: you can use a dictionary). To get a little more practice you can also try putting it into a class. It would be a very good habit to get into early.

Good work and good luck in the world of programming.

It looks good.
Like SoulMazer said, you don't need the "\n".

And I don't use 3.0, I use 2.6 and in your addNames() function I noticed you using input(). In 2.6 input() is for numbers and raw_input() is for strings, I don't know about 3.0 but that would have given me tracebacks used like that.

For further expansion, try making it a GUI and/or adding more entry options. And maybe some sorting of existing entries?

Anyway good work. =)

I see no big problem with the script. Most of my feedback is coming from the assumption, that the program gets bigger, and must be maintained in the future.

  1. I recommend using python 2.x. Most libraries and people use this, and there are big differences on the beginner level, but hardly any differences on more advanced levels.
  2. You use a global names variable. It is quick and simple, but in the long run does not pay. Use a class instead, or pass the names between the functions.
  3. It is a good practice to never put anything on zero level except class and def statements and an if name equals main line.
  4. You cannot enter "q" as a word. Maybe it is a feature not a bug:)
  5. I have never seen str.lower called. I allways call "actual string".lower(). I think it is a difference on object oriented and structural-functional style.
  6. The python naming convention hardly recommends a schema that does permit thisTypeOfCamelCase. Most people I know never use this. One has to write code, that makes clear if a variable is local, global, a method, a function or any other. But the main point is consistency.
  7. It is good practice to isolate the part that handles io (here user input and output) from the part that does internal processing. But there is no processing in this case except list.add.
from __future__ import print_function #python 2.x glitch
import time

input=raw_input #python 2.x glitch
class Names(object):#(object) another python 2.x glitch
    def __init__(self):
        self.names=[]
    
    def add(self):
        while True:
            userInput = input('Please type a name to add to the list or "Q" when you are done...')
            if userInput == 'q':
                break
            elif userInput == 'Q':
                print('\n')
                break
            else:
                self.names.append(userInput)

    def print_names(self):
        if not self.names:
            print('\nThere are no names in the list...\n')
        else:
            print('\n'.join(self.names), "\n")

def main():
    names=Names()
    while True:
        userInput = input('What would you like to do?\nA) Add names?\nB) Print names?\nC) Quit\n').lower()
        if userInput == 'a':
            print('\n')
            names.add()
        elif userInput == 'b':
            names.print_names()
        elif userInput == 'c':
            print('\nNow quitting program...')
            time.sleep(3)
            break
        else:
            print('\nPlease enter "A", "B" or "C"\n')

if __name__=="__main__":
    main()

Well, my initial comment is, great work!

If this is your first program, then you are doing really great!


What is good:

  1. You have a while True: !
    It might not seem like much, but your use of it indicates that you really understand how loops work.
  2. You are using if not names: As you can see, names is a list.
    I would expect a beginner to do something like: if len(names) == 0: or perhaps even if not len(names): By using if not names: , you indicate that you understand that an empty list is essentially False , which is a crucial concept.
  3. You are using Python 3.0, which is good in my opinion. Sure, there are changes from Py2.6, but languages change. Nobody uses Python 1.0 anymore, I hope. Sooner or later, Python 3.0 will be the standard by majority, so I encourage you to continue learning it.
  4. Your use of str.join(), which is great. String operations are pretty neat in Python.
  5. Coming to Daniweb to ask for feedback. We're very eager to comment on your code. Don't be afraid to ask questions.

What direction I would suggest you take:
This is a good program, and of course, you can expand it.

Python is a big language, and you're very good at the scripting part of it. What about its object-oriented paradigm?

Learn about classes and add some to your code.
They make Python fun.

Your program shows that you really understand a huge part of Python. Keep learning though, there's lots more!

I'm sorry that I have to double post, can't edit after 30 min :(.

Anyways, here are some things that you might want to try in future code (because they are common in Python code, and really help).

  • try...except...finally
  • the class statement
  • for...in
  • continue
  • pass (does nothing, by the way. You might find it useful, it's good inside of empty functions.
  • raise (first understand Exception handling though)
  • return (very crucial for functions)
  • function arguments (extremely crucial)
  • docstrings and comments (even good programmers will forget what some functions do)

When you've mastered that, you can try adding even more advanced items to your code, such as:

  • with...as
  • function decorators
  • the yield statement
  • metaclasses (which I never use. it's dark, scary magic. Just to get you curious :D)
  • assert, unittests
  • regular expressions
  • GUI (there are people who encourage you to extend your program with GUI. Don't yet. First make sure you have a good foundation in Python, and a good understanding of OO, which is my recommendation. GUI is considered an advanced topic.

Just keep coding, and you'll get better every year. Feel free to ask questions.

Member Avatar for revellution

Thanks for all the feedback guys! Good to see I'm on the right track. I will try again with some classes and let you know how it turns out!

Thanks again its really great to get positive feedback on something I'm so new at :D

Member Avatar for revellution

Okie dokie dudes... I put it in a class and let you name the list. I will go into depth about 3.1 later but for now what do you think?

import time

class nameList:
    
    def __init__(self, name):
        self.names = []
        self.name = name
        print('Now constructing a', name, 'list!')

    def addNames(self):
        while True:
            self.userInput = input('Please type a name to add to the list or "Q" when you are done...')
            if self.userInput == 'q':
                break
            elif self.userInput == 'Q':
                break
            else:
                self.names.append(self.userInput)

    def printNames(self):
        if not self.names:
            print('\nThere are no names in the list...\n')
        else:
            print('\n'.join(self.names), "\n")

    def delNames(self):
        while True:
            self.userInput = input('Type a name to delete off the list or "Q" when you are done...')
            if self.userInput == 'q':
                break
            elif self.userInput == 'Q':
                break
            else:
                self.names.remove(self.userInput)

    def runMenu(self):
        while True:
            print('-'*30)
            self.userInput = str.lower(input('What would you like to do?\nA) Add names?\nB) Print names?\nC) Delete Names?\nD) Quit\n'))
            print('-'*30)
            if self.userInput == 'a':
                print('\n')
                self.addNames()
            elif self.userInput == 'b':
                self.printNames()
            elif self.userInput == 'c':
                self.delNames()
            elif self.userInput == 'd':
                print('\nNow quitting program...')
                time.sleep(3)
                break
            else:
                print('\nPlease enter "A", "B" or "C"\n')

nameOfList = input('What would you like to make a list of?')
newList = nameList(nameOfList)
newList.runMenu()

And here is the output!

What would you like to make a list of?Cars
Now constructing a Cars list!
------------------------------
What would you like to do?
A) Add names?
B) Print names?
C) Delete Names?
D) Quit
a
------------------------------


Please type a name to add to the list or "Q" when you are done...Subaru Impreza WRX
Please type a name to add to the list or "Q" when you are done...Mitsubishi Lancer VRX
Please type a name to add to the list or "Q" when you are done...q
------------------------------
What would you like to do?
A) Add names?
B) Print names?
C) Delete Names?
D) Quit
c
------------------------------
Type a name to delete off the list or "Q" when you are done...Mitsubishi Lancer VRX
Type a name to delete off the list or "Q" when you are done...q
------------------------------
What would you like to do?
A) Add names?
B) Print names?
C) Delete Names?
D) Quit
b
------------------------------
Subaru Impreza WRX

------------------------------
What would you like to do?
A) Add names?
B) Print names?
C) Delete Names?
D) Quit
d
------------------------------

Now quitting program...

If you are on Linux you can make the program executable, typing ./programname in terminal.

For that you need to point to the interpreter, add at the beginning of the program, first line:

#!/usr/bin/python

And at the bottom where the initialization are made, before making object class:

if __name__ == "__main__":

After that run chmod a+x programname.py
Turns, green, as an executable on linux.
Hope my 2 cents help, i am a beginner also. :)

Some recommended changes, most of them are style changes ...

import time

# it's customary to capitalize class names
class NameList:
    
    def __init__(self, name):
        self.names = []
        self.name = name
        print('Now constructing a', name, 'list!')

    def addNames(self):
        prompt = """\
Type a name to add to the list
or "Q" when you are done... """        
        while True:
            self.userInput = input(prompt)
            if self.userInput in 'Qq':
                break
            else:
                self.names.append(self.userInput)

    def printNames(self):
        if not self.names:
            print('\nThere are no names in the list...\n')
        else:
            print('\n'.join(self.names), "\n")

    def delNames(self):
        # helps code line to stay within 70 char length
        prompt = """\
Type a name to delete off the list
or "Q" when you are done... """
        while True:
            self.userInput = input(prompt)
            if self.userInput in 'Qq':
                break
            elif self.userInput in self.names:
                self.names.remove(self.userInput)
            else:
                print('Name not in list!')
                break

    def runMenu(self):
        while True:
            print('-'*30)
            # Python relaxes indent rules within a multiline string
            prompt = """\
What would you like to do?
A) Add names?
P) Print names?
D) Delete Names?
Q) Quit
"""
            self.userInput = input(prompt).lower()
            print('-'*30)
            if self.userInput == 'a':
                print('\n')
                self.addNames()
            elif self.userInput == 'p':
                self.printNames()
            elif self.userInput == 'd':
                self.delNames()
            elif self.userInput == 'q':
                print('\nNow quitting program...')
                time.sleep(3)
                break
            else:
                print('\nPlease enter "A", "P", "D" or "Q"\n')


nameOfList = input('What would you like to make a list of? ')
newList = NameList(nameOfList)
newList.runMenu()

Overall, nice coding!

Member Avatar for revellution

Here is the final version of my first program, the Almighty List Maker!

import time

class NameList:
    
    def __init__(self, name):
        self.items = []
        self.name = name
        print('-'*30)
        print('Now constructing a', name, 'list!')

    def addNames(self):
        print('Please type an item to add to the list or "Q" when you are done...')
        while True:
            userInput = input('...')
            if userInput in 'qQ':
                break
            else:
                self.items.append(userInput)

    def printNames(self):
        if not self.items:
            print()
            print('***There are no items in the list!***')
            time.sleep(3)
            print()
        else:
            print()
            print('\n'.join(self.items))
            print()

    def delNames(self):
        print('Type an item to delete off the list or "Q" when you are done...')
        while True:
            userInput = input('...')
            if userInput in 'qQ':
                break
            elif userInput in self.items:
                self.items.remove(userInput)
            else:
                print()
                print('***That item is not in the list (note: it\'s case sensitive)***')
                time.sleep(3)
                print()

    def savNames(self):
        items = '\n'.join(self.items)
        nameOfFile = self.name + ' List.txt'
        file = open(nameOfFile, 'w')
        file.write(items)
        file.close()
        print()
        print('Exported to', nameOfFile)
        print()
                
    def runMenu(self):
        while True:
            print('-'*30)
            prompt = \
'''What would you like to do?
A) Add items?
P) Print items?
D) Delete items?
S) Save list to a file?
Q) Quit?\n'''
            self.userInput = input(prompt).lower()
            print('-'*30)
            if self.userInput == 'a':
                self.addNames()
            elif self.userInput == 'p':
                self.printNames()
            elif self.userInput == 'd':
                self.delNames()
            elif self.userInput == 's':
                self.savNames()
            elif self.userInput == 'q':
                print('\nNow quitting program...')
                time.sleep(3)
                break
            else:
                print('\nPlease enter "A", "P", "D" or "Q"\n')

nameOfList = input('What would you like to make a list of? ')
newList = NameList(nameOfList)
newList.runMenu()
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.