前言
轉載于本人博客,
面向有編程經驗者的極速入門指南,
大部分內容簡化于 W3School,翻譯不一定準確,因此標注了英文,
包括代碼一共兩萬字符左右,預計閱讀時間一小時,
目前我的博客長文顯示效果不佳,缺乏目錄,因此可以考慮下載閱讀,博客完全開源于 Github.
目錄- 前言
- 語法(Syntax)
- 注釋(Comment)
- 變數(Variables)
- 數值(Number)
- 真值(Boolean)
- 條件與回圈(If...Else/While/For)
- 字串(String)
- 運算子(Operators)
- 集合(Collections)
- 陣列(List)
- 元組(Tuple)
- 集合(Sets)
- 字典(Dictionary)
- 函式(Functions)
- Lambda 運算式
- 類和物件(Classes/Objects)
- 繼承(Inheritance)
- 迭代器(Iterators)
- 定義域(Scope)
- 模塊(Modules)
- PIP
- 例外捕獲(Try...Except)
- 輸入(Input)
- 格式化字串(Formatting)
- 結語
語法(Syntax)
檔案執行方式:python myfile.py
強制縮進,縮進不能省略,縮進可以使用任意數量的空格,
if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
注釋(Comment)
注釋語法:
# Single Line Comment
"""
Multiple
Line
Comment
"""
變數(Variables)
當變數被賦值時,其被創建,
沒有顯式宣告變數的語法,
x = 5
y = "Hello, World!"
可以轉換型別,
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
可以獲得型別,
x = 5
y = "John"
print(type(x))
print(type(y))
還可以這樣賦值:
x, y, z = "Orange", "Banana", "Cherry"
x = y = z = "Orange"
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
沒有在函式中宣告的變數一律視作全域變數,
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
區域變數優先,
x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)
也可以顯式宣告全域變數,
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
由于不能區分賦值和宣告,因此如果在函式中修改全域變數,需要指明全域,
x = "awesome"
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
數值(Number)
三種數值型別:int float complex
其中復數的虛部用 j 來表示,
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
真值(Boolean)
使用 True 和 False,大小寫敏感,
可以強制轉換:
x = "Hello"
y = 15
print(bool(x))
print(bool(y))
空值一般轉換為假,例如零、空文本、空集合等,
條件與回圈(If...Else/While/For)
大于小于等于不等于跟 C 語言一致,
如果:
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
適當壓行也是可以的:
if a > b: print("a is greater than b")
三目運算子,需要注意的是執行陳述句在前面,
a = 2
b = 330
print("A") if a > b else print("B")
print("A") if a > b else print("=") if a == b else print("B")
與或:
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
if a > b or a > c:
print("At least one of the conditions is True")
如果不能為空,可以傳遞個 pass 占位,
if b > a:
pass
while 回圈很常規:
i = 1
while i < 6:
print(i)
if i == 3:
break
if i == 4:
continue
i += 1
還有個 else 的語法:
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
這個有什么用呢?其實是可以判斷自然結束還是被打斷,
i = 1
while i < 6:
break
else:
print("i is no longer less than 6")
Python 中的 for 回圈,更像是其他語言中的 foreach.
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "apple":
continue
print(x)
if x == "banana":
break
為了回圈,可以用 range 生成一個陣列,依然是左閉右開,可以預設左邊界 0.
for x in range(6): #generate an array containing 0,1,2,3,4,5
print(x)
for x in range(2, 6): #[2,6)
print(x)
可以指定步長,默認為 1.
for x in range(2, 30, 3):
print(x)
也支持 else
for x in range(6):
print(x)
else:
print("Finally finished!")
也可以拿 pass 占位,
for x in [0, 1, 2]:
pass
字串(String)
有兩種寫法:
print("Hello")
print('Hello')
好像沒什么區別,
多行字串:
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
字串可以直接當陣列用,
a = "Hello, World!"
print(a[0])
獲得長度,
a = "Hello, World!"
print(len(a))
直接搜索,
txt = "The best things in life are free!"
print("free" in txt)
print("expensive" not in txt)
if "free" in txt:
print("Yes, 'free' is present.")
if "expensive" not in txt:
print("Yes, 'expensive' is NOT present.")
幾個常用函式:
upper,大寫,lower,小寫,strip,去除兩端空格,replace,替換,split,以特定分隔符分割,
連接兩個字串,直接用加號,
a = "Hello"
b = "World"
c = a + b
print(c)
格式化:
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
可以指定引數填入的順序:
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))
轉義符:\
txt = "We are the so-called \"Vikings\" from the north."
運算子(Operators)
-
算術運算子
+-*/%,取模,**,次冪,例如2**10回傳 \(1024\).//,向下取整,嚴格向下取整,例如-11//10將會得到 \(-2\).
-
比較運算子
==!=><>=<=
-
邏輯運算子,使用英文單詞而非符號,
andornot
-
身份運算子?(Identity Operators)
isis not- 用于判斷是否為同一個物件,即在記憶體中處于相同的位置,
-
成員運算子?(Membership Operators)
innot in- 用在集合中,
-
位運算子
&|^~<<>>
集合(Collections)
陣列(List)
沒有 Array,只有 List.
thislist = ["apple", "banana", "cherry"]
print(thislist)
下標從零開始,
thislist = ["apple", "banana", "cherry"]
print(thislist[0])
還可以是負的,-1 表示倒數第一個,依此類推,
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
獲取子陣列,左閉右開,例如 [2:5] 代表 [2,5)
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
還可以去頭去尾,
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4])
print(thislist[2:])
獲得元素個數:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
元素型別都可以不同:
list1 = ["abc", 34, True, 40, "male"]
構造:
thislist = list(("apple", "banana", "cherry")) # note the double round-brackets
print(thislist)
賦值:
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)
甚至一次改變一個子陣列:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)
元素數量可以不對等,可以視作將原陣列中的 [l,r) 扔掉,然后從切口塞進去新的子陣列,
thislist = ["apple", "banana", "cherry"]
thislist[1:2] = ["blackcurrant", "watermelon"]
print(thislist)
支持插入,應該是 \(O(n)\) 復雜度的,insert(x,"something") 即讓 something 成為下標為 x 的元素,也就是插入到當前下標為 x 的元素前,
thislist = ["apple", "banana", "cherry"]
thislist.insert(2, "watermelon")
print(thislist)
尾部追加,應該是 \(O(1)\) 的,
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
直接連接兩個陣列:
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)
啥都能連接?
thislist = ["apple", "banana", "cherry"]
thistuple = ("kiwi", "orange")
thislist.extend(thistuple)
print(thislist)
洗掉,一次只刪一個,
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
按下標洗掉,可以省略引數,默認洗掉最后一個,
thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
thislist.pop()
print(thislist)
還可以用 del 關鍵字,
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
del thislist #delete the entire list
清空,陣列物件依然保留,
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)
可以直接用 for 來遍歷,
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
也可以用下標遍歷,
thislist = ["apple", "banana", "cherry"]
for i in range(len(thislist)):
print(thislist[i])
為了性能,也可以用 while 來遍歷,避免 range 生成過大的陣列,
thislist = ["apple", "banana", "cherry"]
i = 0
while i < len(thislist):
print(thislist[i])
i = i + 1
縮寫的 for 遍歷,兩邊中括號是必須的,
thislist = ["apple", "banana", "cherry"]
[print(x) for x in thislist]
賦值的時候,也有一些神奇的語法糖:
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
newlist = [x for x in fruits if "a" in x]
#Equals to
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
更抽象地:
newlist = [expression for item in iterable if condition == True]
還是比較靈活的:
newlist = [x.upper() for x in fruits]
支持直接排序,
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort()
print(thislist)
排序也有一些引數,
thislist = [100, 50, 65, 82, 23]
thislist.sort(reverse = True)
print(thislist)
可以自定義估值函式,回傳一個物件用于比較?
def myfunc(n):
return abs(n - 50)
thislist = [100, 50, 65, 82, 23]
thislist.sort(key = myfunc)
print(thislist)
還有這樣的:
thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.sort(key = str.lower) #case insensitive
print(thislist)
所以其實排序內部可能是這樣的:
if key(a) > key(b):
a,b = b,a #swap the objects
翻轉陣列:
thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.reverse()
print(thislist)
直接拷貝只能拷貝到參考,所以有拷貝陣列:
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)
也可以直接構造:
thislist = ["apple", "banana", "cherry"]
mylist = list(thislist)
print(mylist)
合并:
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
總結一下內置函式:
append,尾部追加,clear,清空,copy,生成副本,count,數數用的,extend,連接兩個陣列,index,查找第一個滿足條件的元素的下標,insert,插入,pop,按下標洗掉,remove,按值洗掉,reverse,翻轉,sort,排序,
元組(Tuple)
元組可以看作是不可修改的 List.
用圓括號包裹,
thistuple = ("apple", "banana", "cherry")
print(thistuple)
與 List 不同的是,單元素的元組宣告時,必須加一個句號,否則不會識別為元組,
myList = ["list"]
myTuple = ("tuple") #not Tuple!
myRealTuple = ("tuple",) #is Tuple!
print(type(myList))
print(type(myTuple))
print(type(myRealTuple))
構造:
thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
print(thistuple)
元組是不可變的(immutable),想要修改只能變成 List,改完再生成元組,當然這樣做效率很低,
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
當我們創建元組時,我們將變數填入,這被稱為「打包(packing)」.
而我們也可以將元組重新決議為變數,這被稱為「解包(unpacking)」.
fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits
print(green)
print(yellow)
print(red)
有趣的是,元組不能修改,卻能連接,這大概是因為運算程序產生了新的元組而作為回傳值,
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
fruits = ("apple", "banana", "cherry")
mytuple = fruits * 2 #interesting multiply <=> mytuple = fruits + fruits + ... times.
print(mytuple)
集合(Sets)
這個集合是數學意義上的集合,即具有無序性、不重復性、確定性的特性的集合,
用大括號:
thisset = {"apple", "banana", "cherry"}
print(thisset)
集合不支持下標訪問,只能遍歷:
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
不能修改元素,但可以添加元素,也可以洗掉再添加來達到修改的效果,
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
簡單的洗掉 remove,如果洗掉的元素不存在會報錯,
thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset)
如果不想要報錯,可以用 discard:
thisset = {"apple", "banana", "cherry"}
thisset.discard("banana")
print(thisset)
甚至可以用 pop,由于無序性,可能會隨機洗掉一個元素?
thisset = {"apple", "banana", "cherry"}
x = thisset.pop()
print(x)
print(thisset)
取并集,也就是合并兩個集合,需要使用 update,合并后會去重,
thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}
thisset.update(tropical)
print(thisset)
當然合并不僅限于集合之間,
thisset = {"apple", "banana", "cherry"}
mylist = ["kiwi", "orange"]
thisset.update(mylist)
print(thisset)
如果不想影響原集合,只需要回傳值,可以用 union:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)
取交集:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.intersection(y) #like union
x.intersection_update(y) #like update
print(x)
還有更有趣的,刪去交集,即 \((\mathbb{A} \cup \mathbb{B}) \setminus (\mathbb{A} \cap \mathbb{B})\)
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.symmetric_difference(y)
x.symmetric_difference_update(y)
print(x)
清空和徹底洗掉:
thisset = {"apple", "banana", "cherry"}
thisset.clear()
print(thisset)
del thisset
print(thisset)
字典(Dictionary)
類似于 C++ 中的 map,鍵值對,
3.7 以上的 Python 版本中,字典是有序的,有序性、可變性、不重復性,
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
print(thisdict["brand"])
print(thisdict.get("model")) #the same with the former approach
有趣的是,值可以是任意資料型別,
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
獲取所有 key:
x = thisdict.keys()
值得注意的是,這里傳出的是一個參考,也就是說是可以動態更新的,但似乎是只讀的,
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.keys()
print(x) #before the change
car["color"] = "white"
print(x) #after the change
values 也是一樣的:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
print(x) #before the change
car["year"] = 2020
print(x) #after the change
還可以直接獲取所有鍵值對 items:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.items()
print(x) #before the change
car["year"] = 2020
print(x) #after the change
可以查看鍵是否存在:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
可以用 update 來更新,支持塞入一個鍵值對集合:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
another = {
"another": "Intersting",
"stuff": "Join it"
}
thisdict.update({"year": 2020})
print(thisdict)
thisdict.update(another)
print(thisdict)
移除特定鍵:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
移除最后一個鍵值對:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)
thisdict.update({"new":"I'm newer"})
print(thisdict)
thisdict.popitem()
print(thisdict)
可以用 del 關鍵字:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
清空:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)
遍歷所有鍵名:
for x in thisdict:
print(x)
遍歷所有值:
for x in thisdict:
print(thisdict[x]) #have to search for the value each time executed
直接獲取集合來遍歷:
for x in thisdict.values():
print(x)
for x in thisdict.keys():
print(x)
遍歷鍵值對:
for x, y in thisdict.items():
print(x, y)
深拷貝:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy()
print(mydict)
mydict = dict(thisdict)
print(mydict)
嵌套:
child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}
myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}
print(myfamily["child1"]["name"])
函式(Functions)
函式定義:
def my_function():
print("Hello from a function")
my_function()
引數:
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
形參(Parameter)和實參(Argument).
不定長引數:
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")
可以用更優雅的方式傳參:
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")
實質上是鍵值對的傳遞,因此:
def my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname = "Tobias", lname = "Refsnes")
默認引數:
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
弱型別,啥都能傳:
def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
回傳值:
def my_function(x):
return 5 * x
占位符:
def myfunction():
pass
Lambda 運算式
只能有一行運算式,但可以有任意個數引數,
lambda arguments : expression
例如一個自增 \(10\) 的函式:
x = lambda a : a + 10
print(x(5))
多引數:
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
有趣的是,可以利用 Lambda 運算式構造匿名函式:
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
類和物件(Classes/Objects)
Python 是一個面向物件(Object Oriented)的語言,
class MyClass:
x = 5
p1 = MyClass()
print(p1.x)
初始化:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
宣告方法:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
函式的第一個引數將會是指向自己的參考,并不強制命名為 self.
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc()
可以洗掉某個屬性:
del p1.age
可以洗掉物件:
del p1
占位符:
class Person:
pass
繼承(Inheritance)
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
#Use the Person class to create an object, and then execute the printname method:
x = Person("John", "Doe")
x.printname()
class Student(Person):
def __init__(self, fname, lname, year): # overwrite parent's __init__
super().__init__(fname, lname)
# <=> Person.__init__(self, fname, lname)
self.graduationyear = year
def welcome(self):
print("Welcome", self.firstname, self.lastname,
"to the class of", self.graduationyear)
def printname(self):
super().printname()
print("plus {} is a student!".format(self.lastname))
x = Student("Mike", "Olsen", 2020)
x.welcome()
x.printname()
迭代器(Iterators)
一個迭代器需要有 __iter__ 和 __next__ 兩個方法,
所有的集合都能提供迭代器,都是可遍歷的(Iterable Containers).
mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)
print(next(myit))
print(next(myit))
print(next(myit))
創建一個迭代器:
class MyNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
if self.a <= 20:
x = self.a
self.a += 1
return x
else:
raise StopIteration #Stop iterating
myclass = MyNumbers()
myiter = iter(myclass)
for x in myiter:
print(x)
定義域(Scope)
函式中宣告的變數只在函式中有效,
def myfunc():
x = 300
print(x)
myfunc()
事實上,它在該函式的域內有效,
def myfunc():
x = 300
def myinnerfunc():
print(x)
myinnerfunc()
myfunc()
全域變數:
x = 300
def myfunc():
print(x)
myfunc()
print(x)
更多有關全域變數的前文已經說過,這里復習一下,
x = 300
def myfunc():
global x
x = 200
def myfunc2():
x = 400
print(x)
myfunc()
myfunc2()
print(x)
模塊(Modules)
調庫大法好,
舉個例子,在 mymodule.py 中保存以下內容:
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
def greeting(name):
print("Hello, " + name)
然后在 main.py 中運行:
import mymodule
mymodule.greeting("Jonathan")
a = mymodule.person1["age"]
print(a)
可以起別名(Alias):
import mymodule as mx
a = mx.person1["age"]
print(a)
有一些內置的模塊:
import platform
x = platform.system()
print(x)
x = dir(platform)
print(x)
可以指定參考模塊的某些部分,此時不需要再寫模塊名:
from mymodule import person1
print (person1["age"])
#print(mymodule.person1["age"]) WRONG!!
也可以起別名:
from mymodule import person1 as p1
print (p1["age"])
PIP
包管理器,
安裝包:pip install <package-name>
例如:pip install camelcase
然后就能直接使用了:
import camelcase
c = camelcase.CamelCase()
txt = "hello world"
print(c.hump(txt))
例外捕獲(Try...Except)
比較常規,
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
else:
print("Nothing went wrong")
finally:
print("Ended.")
舉個例子:
try:
f = open("demofile.txt")
f.write("Lorum Ipsum")
except:
print("Something went wrong when writing to the file")
finally:
f.close()
拋出例外:
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
可以指定型別:
x = "hello"
if not type(x) is int:
raise TypeError("Only integers are allowed")
輸入(Input)
很簡單的輸入,
username = input("Enter username:")
print("Username is: " + username)
格式化字串(Formatting)
前文已經簡單提及了,
price = 49
txt = "The price is {} dollars"
print(txt.format(price))
可以指定輸出格式:
quantity = 3
itemno = 567
price = 49
myorder = "I want {0} pieces of item number {1} for {2:.2f} dollars."
print(myorder.format(quantity, itemno, price))
可以重復利用:
age = 36
name = "John"
txt = "His name is {1}. {1} is {0} years old."
print(txt.format(age, name))
可以傳鍵值對:
myorder = "I have a {carname}, it is a {model}."
print(myorder.format(carname = "Ford", model = "Mustang"))
結語
差不多把 Python 中的基礎語法過了一遍,相信各位讀者讀完后都能入門吧,
大部分編程概念都是相似的,學習起來并不困難,這也是一個寫起來沒什么心智負擔的工具語言,有什么需要直接面向谷歌編程即可,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/282532.html
標籤:其他
