Python学习笔记4.拆包、字典

拆包(元组中)

co=(1,2,3)
x,y,z=co
print(x)

自动将1分配给x,以此类推


字典

customer = {
    "name":"John Smith",
    "age":30,
    "is_verified":True
}//定义方法,前面的是关键字,必须唯一
print(customer["name"])
//访问
customer["name"]="Jack Smith"
//可更改
print(customer.get("name"))
//另一种访问方法
print(customer.get("birthday"))
//若用get方法访问不存在的关键字,将返回None,用第一种访问方法将报错
print(customer.get("birthday"),"2008")

//可赋值不存在的关键字

执行:

John Smith
Jack Smith
None
None 2008

进程已结束,退出代码为 0



字典练习:翻译

用户输入电话号码,翻译为英文单词并输出

phone=input("phone:")
dict={
    "1":"one",
    "2":"two",
    "3":"three",
    "4":"four"
}
output=""
for i in phone:
    output+=dict.get(i,"!")+" "//注意,“”里带空格,以便输出时可以分开
print(output)

执行示例:

phone:1234
one two three four 

进程已结束,退出代码为 0




一个有趣的小示例:

用户输入happy或者sad,替换成表情符,输出

message = input(">")
words=message.split(' ')
print(words)//这两行将输入的词以空格为边界分开,形成列表,可以查看

emojis={
    "happy":":)",
    "sad":":("
}
output=""
for i in words:
    output+=emojis.get(i,i)+" "
print(output)

执行结果:

>i am happy
['i', 'am', 'happy']
i am :) 

进程已结束,退出代码为 0

>i am so sad
['i', 'am', 'so', 'sad']
i am so :( 

进程已结束,退出代码为 0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值