iT邦幫忙

2021 iThome 鐵人賽

DAY 4
1
自我挑戰組

Python 30天自我挑戰系列 第 4

Day04 - Python基本語法 Part 1

今天開始將進行Python基本語法練習,因大部分語法跟很多程式語言相似,故這個部分將主要以筆記方式註記重點,做為未來的備忘錄。
補充說明:部分範例程式來自於W3Schools

Python特色

  1. 直譯式語言,不需要事先編譯。
  2. 可讀性高,更接近於一般英文語句。
  3. 使用換行符號區隔指令。 (大部分程式語言多使用「;」做結尾)
  4. 使用空格界定範圍。 (大部分程式語言多使用括號界定範圍)
if 2>1:
  print("2>1")
  print("First Part")
else:
  print("Else Part")  

註解

  • 單行註解
#This is a comment
  • 多行註解
"""
Comment 1
Comment 2
Comment 3
"""

變數

  • 變數型態依指派的資料型態而定
  • 顯示變數型態
x = 4
y = "Test"
print(type(x))
print(type(y))
  • 變數型態會依後續指派的數值型態自動轉變
x = 4
print(type(x))
x = "Test"
print(type(x))
  • 指派時宣告型態
x = str(1)
print(type(x))
x = int(1)
print(type(x))
x = float(1)
print(type(x))
  • 一次指派多個變數不同的值
x, y, z = "A", "B", "C"
  • 一次指派多個變數相同的值
x = y = z = "A"
  • 將數值集合拆分指派至多個變數
testSet = ["A","B","C"]
x, y, z = testSet

資料型態

  • Text Type:str

  • Numeric Types:int, float, complex

x = 1   # 數值
y = "j" # 文字
z = 1j  # 複合型態
print(type(x))
print(type(y))
print(type(z))
  • Sequence Types:list, tuple, range
x = ["A","B","C"]  # list
y = ("A","B","C")  # tuple
z1 = range(1, 7)   # range
z2 = range(7)      # range
  • Mapping Type:dict
employee = {"id": 1, "name": "Alice"}
print(employee)
print(employee["name"])
  • Set Types:set, frozenset
x = {"A","B","C"}             # set
x = frozenset({"A","B","C"})  # frozenset
  • Boolean Type: bool
x = True
y = False

使用bool()可以將各種型態的變數轉換為bool型態。
判斷為False的情境:

  1. 文字:空字串
  2. 數字:0
  3. 集合:空集合
  4. Binary Types:bytes, bytearray, memoryview

亂數

需要使用Random模組

import random
print(random.randrange(1,10))

字串處理

因重點較多故另外整理出來。

  • 多行字串指派:使用"""或'''都可以
x = """Line 1.
Line 2.
Line 3.
"""

y = '''Line 4.
Line 5.
Line 6.
'''

print(x)
print(y)
  • 字串長度
a = "Test"
print(len(a))
  • 判斷字串是否存在於另一個字串
x = "Hello World"
print("World" in x)
  • 取出子字串
    以矩陣中的指標範圍處理,寫法:array[startIndex:endIndex]。
    注意:endIndex不包含在選取範圍內
x = "Hello World"
print(x[2:5])
print(x[:5])
print(x[2:])
print(x[-5:-2])

https://ithelp.ithome.com.tw/upload/images/20210916/20141886l7T9xemYxn.png

  • 字串修改
x = "   Hello World    !"
print(x.lower())  # 轉換為小寫
print(x.upper())  # 轉換為大寫
print(x.strip())  # 移除頭尾的空白
print(x.replace("l", "L"))  # 取代
print(x.split(" "))  # 字串分隔

https://ithelp.ithome.com.tw/upload/images/20210916/20141886RnpbSdKO6i.png

  • 字串合併
x = "Hello "
y = "World"
z = x + y
print(z)
  • format
    因字串和數字不能以「+」直接合併,可透過format的寫法,讓數值變數取代該字串中特定位置,以達到字串和數字合併的效果。
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))

可以使用index來指定欲取代的變數。

quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))

上一篇
Day03 - Visual Studio Code安裝Python插件
下一篇
Day05 - Python基本語法 Part 2,關於「集合」
系列文
Python 30天自我挑戰30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言