2a, b = b, a # 實現了對兩個數的交換
a, b
(2, 1)
name =
'jack'
country =
'china'
age =
18# 1. 傳統的字串拼接(很繁雜)
print
("hi, i'm "
+ name +
". i'm from "
+ country +
". and i'm "
+str
(age)
+" years old."
)# 2. 百分號語法
print
("hi, i'm %s. i'm from %s. and i'm %d years old."
%(name, country, age)
)# 3. format函式
print
("hi, i'm {}. i'm from {}. and i'm {} years old."
.format
(name, country, age)
)# print("hi, i'm . yes, i'm !".format(name, country, age)) # 索引0為第乙個引數
# 4. f-string寫法
print
(f"hi, i'm . i'm from . and i'm years old."
)
hi, i'm jack. i'm from china. and i'm 18 years old.
hi, i'm jack. i'm from china. and i'm 18 years old.
hi, i'm jack. i'm from china. and i'm 18 years old.
hi, i'm jack. i'm from china. and i'm 18 years old.
# 傳統寫法
deffibo
(n):
a =0 b =
1 nums =
for _ in
range
(n):
a, b = b, a+b
return nums
for i in fibo(6)
:print
(i)
011235
# 用yield函式
deffibo_y
(n):
a =0 b =
1for _ in
range
(n):
yield a
a, b = b, a+b
for i in fibo_y(6)
:print
(i)
011235
# 傳統寫法
fruit =[,
'pear',,
'orange'
,'banana'
]for i in
range
(len
(fruit)):
fruit[i]
= fruit[i]
.upper(
)
fruit
# 簡潔寫法
fruits =[,
'pear',,
'orange'
,'banana'
]fruits =
[x.upper(
)for x in fruits]
fruits
# 挑選出以『p』字母開頭的元素
fruits =[,
'pear',,
'orange'
,'banana'
]filtered_fruits =
[x for x in fruits if x.startswith(
'p')
]
filtered_fruits
fruits =[,
'pear',,
'orange'
,'banana'
]for i, x in
enumerate
(fruits)
:print
(i, x)
1 pear
3 orange
4 banana
fruits =[,
'pear',,
'orange'
,'banana'
]for i, x in
enumerate
(reversed
(fruits)):
print
(i, x)
0 banana
1 orange
3 pear
fruits =[,
'pear',,
'orange'
,'banana'
]for i, x in
enumerate
(sorted
(fruits)):
print
(i, x)
1 banana
2 orange
3 pear
a =
b =c =
c
score =[56
,63,80
,20,100
]s =
['pass'
if x>
60else
'fail'
for x in score]
s
['fail', 'pass', 'pass', 'fail', 'pass']
name =
'jack tim'
first_name, last_name = name.split(
)first_name, last_name
('jack', 'tim')
# 傳統寫法
f =open
('haha.txt'
,'r'
)s = f.read(
)f.close(
)# 不可省略,會占用資源
# with語句
with
open
('haha.txt'
,'r'
)as f:
s = f.read(
)
10個Python小技巧
flag true if flag x 1else x 2print x 簡化形式 flag true x 1 if flag else 2 print x sum 0 for i in range 0,101 sum i print sum 利用求和函式sum print sum range 0,...
10個程式設計技巧
很長一段時間以來,我都在關注如何提高 質量,也為此做過一些嘗試,我想這個話題可能大家會比較感興趣,在這裡分享一下我關於如何提高 質量的一些體會。你知道怎麼寫高質量 嗎?不要一上來就開始寫 想清楚再動手,下面分享10個寫 的小技巧教你寫出高質量 1 重構思維模式 不要一上來就開始寫 要掌握盡量多的重構...
10個jQuery小技巧
收集的10個 jquery 小技巧 片段,可以幫你快速開發。1.返回頂部按鈕 你可以利用animate和scrolltop來實現返回頂部的動畫,而不需要使用其他外掛程式。1 a.top click function 800 3return false 4 改變scrolltop的值可以調整返回距離頂...