当我们需要一个数列,特别是等差数列,这个时候就可以使用range函数:
range(start,end,step)
range(start,end) #默认步长为1
range(end) #默认start = 0, step = 1;
>>> list(range(3,11,2))
[3,5,7,9]
默认参数都必须写在后面,不允许出现如下情况:
def (x = false,y):
balabala
def my_add(x,y) :
return x+y
等价于:
my_add = lambda x,y : x + y
一般的来说,同一个问题使用递归方案会比使用循环方案更消耗资源(时间,内存),但是有些问题目前只有递归方案解决,例如汉诺塔问题。
def hanoi(a,b,c,n): #借助b将n个盘子从a搬动到c
if n == 1:
print(a,'->',c)
else:
hanoi(a,c,b,n-1) #借助c将n-1个盘子从a搬动到b
print(a,'->',c) #把a的最大的盘子搬动给c
hanoi(b,a,c,n-1) #然后将b上的n-1个盘子借助a移动到c
hanoi('a','b','c',4)
for iter_var in iterable_object:
suite_to_repeat
其中,iterable_object
一般是这么几类(要求是可迭代对象):
- String
- List
- Tuple
- Dictionary
- File
from math import sqrt
num = int(input('please enter a number:'))
j = 2
while j <= int(sqrt(num)):
if num % j == 0:
print('{:d} is not a prime.'.format(num))
break
j += 1
else: #python中else可以和while、for连接,在“正常完成循环”时,执行语句
print('{:d} is a prime.'.format(num))
多重赋值PI,r = 3.14,4的本质由两个步骤构成:
>>>temp = 3.14,4 #元组打包(Tuple packing)
>>>PI,r =3.14,4 #序列解包(Sequence unpacking)
>>> round(3.4)
3
>>> round(4.6)
5
>>> round(3.5)
4
>>> round(2.5)
2
import collections
Card = collections.namedtuple('Card',['rank','suit'])
class FrenchDeck:
ranks = [str(n) for n in range(2,11)] + list('JQKA')
suits = 'spades diamonds clubs hearts'.split()
def __init__(self):
self._cards = [Card(rank,suit) for suit in self.suits for rank in self.ranks]
def __len__(self):
return len(self._cards)
def __getitem__(self,position):
return self._cards[position]
deck = FrenchDeck()
a = len(deck)
b = deck.__getitem__(51)
print(a)
print(b)
Python 类与元类的深度挖掘这个讲得容易懂。