2017-10-13  526 views 评论

Python chapter 4 learning notes

1.      About loop

·        Indentation means these sentences or this sentence  belong(s) to this loop.Such as,

magicians=['david','joe','kite','john']

for magician in magicians:# loop

print(magician.title() + ', you have been invited.')

print("I can't wait to see your next trick, "+ magician.title() + '\n')

·        After loop, a non-indented sentence means it doesn't belongs to this loop.

·        DO NOT FORGET THE":" AFTER YOU WRITE THE FOR xxx

2.      About numerical list

·        Use range()

o   If you want to print one to five, you need to use range(1,6).DO NOT FORGET IT.

For example,

for value in range(1,6):

print(value)

range(a,b,m), a means the start point, b means the end point, and m means step length.

For example,

o  After you input range(1,6,2), you can see [1,3,5].

o  Use range() and list() to make up a list

For example,

numbers=list(range(1,11))

print(numbers)

If you use list(range(1,11,2)), you can see [1,3,5,7,9].

power operation just like a**2,using **.

·        Some simple functions

·        min(digits) means figure out the mnimum.

·        max(digits) means figure out the max number.

·        sum(digits) means figure out the sum.

·        List Comprehensions(列表解析)

For example,

data=[valu**3 for valu in range(2,12,2)]

print(data)

Using part of list: Slice

·        Some ways:

o   print str[0:3] #截取第一位到第三位的字符

o   print str[:] #截取字符串的全部字符

o   print str[6:] #截取第七个字符到结尾

o   print str[:-3] #截取从头开始到倒数第三个字符之前

o   print str[2] #截取第三个字符

o   print str[-1] #截取倒数第一个字符

o   print str[::-1] #创造一个与原字符串顺序相反的字符串

o   print str[-3:-1] #截取倒数第三位与倒数第一位之前的字符

o   print str[-3:] #截取倒数第三位到结尾

o   print str[:-5:-3] #逆序截取

·        Copy list:

If we want to copy the elements of one list to another list, we need to do as followed:

my_foods = ['apple','banana','cake']

friend_foods = my_foods[:]#如果没有[:]那就意味着只是将my_foods的地址指向friend_foods,这样的话,如果更改前者元素后者也会更改

print(my_foods)

print(friend_foods)

my_foods.append("water melon")

friend_foods.append("monga")

print(my_foods)

print(friend_foods)

We can see that firend_foods is different from my_foods.

Tuple(元组)

list is unchangeable, so sometime we need a tuple. Tuple is changeable.

define a tuple like this: dimensions=(200,50). We do not use [].

The elements of tuple cannot be changed, but we can assign.

In addition , tuple is as same as list.

给我留言

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: