这是我为电话簿编写的一些简单代码。 它似乎不起作用,我不知道为什么。 我是python的新手,我确信有很多错误。
def startup(contactlist = {}):
print "Welcome to Contacts+\n"
print "Please enter your name"
name = raw_input()
print "Hi " + name + " would you like to check your existing contacts or make new ones?"
print "To make new contacts type in 'New'"
print "To check existing contacts type in 'Contacts'"
choose = ""
choose = raw_input()
if choose == "'New'" or choose == "'new'" or choose == "New" or choose == "new":
newcontact()
elif choose == "'Contacts'" or choose == "'contacts'" or choose == "Contacts" or choose == "contacts":
checkcontact()
def newcontact():
startup(contactlist = {})
print "To create a new contact please first input the name"
contactname = raw_input()
print "Next enter the phone number"
contactnumber = raw_input()
print "Contact created!"
contactlist[name] = number
def checkcontact():
startup(contactlist = {})
print contactlist
startup()
答案 0 :(得分:0)
你试过这个吗??
此if / elif语句不应缩进:
if choose == "'New'" or choose == "'new'" or choose == "New" or choose == "new":
newcontact()
elif choose == "'Contacts'" or choose == "'contacts'" or choose == "Contacts" or choose == "contacts":
checkcontact()
为什么你有:
startup(contactlist = {})
在newcontact()和checkcontact()函数的开头?
答案 1 :(得分:0)
你可以做的四件事现在让你的代码变得更好:
None
的Python习惯用法来做正确的事。raw_input
的第一个参数。而不是print('Hey user!'); raw_input()
,只需撰写raw_input('Hey user!')
。in
关键字。每当你发现自己说if x == 'x' or x == 'y' or x == 'z'
时,写if x in 'xyz'
可能更容易(字符串是可迭代的,还记得吗?)。您还可以通过剥离用户可能输入的引号来消除其中两种情况 - choose.strip("'")
。f(a, b, c)
或关键字参数f(a, b=0, c=2)
以两种方式调用Python中的函数。像startup(contactlist={})
之类的调用只是将该参数显式设置为空字典,即其默认值,因此它总是等同于startup()
所定义的方式。