1.赋值语句
1.多变量赋值
In[62]: a,b,c,d=1,2,3,4 In[63]: print(a,b,c,d) 1 2 3 4
2.交换
In[64]: a Out[63]: 1 In[65]: b Out[64]: 2 In[66]: a,b=b,a In[67]: a Out[66]: 2 In[68]: b Out[67]: 1
2.条件语句————if、elif、else:冒号,缩进(4个空格为默认)
number = 23 guess = int(input('Enter an integer : ')) # convert strings to a integer if guess == number: print('Congratulations, you guessed it.') # New block starts here print('(but you do not win any prizes!)') # New block ends here elif guess < number: print('No, it is a little higher than that') # Another block # You can do whatever you want in a block ... else: print('No, it is a little lower than that') # you must have guess > number to reach here print('Done') # This last statement is always executed, after the if statement is executed
3.循环语句————for循环
for 循环变量 in (可迭代对象):字符串、序列、元组、字典、列表等有迭代性质的对象。
通常用range对象来进行循环迭代。
In[74]: word='abcdefgh' #用字符串对象循环 In[75]: for i in word: ... print('The No.{0} letter is {1}'.format(word.index(i),i)) ... The No.0 letter is a The No.1 letter is b The No.2 letter is c The No.3 letter is d The No.4 letter is e The No.5 letter is f The No.6 letter is g The No.7 letter is h
In[76]: wordlist=['a','b','c','d','e','f'] In[77]: wordtuple=('a','b','c','d','e','f') In[78]: wordset={'a','b','c','d','e','f'} In[79]: worddic={1:'a',2:'b',3:'c',4:'d',5:'e',6:'f'} In[80]: for i in wordlist: #列表循环对象 ... print('The No.{0} letter is {1}'.format(wordlist.index(i), i)) ... The No.0 letter is a The No.1 letter is b The No.2 letter is c The No.3 letter is d The No.4 letter is e The No.5 letter is f In[81]: for i in wordtuple: #元组循环duix ... print('The No.{0} letter is {1}'.format(wordtuple.index(i), i)) The No.0 letter is a The No.1 letter is b The No.2 letter is c The No.3 letter is d The No.4 letter is e The No.5 letter is f In[82]: for i in wordset: #集合循环对象 ... print(i) ... e b d a c f In[85]: for i in worddic.keys(): #字典循环对象 ... print('The No.{0} letter is {1}'.format(i,worddic[i])) ... The No.1 letter is a The No.2 letter is b The No.3 letter is c The No.4 letter is d The No.5 letter is e The No.6 letter is f
4.range(start,end,step)对象:产生一组进行迭代的数列对象。
In[12]: a=range(10) In[13]: a Out[13]: range(0, 10) In[14]: type(a) Out[14]: range #该对象类型为range,为可迭代对象
显示用列表或元组;通常用for进行循环遍历:
In[19]: for i in range(11): ... print(i,'----->',end='') ... 0 ----->1 ----->2 ----->3 ----->4 ----->5 ----->6 ----->7 ----->8 ----->9 ----->10 ----->