-1
def key(keyC, keyG, keyE):
    keyC = ('em','f','g','am','c')
    keyG = ('g','c','d','em','am')
    keyE = ('a','b','e')
    key = input("What key would you like to play in")
    print "I will display chords in that key"
    if input == 'c':
        return(random.choice(keyC))
    elif input == 'g':
        return(random.choice(keyG))
    elif input == 'e':
        return(random.choice(keyE))
    else:
        return "Pick another key"

I'm new at this and I'm writing my code and it just seems funny. Any input or advice would be helpful.

2 Answers2

4

You should be comparing your strings against key:

if key == 'c':
...
elif key == 'g':
...
elif key == 'e':

key is what holds the user's input. input is just the built-in function for getting the input:

>>> key = input(':')
:abc
>>> input
<built-in function input>
>>> key
'abc'
>>>

Note however that the demonstration given above was written in Python 3.x. If you are using Python 2.x, then you should be using raw_input instead of input. The Python 2.x input function evaluates its input as real Python code and will raise a NameError for any undefined names you enter.

1

A few corrections:

  1. Use key, as outlines by iCodez
  2. Put import random above your function definition. Otherwise, a program that uses this will ask where random is.
  3. Use raw_input("What key would you like to play in") instead of input. If I type c after the prompt, input will look for a variable named c and print its value. If that variable doesn't exist, and error is thrown. raw_input just converts your input to a string.
  4. If you're defining keyC,keyG, and keyE within the function as constants, then having them as arguments to the function is not necessary (and does nothing). You could have them as optional arguments, or you could leave out the arguments entirely.

Final Code:

import random
def key(keyC=('em','f','g','am','c'),keyG=('g','c','d','em','am'),keyE=('a','b','e')): 
    #keyC, keyG, keyE as optional arguments

    key = raw_input("What key would you like to play in")
    print "I will display chords in that key"

    if key == 'c':
        return(random.choice(keyC))
    elif key == 'g':
        return(random.choice(keyG))
    elif key == 'e':
        return(random.choice(keyE))
    else:
        return "Pick another key"

Also see this answer.

Edit: As per twasbrillig, this solution assumes Python 2.x and not Python 3. I use Python 2.7, and it is still commonly seen.

Community
  • 1
  • 1
Matt
  • 303
  • 1
  • 2
  • 16
  • 1
    The OP may be using Python 3 in which case `input` is the correct one to use. – twasbrillig Nov 15 '14 at 18:41
  • Ah I hadn't considered Python 3. I'm accustomed to using Python 2.7. :) I guess that detail is also required. – Matt Nov 15 '14 at 19:03
  • 1
    Cool. The comment was removed but someone pointed out that the `print` statements show that in this case the OP is most likely using Python 2. – twasbrillig Nov 15 '14 at 19:04