本文摘自:https://www.cnblogs.com/scios/p/8108243.html
#!/usr/bin/python
# -*- coding:UTF-8 -*-
print('''|---welcome contacts---|
|---1 query contacts---|
|---2 insert contacts---|
|---3 delete contacts---|
|---4 exit contacts---|''')
addressBook={}
while 1:
temp=raw_input('please input number:')
if not temp.isdigit():
print('input error,please input again:')
continue
item=int(temp)
if item==4:
print("thanks for using addressBook!")
break
name=raw_input("please input name:")
if item==1:
if name in addressBook:
print(name,":",addressBook[name])
continue
else:
print("addressBook has no this name!")
if item==2:
if name in addressBook:
print("addressBook has this name-->>",name,":",addressBook[name])
isEdit=input("is modify information(Y/N):")
if isEdit=='Y':
userphone=input("please input phone number:")
addressBook[name]=userphone
print("modify success!")
continue
else:
continue
else:
userphone=input("please input phone number:")
addressBook[name]=userphone
print("modify success!")
continue
if item==3:
if name in addressBook:
del addressBook[name]
print("delete success!")
else:
print("addressBook has no this name!")
print addressBook
print addressBook.keys()
print addressBook.items()
输出:
|---welcome contacts---|
|---1 query contacts---|
|---2 insert contacts---|
|---3 delete contacts---|
|---4 exit contacts---|
please input number:2
please input name:bob
please input phone number:10086
modify success!
please input number:2
please input name:lili
please input phone number:11110
modify success!
please input number:2
please input name:Sam
please input phone number:10010
modify success!
please input number:4
thanks for using addressBook!
{'bob': 10086, 'lili': 11110, 'Sam': 10010}
['bob', 'lili', 'Sam']
[('bob', 10086), ('lili', 11110), ('Sam', 10010)]
需要注意:
1、isdigit()用于字符串的检测:
-
str.
isdigit
(
)
-
Return true if all characters in the string are digits and there is at least onecharacter, false otherwise.
2、啥时候用raw_input()啥时候用input()?
字符的时候可以用raw_input()
int类型的时候最好用input()
3、访问字典元素
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}; print "dict['Name']: ", dict['Name']; print "dict['Age']: ", dict['Age']; #以上实例输出结果: #dict['Name']: Zara #dict['Age']: 7
4、字典内置函数
radiansdict.clear() #删除字典内所有元素
radiansdict.copy() #返回一个字典的浅复制
radiansdict.fromkeys() #创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值
radiansdict.get(key, default=None) #返回指定键的值,如果值不在字典中返回default值
radiansdict.has_key(key) #如果键在字典dict里返回true,否则返回false
radiansdict.items() #以列表返回可遍历的(键, 值) 元组数组
radiansdict.keys() #以列表返回一个字典所有的键
radiansdict.setdefault(key, default=None) #和get()类似, 但如果键不已经存在于字典中,将会添加键并将值设为default
radiansdict.update(dict2) #把字典dict2的键/值对更新到dict里
radiansdict.values() #以列表返回字典中的所有值