Domanda

I'm using py 2.7. I'm completely new to python and by that I mean three days. I'm trying to get this basic ability down though, so I can create some scripts as I work along in the book I'm learning from. What I want to do is to create a script that will print lists to the screen when one is chosen, between functions, methods, and modules. All I know to do is this, but if someone can help me with making the script accept functions, methods, or modules as input to print the lists, I would be greatly appreciative and will learn python faster. Thanks in advance.

raw_input ("Choose functions, methods, or modules: ')

of course I also know how to make the list:

functions= [
...some functions
]
modules = [
...some modules
]
methods = [
...some methods
]

what I don't know how to do is put it all together into an executable script that will accept the three choices as raw_input. remember this isn't py 3 so input is not what i'm looking for.

È stato utile?

Soluzione 2

You can consider mapping them into a dictionary. All straight forward code.

functions = ['sum', 'id', 'str', 'list']
modules = ['random', 'numpy', 'scipy', 'os']
methods = ['some_other_stuff']

answer = dict()
answer['functions'] = functions
answer['modules'] = modules
answer['methods'] = methods

while True:
    choice = raw_input('Choose between functions, methods, or modules: ')
    if choice in answer.keys(): # ['functions', 'modules', 'methods']
        print answer[choice]

Altri suggerimenti

choice = None
while choice not in ['functions', 'methods', 'modules']:
    choice = raw_input('Choose functions, methods, or modules: ')

Here is an example of how you could accept 3 different choices for user input. If the user doesn't type functions, methods, or modules, it will ask them to choose again.

Then depending on what they enter, if it's in the three choices, it will execute only that choice they typed. This works the same for practically anything.

   def userInput():
       variable_21 = raw_input("Type functions, methods, or modules: ")
       if variable_21 == "functions":
           doFunction()
           print functions
       elif variable_21 == "methods":
           print methods
       elif variable_21 == "modules":
           print modules
       else:
           print "Sorry, you didn't type a valid value."
           userInput()

A really good way to learn python for a beginner. Is to use www.codecademy.com. They have very straight forward, step by step instructions.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top