主頁 > 後端開發 > Python 極速入門指南

Python 極速入門指南

2021-05-04 07:27:27 後端開發

前言

轉載于本人博客,

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

大部分內容簡化于 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)

使用 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 中的基礎語法過了一遍,相信各位讀者讀完后都能入門吧,

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

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/282532.html

標籤:其他

上一篇:SpringCloud(五)GateWay網關

下一篇:2021Q1最受歡迎語言,你get到了嗎?

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more