Python 極速入門指南

前言

轉載於本人博客

面向有編程經驗者的極速入門指南。

大部分內容簡化於 W3School,翻譯不一定準確,因此標註了英文。

包括代碼一共兩萬字符左右,預計閱讀時間一小時。

目前我的博客長文顯示效果不佳,缺乏目錄,因此可以考慮下載閱讀。博客完全開源於 Github.

語法(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)

使用 TrueFalse,大小寫敏感。

可以強制轉換:

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\).
  • 比較運算符

    • ==
    • !=
    • >
    • <
    • >=
    • <=
  • 邏輯運算符,使用英文單詞而非符號。

    • and
    • or
    • not
  • 身份運算符?(Identity Operators)

    • is
    • is not
    • 用於判斷是否為同一個對象,即在內存中處於相同的位置。
  • 成員運算符?(Membership Operators)

    • in
    • not 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 中的基礎語法過了一遍,相信各位讀者讀完後都能入門吧。

大部分編程概念都是相似的,學習起來並不困難。這也是一個寫起來沒什麼心智負擔的工具語言。有什麼需要直接面向谷歌編程即可。

Tags: