赋值语句,print和import的一些特性

1.打印多个表达式,只要将它们用逗号隔开就好
>>> print('age: ',42)
age:  42
>>> print(1,2,3)
1 2 3
>>> print((1,2,3))
(1, 2, 3)
2.如果想要同时输出文本和变量的值,却又不希望使用字符串格式化,可以用这个特性来操作
>>> name = 'Gumby'
>>> salutation  = 'Mr.'
>>> greeting = 'Hello,'
>>> print(greeting,salutation,name)
Hello, Mr. Gumby
>>> greeting = 'Hello'
>>> print(greeting,',',salutation,name)        #这样也能实现逗号
Hello , Mr. Gumby
>>> print(greeting + ',',salutation ,name)
Hello, Mr. Gumby
3.功能导入
import somemodule
form somemodule import somefunction
form somemodule import somefunction,anothfunction,yetanotherfunction
from somemodule import *
如果两个模块都有open函数
module1.open(...)
module2.open(...)
还可以为整个模块或函数提供别名
>>> import math as foobar
>>> foobar.sqrt(4)
2.0
>>> from math import sqrt as foobar
>>> foobar(4)
2.0
对与open函数还可以这样操作
from module1 import open as open1
from module2 import open as open2
4.序列解包
>>> x,y,z = 1,2,3
>>> print(x,y,z)
1 2 3
>>> x,y = y,x        #交换两个(或多个)变量也是没问题的
>>> print(x,y,z)
2 1 3
>>> values = 1,2,3
>>> values
(1, 2, 3)
>>> x,y,z = values        当函数或方法返回元组时,这个特性尤其有用
>>> x
1
当函数或方法返回元组时,这个特性尤其有用,它允许函数返回一个以上的值并且打包成元组,然后通过一个赋值语句很容易进行访问
>>> scoundrel = {'name':'Robin','girlfriend':'Marion'}
>>> key,value = scoundrel.popitem()        #所解包的序列中元素数必须和放置在赋值符号=左边的变量
>>> key                                                     #数量完全一致
'girlfriend'
>>> value
'Marion'
在Python3.x中有另外一个解包特性:可以像在函数的参数列表中一样使用星号运算符
>>> a,b,*rest = [1,2,3,4]
>>> a
1
>>> b
2
>>> rest        #是一个列表
[3, 4]
5.链式赋值
x = y = somefunction()
6.增量赋值
>>> x = 2
>>> x += 1
>>> x *= 2
>>> x
6
>>> fnord = 'foo'        #对其他数据类型也适用(只要二元运算符本身适用于这些数据类型即可)
>>> fnord += 'bar'
>>> fnord *= 2
>>> fnord
'foobarfoobar'
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值