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"
我是新手,我正在编写我的代码,这看起来很有趣。任何意见或建议都会有所帮助。
答案 0 :(得分:4)
您应该将您的字符串与key
进行比较:
if key == 'c':
...
elif key == 'g':
...
elif key == 'e':
key
是用户输入的内容。 input
只是获取输入的内置函数:
>>> key = input(':')
:abc
>>> input
<built-in function input>
>>> key
'abc'
>>>
但请注意,上面给出的演示是用Python 3.x编写的。如果您使用的是Python 2.x,那么您应该使用raw_input
而不是input
。 Python 2.x input
函数将其输入计算为真正的Python代码,并为您输入的任何未定义名称引发NameError
。
答案 1 :(得分:1)
一些更正:
key
,作为iCodez import random
放在函数定义之上。否则,使用此程序的程序将询问random
的位置。raw_input("What key would you like to play in")
代替input
。如果我在提示后输入c
,input
将查找名为c
的变量并打印其值。如果该变量不存在,则抛出错误。 raw_input
只是将您的输入转换为字符串。keyC
,keyG
和keyE
定义为常量,则不必将它们作为函数的参数(并且不执行任何操作)。你可以将它们作为可选参数,或者你可以完全忽略参数。最终守则:
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"
另见this answer。
编辑:根据twasbrillig,此解决方案假定使用Python 2.x而不是Python 3.我使用的是Python 2.7,它仍然很常见。