Name | Type | Note |
---|---|---|
integer | int | -1,-2,0,1,2 (整數) |
floating point | float | -1.1, 0.3, 1.2 (浮點數) |
boolean | bool | True / False (布林值) |
Numeric type(數值型態): int, float, bool
String type(字串型態) : str
iv = 10 # 將整數 10 指派給變數 iv
fv = 12.3 # 將浮點數 12.3 指派給變數 fv
sv = 'hello python' # 將字串 'hello python' 指派給變數 sv
bv = True # 將布林值 True 指派給變數 bv
print('iv :', iv, '; fv :', fv, '; sv :', sv, '; bv :', bv)
print(type(iv)) # type(iv)會得到 iv 的形態 ==> int
print(type(fv)) # type(fv)會得到 fv 的形態 ==> float
print(type(sv)) # type(sv)會得到 sv 的形態 ==> str
print(type(bv)) # type(bv)會得到 bv 的形態 ==> bool
iv : 10 ; fv : 12.3 ; sv : hello python ; bv : True
<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>
不同型態間的運算,自動轉換成範圍比較大的型態
int < float
print(4 + 2) # 6
print(4.0 + 2) # 6.0
print(4.0 + 2.0) # 6.0
print(2 / 5) # 0.4
print(2.0 / 5) # 0.4
print(2 / 5.0) # 0.4
print(2.0 / 5.0) # 0.4
print(2 // 5) # 0
Declaring Strings in Python (在 Python 中宣告字串)
Use single quotes: '...'
Or double quotes: "..."
What is a String? (什麼是字串?)
A sequence of characters (一串字)
str1 = '12345' # 用 '...' 宣告字串 str1
str2 = "hello world" # 用 "..." 宣告字串 str2
print(f"str1 is {str1} {type(str1)}") # 印出 str1 的內容與型態
print(f"str2 is {str2} {type(str2)}") # 印出 str2 的內容與型態
str1 is 12345 <class 'str'>
str2 is hello world <class 'str'>
Example | String? |
---|---|
“2” | Yes ✅ |
‘3.6’ | Yes ✅ |
“True” | Yes ✅ |
7 | No ❌ |
HELLO | No ❌ |
True | No ❌ |
程式中的第一個引號 ' 視為字串的開始,並將第二個引號 ' 視為字串的結束
Python sees the string as starting with the first single quote and ending with the apostrophe in "I'm",
' I'm learning Python! ' # 用 '...' 宣告的字串有 '
File "<ipython-input-36-f8fc62258cda>", line 1
' I'm learning Python! ' # 用 '...'' 宣告的字串有 ''
^
SyntaxError: invalid syntax
👆
👆
程式中的第一個引號 " 視為字串的開始,並將第二個引號 " 視為字串的結束
The string starts with the first double quote and Python will interpret the next double quote (before "test") as the end of the string
"It is a word "test"." # 用 "..." 宣告的字串有 "
File "<ipython-input-20-8d044cdc5263>", line 1
"It is a word "test"." # 用 "..." 宣告的字串有 "
^
SyntaxError: invalid syntax
👆
👆
Leveraging Escape Characters (利用跳脫字元)
Represent special characters within strings.
Choosing Between Quotation Marks (選擇不同的引號)
Opt for single ('...') or double ("...") quotes based on the content.
' I\'m learning Python! ' # 用 '...' 宣告的字串有 '
" I'm learning Python! "
"It is a word \"test\"." # 用 "..." 宣告的字串有 "
'It is a word "test".'
str1 = "I'm learning Python! " # 用 "..." 宣告的字串有 '
str2 = 'It is a word "test".' # 用 '...' 宣告的字串有 "
print(f"str1: {str1}")
print(f"str2: {str2}")
I'm learning Python!
It is a word "test".
+ (串接 ):
字串 + 字串 ==> 字串串接
name = "May"
print("Hello " + name + " :)")
gretting = "Hi, " + name
print(gretting + " :)")
Hello May :)
Hi, Amy! :)
* (重複) :
字串 * n ==> 字串重複 n 次
hi = "Hi. " # 這是字串 hi
hi3 = hi * 3 # 重覆3次 hi 的內容
print("hi :", hi)
print("hi3 :", hi3)
hi : Hi.
hi3 : Hi. Hi. Hi.
in (包含):
"字串A" in "字串B": 字串 A 是否在字串 B 中
string = "Emma is there"
print("Emma" in string) # "Emma" 是否在 string 中
print("emma" in string) # "emma" 是否在 string 中
True
False
s = " hello WORLD. "
print(f"Original string: |{s}|")
print(f"After strip(): |{s.strip()}|")
print(f"Capitalize: |{s.strip().capitalize()}|")
print(f"Title case: |{s.strip().title()}|")
print(f"To uppercase: |{s.upper()}|")
print(f"To lowercase: |{s.lower()}|")
print(f"Center with '*' upto 30: |{s.center(30, '*')}|")
start_str = ''.join('*' if i % 5 == 0 else '-' for i in range(1, 31))
position_str = ' ' * len("Center with '*': ") + "|"+start_str+"|"
print(position_str)
print(f"Starts with 'hello': {s.startswith('hello')}")
print(f"Ends with 'world.' : {s.endswith('world.')}")
print(f"Position of 'world': {s.find('world')}")
print(f"Last position of 'o': {s.rfind('o')}")
print(f"Count of 'l': {s.count('l')}")
print(f"Is alphabetic: {s.isalpha()}")
print(f"Is digit: {'12345'.isdigit()}")
print(f"Is space: {' '.isspace()}")
Original string: | hello WORLD. |
After strip(): |hello WORLD.|
Capitalize: |Hello world.|
Title case: |Hello World.|
To uppercase: | HELLO WORLD. |
To lowercase: | hello world. |
Center with '*' upto 30: |****** hello WORLD. ******|
|----*----*----*----*----*----*|
Starts with 'hello': False
Ends with 'world.' : False
Position of 'world': -1
Last position of 'o': 7
Count of 'l': 2
Is alphabetic: False
Is digit: True
Is space: True
s = "hello world."
print(f"Original string: {s}\n")
# Group: "Is" functions
print("=== Checking Properties ===")
print(f"Is alphanumeric: {s.isalnum()}")
print(f"Is lowercase: {s.islower()}")
print(f"Is uppercase: {s.swapcase().isupper()}")
print(f"Is digit: {'12345'.isdigit()}")
print(f"Is alphabetic: {s.isalpha()}")
print(f"Is space: {' '.isspace()}\n")
# Group: Positional & Search functions
print("=== Positional & Search ===")
print(f"Starts with 'hello': {s.startswith('hello')}")
print(f"Ends with 'world.': {s.endswith('world.')}")
print(f"Position of 'world': {s.find('world')}")
print(f"Index of 'o': {s.index('o')}\n")
# Group: Transformation functions
print("=== Transformations ===")
print(f"Swap case: {s.swapcase()}")
print(f"Join list with ',': {','.join(['a', 'b', 'c'])}")
splitlines_example = 'Hello\nWorld'.splitlines()
print("Split lines: ", splitlines_example)
Original string: hello world.
=== Checking Properties ===
Is alphanumeric: False
Is lowercase: True
Is uppercase: True
Is digit: True
Is alphabetic: False
Is space: True
=== Positional & Search ===
Starts with 'hello': True
Ends with 'world.': True
Position of 'world': 6
Index of 'o': 4
=== Transformations ===
Swap case: HELLO WORLD.
Join list with ',': a,b,c
Split lines: ['Hello', 'World']
s = "HELLO WORLD"
Syntax: s[index]
Access the character at a specific position in string s
.
H | E | L | L | O |
---|---|---|---|---|
0 | 1 | 2 | 3 | 4 |
-11 | -10 | -9 | -8 | -7 |
, | W | O | R | L | D |
---|---|---|---|---|---|
5 | 6 | 7 | 8 | 9 | 10 |
-6 | -5 | -4 | -3 | -2 | -1 |
s[0] = s[-11]
s[4] = s[-7]
s[10] = s[-1]
s = "HELLO,WORLD"
print('s :', s)
print('s[0] ', s[0]) # 取 index = 0 第一個字 H
print('s[-11]', s[-11]) # 取 index = -11 第一個字 H
print('s[4] ', s[4]) # 取 index = 4 第五個字 O
print('s[-1] ', s[-1]) # 取 index = -1 最後一個字 D
s : HELLO,WORLD
s[0] H
s[-11] H
s[4] O
s[-1] D
👆
s[start_index:stop_index]
start_index
butstop_index
.H | E | L | L | O |
---|---|---|---|---|
0 | 1 | 2 | 3 | 4 |
-11 | -10 | -9 | -8 | -7 |
, | W | O | R | L | D |
---|---|---|---|---|---|
5 | 6 | 7 | 8 | 9 | 10 |
-6 | -5 | -4 | -3 | -2 | -1 |
s[0:3]
s[6:10]
s[-9:-4]
s = "HELLO,WORLD"
no = "01234567890"
no1 = "10987654321"
print('s :', ' '.join(s))
print('+no :', ' '.join(no))
print('-no :', ' '.join(no1), '\n')
print('s[2:5] ', s[2:5]) # 取 index 2-5 [2,3,4] 第2到第4
print('s[-10:-6] ', s[-10:-6]) # 從 -10 取到 -5
print('s[2:] ', s[2:]) # 從 index 2到底
print('s[:5] ', s[:5]) # 從 開頭取到第5
print('s[:-2] ', s[:-2]) # 從 開頭取到倒數第2
s : H E L L O , W O R L D
+no : 0 1 2 3 4 5 6 7 8 9 0
-no : 1 0 9 8 7 6 5 4 3 2 1
s[2:5] E L
s[-10:-6] W O
s[2:] E L L O , W O R L D
s[:5] H E L
s[:-2] H E L L O , W O R L
👆
A variable is a symbolic name for a storage location where data can be held and referenced.
3
variable
variable
3
variable name
assign
value
10
x
10
x
Naming Objects
Objects
Pointer
# Variable Assignment in Python
# Assign a value to a variable using the "=" symbol
x = 10 # Here, 'x' is a variable that is assigned the value 10.
# Variables act as pointers to memory locations
# The variable 'x' points to a memory location holding the value 10.
# Utilize the variable in operations
double_x = x * 2 # Multiply the value of 'x' by 2 and assign to 'double_x'.
# Display the result using the variable
print(double_x) # This will print 20, which is 10 multiplied by 2.
20
x = 3
y = 3
3
x
3
x
3
y
y
In Python, variables are not just tied to a specific value but also aren't bound to a specific data type.
x = 10
print("x is an integer:", x)
x = 'Hello'
print("x is a string:", x)
x is an integer: 10
x is a string: Hello
10
x
'Hello'
x
Allows you to assign a single value to multiple variables simultaneously
a = b = c = 300 # Chained assignment of value 300 to variables a, b, and c
print(a, b, c) # This will print 300 300 300
300, 300, 300
performing an operation and assignment in one step
variable <operator>= expression
x += 5
x += 5 --> x = x + 5
x −= 3 --> x = x − 3
x ∗= 4 --> x = x * 4
x /= 2 --> x = x / 2
x %= 4 --> x = x % 4
x ∗∗= 3 --> x = x ** 3
x //= 3 --> x = x // 3
# Initialize variables
total_items = 0
price_per_item = 50 # in TWD
discount = 0.1 # 10% discount
# User buys 6 items
total_items += 6
total_cost = total_items * price_per_item
total_cost -= total_cost * discount # Apply discount
print(f"物品數量: {total_items}")
print(f"每件價格: {price_per_item} TWD")
print(f"總價格: {total_cost} TWD")
物品數量: 6
每件價格: 50 TWD
總價格: 270.0 TWD
Use only letters, numbers, and underscores.
Start with a letter or underscore, not a number.
Names are case-sensitive (variable ≠ Variable).
Avoid Python keywords (e.g., if, else, for).
No spaces; use underscores for separation (user_name).
Prefer descriptive names (word_list vs wl).
No special symbols like !, @, #, etc.
Chinese characters are permissible but not encouraged.
Variable Name | Result | Remarks |
---|---|---|
username | ✅ | |
_user_name | ✅❌ | python Internal use (by convention) |
user9name | ✅ | |
9username | ❌ | Starts with a number |
user name | ❌ | Contains a space |
user@name | ❌ | Contains a special symbol |
if | ❌ | Python keyword |
用户 | ✅❌ | Chinese characters (not recommended) |
user-name | ❌ | Contains a hyphen |
userName | ✅ | camelCase format |
# Traditional Chinese character in variable name (not recommended but valid)
學生 = "Alice" # Assigning Alice's name to the variable 學生
user_age = 25
user_email = "alice@example.com"
# Using numbers in variable names
order_1 = "Book"
order_2 = "Laptop"
# List of users (demonstrating snake_case)
user_list = [學生, "Bob", "Charlie"]
# Calculating average age of users (example of a descriptive variable name)
total_age = user_age + 30 + 28 # Ages of Alice, Bob, and Charlie
average_age = total_age / 3
# Translation: Alice's email is {user_email}, and she ordered a {order_1}.
print(f"{學生} 的電子郵件是 {user_email},她訂購了 {order_1}。")
# Translation: The average age of users is {average_age} years.
print(f"使用者的平均年齡是 {average_age:.2f} 歲。")
Alice 的電子郵件是 alice@example.com,她訂購了 Book。
使用者的平均年齡是 27.67 歲。
print(f"5,記憶體位址是 {hex(id(5))}")
print(f"5.0,記憶體位址是 {hex(id(5.0))}")
print(f"'hello',記憶體位址是 {hex(id('hello'))}")
print(f"(1, 2, 3),記憶體位址是 {hex(id((1, 2, 3)))}")
print(f"True,記憶體位址是 {hex(id(True))}")
5,記憶體位址是 0x7885b0880170
5.0,記憶體位址是 0x788596f9edd0
'hello',記憶體位址是 0x7885973310b0
(1, 2, 3),記憶體位址是 0x78857af16e40
True,記憶體位址是 0x57d94cfcf420
frozenset([1, 2, 3]),記憶體位址是 0x7885971cedc0
print(f"3,記憶體位址是 {hex(id(3))}")
print(f"5,記憶體位址是 {hex(id(5))}")
3,記憶體位址是 0x7885b0880130
5,記憶體位址是 0x7885b0880170
a = 3
print(f"a 的值是 {a},記憶體位址是 {hex(id(a))}")
b = 5
print(f"b 的值是 {b},記憶體位址是 {hex(id(b))}")
a 的值是 3,記憶體位址是 0x7885b0880130
b 的值是 5,記憶體位址是 0x7885b0880170
int
a = 3
print(f"a 的值是 {a},記憶體位址是 {hex(id(a))}") # 這會顯示 'a' 的記憶體位址。
b = 5
print(f"b 的值是 {a},記憶體位址是 {hex(id(b))}") # 這會顯示 'b' 的記憶體位址。
a = 8
print(f"a 的值是 {a},記憶體位址是 {hex(id(a))}") # 新的記憶體位址,因為 a 現在參考到一個不同的整數。
b = 8
print(f"b 的值是 {a},記憶體位址是 {hex(id(b))}") # 新的記憶體位址,因為 b 現在參考到一個不同的整數。
a 的值是 3,記憶體位址是 0x7c165bd38130
b 的值是 3,記憶體位址是 0x7c165bd38170
a 的值是 8,記憶體位址是 0x7c165bd381d0
b 的值是 8,記憶體位址是 0x7c165bd381d0
word = 'Python'
word[0] = 'J'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-74-ad89e228b316> in <cell line: 2>()
1 word = 'Python'
----> 2 word[0] = 'J'
TypeError: 'str' object does not support item assignment
word = 'Python'
new_word = 'J' + word[1:]
print(f"word {word}")
print(f"new word: {new_word}")
# Recreating new_word using join method
new_word_join = ''.join(['J', word[1:]])
print(f"new word: {new_word}")
word Python
new word: Jython
new word: Jython
Direct operations between different data types can result in errors.
不同的資料形態不能運算
123 + 'aaa'
'aaa' - 12
a = 123 # a is int
b = '456' # b is str
print(a+b) # a+b ==> int + str has error
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-3-d3484c5e35e9> in <cell line: 3>()
1 a = 123 # a is int
2 b = '456' # b is str
----> 3 print(a+b) # a+b ==> int + str has error
TypeError: unsupported operand type(s) for +: 'int' and 'str'
OperationResult
int(x) | x converted to integer |
float(x) | x converted to floating point |
str(x) | x coverted to string |
a = 123 # a is int
b = '456' # b is str
print(a+int(b)) # int(b) ==> int + int
print(str(a)+b) # str(a) ==> str + str
579
123456
x = input("What's x? ")
y = input("What's y? ")
z = x + y
print(z)
What's x? 3
What's y? 5
35
x = int(input("What's x? "))
y = int(input("What's y? "))
z = x + y
print(z)
What's x? 3
What's y? 5
8
student_name = '李大中' # 學生名稱
ch_score = 98 # 國文成績
en_score = 95 # 英文成績
math_score = 90 # 數學成績
# 計算總分和平均
total = ch_score + math_score + en_score # 總分
average = total / 3 # 平均
# 顯示學生姓名和成績
print('學生姓名:', student_name)
print('國英數成績:', ch_score, en_score, math_score)
print('平均成績:', average)
學生姓名: 李大中
國英數成績: 98 95 90
平均成績: 94.33333333333333
round(number) # 預設無小數
round(number , 小數後幾位)
print('round(59.4)', round(59.4))
print('round(59.5)', round(59.5))
sc = 5954/100
print('sc', sc, 'round(sc)', round(sc))
print('sc', sc, 'round(sc,1)', round(sc, 1))
print('sc', sc, 'round(sc,2)', round(sc, 2))
round(59.4) 59
round(59.5) 60
sc 59.54 round(sc) 60
sc 59.54 round(sc,1) 59.5
sc 59.54 round(sc,2) 59.54
請寫一支Python程式,能讀取兩個整數,並把他們的四則運算印出來。四捨五入取到小數點第二位
身體質量指數(Body Mass Index, BMI)
BMI = 體重(公斤)除以身高(公尺)的平方
---------------------------------------------------------------------------
請使用者輸入體重(公斤)和身高 (公分),協助計算使用者的BMI並輸出 (input(), int(x), print())
程式請宣告體重,身高,BMI三個變數
BMI請四捨五入取到小數點第二位 (fstring)
A list is one of the fundamental data structures in Python. It is like a container that stores a collection of items in a specific order, and these items can be of any type.
# Shopping List
shopping_list = ["milk", "eggs", "bread", "apples"]
# Bookshelf with Mixed Data Types (Strings and Dictionaries)
bookshelf = [
"Harry Potter",
{"title": "Harry Potter and the Philosopher's Stone", "author": "J. K. Rowling"},
"1984",
{"title": "Nineteen Eighty-Four", "author": "George Orwell"}
]
# Class Scores with Mixed Data Types (Strings and Floats)
class_scores = ["John", 85.5, "Emily", 92.0, "Michael", "Sarah", 89.0]
# Queue at a Bank with Mixed Data Types (Strings and Tuples)
bank_queue = ["Person1", ("Person2", "09:05 AM"), "Person3", ("Person4", "09:15 AM")]
mixed = ['apple', 1, [2, 3], 3.1416]
print(f"mixed type: {type(mixed)}")
for i, item in enumerate(mixed):
print(f"Item {i} : {str(item):<10} - Type: {type(item)}")
mixed type: <class 'list'>
Item 0 : apple - Type: <class 'str'>
Item 1 : 1 - Type: <class 'int'>
Item 2 : [2, 3] - Type: <class 'list'>
Item 3 : 3.1416 - Type: <class 'float'>
Python lists are ordered collections. Each item has an index starting from 0.
mixed
mixed[0]
mixed[1]
mixed[2]
mixed[3]
mixed = ['apple', 1, [3, 4], 3.1416]
print(f"mixed : {mixed}\n")
for i in range(len(mixed)):
print(f"mixed[{i}] get {mixed[i]}")
mixed : ['apple', 1, [3, 4], 3.1416]
mixed[0] get apple
mixed[1] get 1
mixed[2] get [3, 4]
mixed[3] get 3.1416
mixed = ['apple', 1, [3, 4], 3.1416]
print(f"mixed : {mixed}\n")
for i in range(-1, -len(mixed)-1, -1):
print(f"mixed[{i}] get {mixed[i]}")
mixed : ['apple', 1, [3, 4], 3.1416]
mixed[-1] get 3.1416
mixed[-2] get [3, 4]
mixed[-3] get 1
mixed[-4] get apple
Trying to access an index that does not exist in the list will result in an IndexError
.
4
The maximum index of a list with N items is N-1
(because indexing starts from 0).
mixed = ['apple', 1, [3, 4], 3.1416]
print(mixed[4]) # ???????
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-19-67ede96cbb23> in <cell line: 3>()
1 mixed = ['apple', 1, [3, 4], 3.1416]
2
----> 3 print(mixed[4]) # ???????
Slicing allows for extracting a subset of items from a list.
mixed = ['apple', 1, [3, 4], 3.1416]
print(f"mixed : {mixed}")
print("First three items mixed[0:3] :", mixed[0:3])
print("Items from second to third mixed[1:3] :", mixed[1:3])
print("All items except the first mixed[1:] :", mixed[1:])
print("All items except the last mixed[:-1] :", mixed[:-1])
print("Reversed every second item mixed[::-2] :", mixed[::-2])
print("Second to last, reversed mixed[-2::-1] :", mixed[-2::-1])
mixed : ['apple', 1, [3, 4], 3.1416]
First three items mixed[0:3] : ['apple', 1, [3, 4]]
Items from second to third mixed[1:3] : [1, [3, 4]]
All items except the first mixed[1:] : [1, [3, 4], 3.1416]
All items except the last mixed[:-1] : ['apple', 1, [3, 4]]
Reversed every second item mixed[::-2] : [3.1416, 1]
Second to last, reversed mixed[-2::-1] : [[3, 4], 1, 'apple']
mixed = ['apple', 1, [3, 4], 3.1416]
print(f"{'Before:':<26}", mixed)
mixed[0] = 'orange'
afterstr = "After mixed[0] = 'orange':"
print(f"{afterstr:<26}", mixed)
Before: ['apple', 1, [3, 4], 3.1416]
After mixed[0] = 'orange': ['orange', 1, [3, 4], 3.1416]
mixed = ['apple', 1, [3, 4], 3.1416]
print(f"{'Before:':<26}", mixed)
mixed[1:3] = [5, 6]
print(f"{'After mixed[1:3] = [5, 6]:':<26}", mixed)
Before: ['apple', 1, [3, 4], 3.1416]
After mixed[1:3] = [5, 6]: ['apple', 5, 6, 3.1416]
mixed = ['apple', 1, [3, 4], 3.1416]
print(f"{'Before:':<32}", mixed)
mixed[2:2] = ['berry', 7]
afterstr = "After mixed[2:2] = ['berry', 7]:"
print(f"{afterstr:<32}", mixed)
Before: ['apple', 1, [3, 4], 3.1416]
After mixed[2:2] = ['berry', 7]: ['apple', 1, 'berry', 7, [3, 4], 3.1416]
afterstr = "After mixed[2:4] = []:"
width = len(afterstr)+1
mixed = ['apple', 1, [3, 4], 3.1416]
print(f"{'Before:':<{width}}", mixed)
mixed[2:4] = []
print(f"{afterstr:<{width}}", mixed)
Before: ['apple', 1, [3, 4], 3.1416]
After mixed[2:4] = []: ['apple', 1]
# Append
# Description: Add an item to the end of the list.
fruits = ['apple', 'banana']
fruits.append('cherry')
print(fruits) # ['apple', 'banana', 'cherry']
# Insert
# Description: Insert an item at a specific position.
fruits.insert(1, 'avocado')
print(fruits) # ['apple', 'avocado', 'banana', 'cherry']
# Remove
# Description: Remove the first occurrence of a value.
fruits.remove('banana')
print(fruits) # ['apple', 'avocado', 'cherry']
# Extend
# Description: Extend the list by appending elements from another list.
veggies = ['carrot', 'broccoli']
fruits.extend(veggies)
print(fruits) # ['apple', 'avocado', 'cherry', 'carrot', 'broccoli']
# Pop
# Description: Remove the item at a specific position and return it.
# By default, it removes and returns the last item.
popped_item = fruits.pop(3)
print(popped_item) # 'carrot'
print(fruits) # ['apple', 'avocado', 'cherry', 'broccoli']
# Index
# Description: Return the index of the first occurrence of a value.
index_of_cherry = fruits.index('cherry')
print(index_of_cherry) # 2
# Count
# Description: Return the number of times a value appears in the list.
count_avocado = fruits.count('avocado')
print(count_avocado) # 1
# Sort
# Description: Sort the list in place.
fruits.sort()
print(fruits) # ['apple', 'avocado', 'broccoli', 'cherry']
# Reverse
# Description: Reverse the list in place.
fruits.reverse()
print(fruits) # ['cherry', 'broccoli', 'avocado', 'apple']
# Clear
# Description: Remove all items from the list.
fruits.clear()
print(fruits) # []
A tuple is a collection of ordered elements.
Unlike lists, tuples are immutable.
This means that once a tuple is created, its elements cannot be modified.
This immutability makes tuples a perfect choice for representing unchangeable data
(),
while Lists are created using square brackets []
,.Consider a birthdate guessing game.
Once a birthdate is set, it remains unchanged.
By representing this data with a tuple, it guarantees constancy throughout its utilization.
# Tuples are made by comma-separating values inside parentheses.
birthdate = ("25th", "December", 2000)
print(birthdate, type(birthdate))
# Without Parentheses
birthdate = "25th", "December", 2000
print(birthdate, type(birthdate))
# Using the tuple() Constructor
date_list = ["25th", "December", 2000]
birthdate = tuple(date_list)
print(birthdate, type(birthdate))
A tuple representing a birthdate "25th", "December", 2000
('25th', 'December', 2000) <class 'tuple'>
('25th', 'December', 2000) <class 'tuple'>
('25th', 'December', 2000) <class 'tuple'>
# Correct way to create a single-element tuple
correct_single_element_tuple = ('25th',)
print(f"(using '('25th',)') {correct_single_element_tuple} , \
type: {type(correct_single_element_tuple)}")
# Incorrect way to create a single-element tuple
incorrect_single_element_tuple = ("25th")
print(f"(using '('25th')') {incorrect_single_element_tuple} ,\
type: {type(incorrect_single_element_tuple)}")
(using '('25th',)') ('25th',) , type: <class 'tuple'>
(using '('25th')') 25th ,type: <class 'str'>
birthdate_with_time = ('25th', 'December', 2000, ('12:00', 'PM'))
print("using nested tuples)")
print("birthdate_with_time = (25th', 'December', 2000, ('12:00', 'PM')")
print(f"birthdate_with_time {birthdate_with_time}")
print(f"birthdate_with_time type: {type(birthdate_with_time)}")
using nested tuples)
birthdate_with_time = (25th', 'December', 2000, ('12:00', 'PM')
birthdate_with_time ('25th', 'December', 2000, ('12:00', 'PM'))
birthdate_with_time type: <class 'tuple'>
birthdate = ("25th", "December", 2000)
# we attempt to modify it
birthdate[1] = "January"
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-29-812b8ae24954> in <cell line: 4>()
2
3 # we attempt to modify it
----> 4 birthdate[1] = "January"
TypeError: 'tuple' object does not support item assignment
birthdate = ("25th", "December", 2000)
additional_info = ("Male", "A+")
combined_data = birthdate + additional_info
print(f"Concatenated tuple: {combined_data}")
Concatenated tuple: ('25th', 'December', 2000, 'Male', 'A+')
birthdate = ("25th", "December", 2000)
# Check if "December" exists in the tuple
exists_december = "December" in birthdate
print(f"Does 'December' exist in the tuple? {exists_december}")
# Check if "January" exists in the tuple
exists_january = "January" in birthdate
print(f"Does 'January' exist in the tuple? {exists_january}")
# Check if a number exists in the tuple
exists_2000 = 2000 in birthdate
print(f"Does the number 2000 exist in the tuple? {exists_2000}")
# Check if a number doesn't exist in the tuple
not_exists_1999 = 1999 not in birthdate
print(f"Does the number 1999 not exist in the tuple? {not_exists_1999}")
Does 'December' exist in the tuple? True
Does 'January' exist in the tuple? False
Does the number 2000 exist in the tuple? True
Does the number 1999 not exist in the tuple? True
The world of key-value pairs in Python!
Key | Value |
---|---|
Apple | 蘋果 |
Orange | 橘子 |
Papaya | 木瓜 |
person = {
"name": "John",
"age": 25,
"is_student": False
}
fruits = {
"Apple" : "蘋果",
"Orange" : "橘子",
"Papaya" : "木瓜"
}
name = person["name"]
name = person.get("name")
# Accessing items from the 'fruits' dictionary
apple_in_chinese = fruits["Apple"]
orange_in_chinese = fruits.get("Orange")
print(f"Translation for Apple: {apple_in_chinese}")
print(f"Translation for Orange: {orange_in_chinese}")
# Accessing items from the 'person' dictionary
person_name = person["name"]
is_student = person.get("is_student")
print(f"\nPerson's Name: {person_name}")
print(f"Is the person a student? {'Yes' if is_student else 'No'}")
Translation for Apple: 蘋果
Translation for Orange: 橙子
Person's Name: John
Is the person a student? No
fruits["Banana"] = "香蕉"
fruits["Grape"] = "葡萄"
print(fruits)
# {'Apple': '蘋果', 'Orange': '橘子', 'Papaya': '木瓜', 'Banana': '香蕉', 'Grape': '葡萄'}
person["gender"] = "male"
person["country"] = "USA"
print(person)
# {'name': 'John', 'age': 25, 'is_student': False, 'gender': 'male', 'country': 'USA'}
Using a key:value pair with an existing key
fruits["Papaya"] = "大木瓜"
print(fruits)
# {'Apple': '蘋果', 'Orange': '橘子', 'Papaya': '大木瓜', 'Banana': '香蕉', 'Grape': '葡萄'}
person["name"] = "Jane"
person["age"] = 30
print(person)
# {'name': 'Jane', 'age': 30, 'is_student': False, 'gender': 'male', 'country': 'USA'}
Using del
keyword
Removes the item with the specified key name
del fruits["Apple"]
Using pop()
method
Removes the item with the specified key name and returns its value
removed_fruit = fruits.pop("Orange")
Using popitem()
method
Removes the last inserted key-value pair
last_item = fruits.popitem()
fruits = {
"Apple" : "蘋果",
"Orange" : "橘子",
"Papaya" : "木瓜",
'Banana': '香蕉'
}
del fruits["Apple"]
print(fruits) # {'Orange': '橘子', 'Papaya': '木瓜', 'Banana': '香蕉'}
removed_fruit = fruits.pop("Orange")
print(removed_fruit) # 橘子
print(fruits) # {'Papaya': '木瓜', 'Banana': '香蕉'}
last_item = fruits.popitem()
print(last_item) # ('Banana', '香蕉')
print(fruits) # {'Papaya': '木瓜'}
person = { "name": "John","age": 25,"is_student": False}
# Looping through keys:
for key in person:
print(f" key: {key:<5}", end=' ')
print()
# Looping through values:
for value in person.values():
print(f"value: {value:<5}", end=" ")
print()
# Looping through both:
for key, value in person.items():
print(f"{key}: {value}")
key: name key: age key: is_student
value: John value: 25 value: 0
name: John
age: 25
is_student: False
Using just {}
creates a dictionary, not a set. To create an empty set, you use the set()
constructor.
empty_set = set()
To create a set, place a comma-separated list of items between curly braces {}
.
fruits = {"apple", "banana", "cherry"}
You can use the set()
constructor to create a set from a list or any other iterable.
numbers_list = [1, 2, 3, 3, 4]
unique_numbers = set(numbers_list) # This will remove duplicates
Sets automatically remove duplicate values. So, if you create a set with duplicate items, they will be stored only once.
duplicates = {"apple", "banana", "apple"}
print(duplicates) # Outputs: {"apple", "banana"}
Since sets are unordered, you cannot access items using an index. Instead, you can loop through the set items using a for
loop.
fruits = {"apple", "banana", "cherry"}
for fruit in fruits:
print(fruit)
To check if an item is present in a set, use the in
keyword.
if "apple" in fruits:
print("Apple is in the set")
You can use the len()
function to determine how many items a set has.
num_of_fruits = len(fruits)
print(num_of_fruits) # Outputs: 3
To add a single item to a set, use the `add()` method.
fruits = {"apple", "banana", "cherry"}
fruits.add("orange")
# Output: {'apple', 'banana', 'cherry', 'orange'}
update()
To add multiple items (from lists, sets, or other iterables), use the update()
method.
fruits = {"apple", "banana", "cherry"}
fruits.update(["mango", "grapes"])
# Output: {'apple', 'banana', 'cherry', 'mango', 'grapes'}
remove()
This method removes the specified item. If the item is not found, it raises an error.
fruits = {'apple', 'banana', 'cherry', 'mango', 'grapes'}
fruits.remove("banana")
# Output: {'apple', 'cherry', 'mango', 'grapes'}
discard()
This method removes the specified item. However, if the item is not found, it does NOT raise an error.
fruits = {'apple', 'cherry', 'grapes', 'mango'}
fruits.discard("mango")
# Output: {'apple', 'cherry', 'grapes'}
pop()
Since sets are unordered, the pop()
method removes a random item. Be cautious when using this.
fruits = {'apple', 'cherry', 'grapes'}
removed_fruit = fruits.pop()
print(f"Removed: {removed_fruit}, Remaining: {fruits}")
# Potential Output: Removed: apple, Remaining: {'cherry', 'grapes'}
To remove all items from a set, use the clear()
method.
Example:
fruits.clear()
Sets store unique values, making them ideal for removing duplicates from a list.
items = [1, 2, 2, 3, 4, 4, 5]
unique_items = set(items)
print(unique_items) # Output: {1, 2, 3, 4, 5}
Sets can be used to quickly check for common words, find unique words, or exclude specific words from texts.
text = "apple banana apple orange"
words = set(text.split())
print(words) # Output: {"apple", "banana", "orange"}
Functions are fundamental in programming. They prevent code repetition and improve code clarity.
def
keyword.# Define a function called 'greet' that takes a single parameter 'name'
def greet(name):
# Print a greeting message using the provided name
print(f"Hello, {name}!")
# Define a function called 'greet' that takes a single parameter 'name'
def greet(name):
# Print a greeting message using the provided name
print(f"Hello, {name}!")
# Call the 'greet' function and pass the string "Alice" as an argument
greet("Alice")
define a function that doesn't take any parameters.
# Define a function called 'display_message'
def display_message():
# Print a static message
print("Welcome to Python Programming!")
# Call the 'display_message' function
display_message() # Expected output: Welcome to Python Programming!
return
keyword to send a result back from the function.None
.
Example:# Define a function called 'add' that takes two parameters: 'a' and 'b'
def add(a, b):
# Return the sum of 'a' and 'b'
return a + b
# Call the 'add' function with arguments 5 and 3, and print the result
print(add(5, 3)) # Expected output: 8
# Define a function called 'full_name' that takes two parameters: 'first_name' and 'last_name'
def full_name(first_name, last_name):
# Return the concatenated full name using the provided first and last names
return f"{first_name} {last_name}"
# Call the 'full_name' function with "John" as the first name and "Doe" as the last name, and print the result
print(full_name("John", "Doe")) # Expected output: John Doe
# Define a function called 'greet' with a default parameter 'name' set to "Guest"
def greet(name="Guest"):
# Print a greeting message using the provided name or the default value if no name is provided
print(f"Hello, {name}!")
# Call the 'greet' function without providing an argument, which will use the default value "Guest"
greet() # Expected output: Hello, Guest!
# Call the 'greet' function with "Alice" as an argument
greet("Alice") # Expected output: Hello, Alice!
Use *args
for variable number of positional arguments.
# Define a function called 'print_args' that accepts a variable number of arguments using *args
def print_args(*args):
# Join all arguments with a space and print them in one line
print(' '.join(map(str, args)))
# Call the 'print_args' function with multiple arguments
print_args(1, 2, 3) # Expected output: 1 2 3
print_args("apple", "banana", "cherry") # Expected output: apple banana cherry
Use **kwargs
for variable number of keyword arguments.
# Define a function that accepts any number of keyword arguments using **kwargs
def print_key_value_pairs(**kwargs):
# Loop through each keyword argument and print the key-value pair
for key, value in kwargs.items():
print(f"{key}: {value}")
# Call the function with two keyword arguments
print_key_value_pairs(brand="Apple", product="iPhone")
# Expected output:
# brand: Apple
# product: iPhone
print_key_value_pairs(subject="Math", grade="A", semester="Spring")
# Expected output:
# subject: Math
# grade: A
# semester: Spring
Python docstrings associate descriptions or documentation with functions, modules, or classes using triple quotes ('''
or """
).
def calculate_area(length, width):
'''
Calculate the area of a rectangle.
Parameters:
- length (float): The length of the rectangle.
- width (float): The width of the rectangle.
Returns:
- float: The area of the rectangle.
'''
return length * width
# Example usage
area = calculate_area(5, 3)
print(area) # Expected output: 15