五. 語句與語法:語句

輸入輸出

s = input() 接收輸入,接收爲str型
input(‘提示’) 先輸出提示信息
print(‘=’ * 20) 輸出20次 =
print(n,b,v,sep=’ - ’) 用-分隔n,b,v並輸出
print(1, 2, 3, 4, sep=’\n’, end=’ end’) 用換行分隔,最後輸出end
print(‘f={:08,.4f}’.format(math.pi * 10000)) -> f=31,415.9265

語句

賦值

x = 1
name, age = ‘tom’, 20
等同於:(name, age) = (‘tom’, 20) 本質爲元組賦值
[name, age] = [‘tom’, 20] 本質爲列表賦值
a,b,c,d=’abcd’ -> a=’a’ b=’b’ c=’c’ d=’d’ 前後數量要一致
a,*b=’abcd’ -> a=’a’ b=’bcd’
a,*b,c=’abcd’ -> a=’a’ b=’bc’ c=’d’
多目標賦值:a = b = 5
b += 10 -> b = b + 10

交換值:a,b = b,a

  1. 賦值創建對象引用
  2. 名稱創建與首次賦值
  3. 名稱引用前必須賦值
  4. 某些操作會執行隱式賦值

函數調用

import math
math.pow(x,2)

條件判斷

if
if x > 3 :
print(‘大於3’)

if…else
score = 55
if score >= 60:
    print('passed')
else:
print('failed')

if …elif…else
score = 85

if score >= 90:
    print('excellent')
elif score >= 80:
    print('good')
elif score >= 60:
    print('passed')
else:
print('failed')

這一系列條件判斷會從上到下依次判斷,如果某個判斷爲 True,執行完對應的代碼塊,後面的條件判斷就直接忽略,不再執行了。

迭代

  1. Python 的 for循環不僅可以用在list或tuple上,還可以作用在其他任何可迭代對象上
  2. 迭代操作就是對於一個集合,無論該集合是有序還是無序,我們用 for 循環總是可以依次取出集合的每一個元素。
  3. 迭代永遠是取出元素本身,而非元素的索引
  4. 使用 enumerate() 函數,我們可以在for循環中同時綁定索引和元素。
    image.png
L = ['Adam', 'Lisa', 'Bart', 'Paul']
for index, item in zip(range(1,len(L) + 1),L):
print index, '-', item

for…in..
for i in range(1,4):
print(i)

L = [75, 92, 59, 68]
sum = 0.0
for sc in L:
    sum += sc
print(sum / 4)

while
sum = 0
x = 1
while x <= 100:
    if x % 2 == 1:
        sum += x
print(sum)
break
sum = 0
x = 1
n = 1
while True:
    if x > 20:
        break
    sum += 2 ** (x -1)
    x += 1
print(sum)

continue
sum = 0
x = 0
while True:
    x += 1 
    if x > 100:
        break
    if x % 2 == 0:
        continue
    sum += x
print sum

多重循環

for x in range(10):
    for y in range(10):
        if x < y:
            print(x * 10 + y)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章