Python_7

  1. 1.
scoundrel={'name':'Grubby','girlfirend':'Mary'}
key,value=scoundrel.popitem()
print key
print value

这里popitem方法会弹出字典里随机的项,并以元组形式返回,那么这个元组就可以直接赋值到两个变量中。

输出结果:

girlfirend
Mary
  1. 2.
>>> x=2
>>> x+=1
>>> x*=2
>>> x
6
>>> str='fun'
>>> str+='ction'
>>> str*=2
>>> str
'functionfunction'

增量赋值语句,可以是代码更加简洁。

  1. 3.
num=input('Input a number:')
if num>0:
    print repr(num)+'>0'
    print 'Your number is >0'
elif num<0:
    print repr(num)+'<0'
    print 'Your number is <0'
else:
    print repr(num)+'=0'
    print 'Your number is =0'

条件语句的应用。

Input a number:5
5>0
Your number is >0
  1. 4.
x=[1,2,3]
y=[1,2,3]

print x==y

print x is y

“==”号比较值,“is”比较是否为同一对象。

True
False
  1. 5.

num=input('Please input a number:')
assert 0<num<10,'Input Wrong!'
print num

这里assert的作用在于检查num的值,如果没在后面第一个参数的范围内,程序直接崩溃并输出第二个参数。

  1. 6.

words=list('Hello')
for word in words:
    print word


print '-'*15
i=0
while i<5:
    print words[i]
    i+=1
print range(1,10)

简单的循环语句,while指定循环次数,for可以“量体裁衣”,按照序列中元素个数循环和range函数的使用。

H
e
l
l
o
---------------
H
e
l
l
o
[1, 2, 3, 4, 5, 6, 7, 8, 9]
  1. 7.
number={'name':'Bob','age':'42'}
for key in number:
    print key,'corresponds to',number[key]

遍历字典。

age corresponds to 42
name corresponds to Bob
  1. 8.
names=['Bob','Mary','Ruby','Smith']
ages=['12','23','24','45']
for i in range(len(names)):
    print names[i],'is',ages[i],'years old.'
print '-'*25

zip(names,ages)

for name,age in zip(names,ages):
    print name,'is',age,'years old.'

这里提供了两种方法对两个序列进行了对应输出。

Bob is 12 years old.
Mary is 23 years old.
Ruby is 24 years old.
Smith is 45 years old.
-------------------------
Bob is 12 years old.
Mary is 23 years old.
Ruby is 24 years old.
Smith is 45 years old.
  1. 9.
strings=['My', 'name', 'is', 'Bob.']
print strings

index=0
for string in strings:
    if 'name' in string:
        strings[index]='your'
    index+=1
print strings

按索引迭代,此程序为修改字符串序列中的’name’为’your’。

['My', 'name', 'is', 'Bob.']
['My', 'your', 'is', 'Bob.']
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值