python的&众不同之处(2)

list列表

定义

>>> classmates = ['Michael', 'Bob', 'Tracy']
>>> classmates
['Michael', 'Bob', 'Tracy']

添加元素

>>> classmates.append('Adam')
>>> classmates
['Michael', 'Bob', 'Tracy', 'Adam']

把元素插入到指定的位

>>> classmates.insert(1, 'Jack')
>>> classmates
['Michael', 'Jack', 'Bob', 'Tracy', 'Adam']

删除指定位置的元素

>>> classmates.pop(1)
'Jack'
>>> classmates
['Michael', 'Bob', 'Tracy']

要把某个元素替换成别的元素

>>> classmates[1] = 'Sarah'
>>> classmates
['Michael', 'Sarah', 'Tracy']

tuple元组

tuple一旦初始化就不能修改

>>> classmates = ('Michael', 'Bob', 'Tracy')

一个元素时定义方法

>>> t = (1,)
>>> t
(1,)

if条件判断

age = 3
if age >= 18:
    print 'adult'
elif age >= 6:
    print 'teenager'
else:
    print 'kid'

for循环

sum = 0
for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
    sum = sum + x
print sum

while循环

sum = 0
n = int(raw_input('n: '))
while n > 0:
    sum = sum + n
    n = n - 2
print sum

python函数

range()函数,可以生成一个整数序

>>> range(5)
[0, 1, 2, 3, 4]

学习参考

http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000

猜你喜欢

转载自blog.csdn.net/sinat_33859977/article/details/52565336
今日推荐