python語法31[基本數據類型和流程控制]
所有類型如下圖:

一 基礎數據類型
1)數字類型
>>> 2/2+2*2
5.0
>>> (50-5*6)/4
5.0
>>> 8/5
1.6
>>> 8//5
1
>>> x=y=1.5
>>> x*y
2.252)string類型
>>> 'hello world'
'hello world'
>>> "hello world"
'hello world'
>>> "doesn't"
"doesn't"
>>> 'hello "tom"'
'hello "tom"'
>>> "hello,\"tom\""
'hello,"tom"'
>>> hello="hello,\
i miss you."
>>> print(hello)
hello,i miss you.
>>> print(r"hello\n world")
hello\n world
>>> word='hello'+'A'
>>> print(word)
helloA
>>> word[0:5]+'B'
'helloB'
>>> word[-1]
'A'
>>> len(word)
6單引號''和雙引號""作用相同,都用來表示字符串,但是單引號''中可以有雙引號"",雙引號""中也可以有單引號'',但是如果雙引號""中使用雙引號""或是單引號''中使用單引號''時,必須使用轉義字符\,例如\'或\"。
行末尾\表示字符串換行。
字符串前的r表示純字符串,此時字符串中的轉義字符失效。
+表示字符串的鏈接。
[]可以用來索引字符串中的字符,但是不能用來修改字符串中的字符。
len()用來獲得字符串的長度。
3)List
>>> a = ['money', 'money', 'money', 100000000]
>>> a
['money', 'money', 'money', 100000000]
>>> a[3]
100000000
>>> a[-1] = a[-1] * 2
>>> a[-1]
200000000
>>> ['i', 'want'] + a
['i', 'want', 'money', 'money', 'money', 200000000]
>>> a
['money', 'money', 'money', 200000000]
>>> a[:0] = ['i', 'want']
>>> a
['i', 'want', 'money', 'money', 'money', 200000000]
>>> a[2:4] = []
>>> a
['i', 'want', 'money', 200000000]
>>> len(a)
4
>>> a[:]= []
>>> a
[]
>>> list中可以包含任何不同的數據類型。
[]可以修改list中的元素。
+可以用來list的合并。
=[]可以用來刪除list中某些元素。
len可以用來獲得list的長度。
二 流程控制關鍵字
注意:Python中使用冒號:和語句前的空格對其齊表示其他語言中的{和}所表示的語句塊的開始和結束。
1)if/else
x = int(input("Please enter an integer: "))
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
print('More')2)for
a = ['cat', 'window', 'defenestrate']
for x in a[1:]:
print(x, len(x))
if len(x) > 6: a.insert(0, x)
print(a)
b = ['Mary', 'had', 'a', 'little', 'lamb']
for i in range(len(b)):
print(i, b[i])3)while
a, b = 0, 1
while b < 10:
print(b)
a, b = b, a+b4)Continue/Break/Pass
for i in range(100):
if(i%5 == 0):
print(i);
continue;
elif(i >= 50):
print("over");
break;
else:
pass;
print("thanks")


浙公網安備 33010602011771號