'''
多分支條件語(yǔ)句的基本結(jié)構(gòu)是 if-elif-else 。
if 條件1:
# 當(dāng)條件1 為真時(shí)執(zhí)行的代碼
elif 條件2:
# 當(dāng) 條件1 為假,條件2 為真時(shí)執(zhí)行的代碼
elif 條件3:
# 當(dāng) 條件1 和 條件2 都為假,條件3 為真時(shí)執(zhí)行的代碼
...
else:
# 當(dāng)所有條件都為假時(shí)執(zhí)行的代碼
強(qiáng)調(diào)要點(diǎn)
條件的順序很重要,先檢查更嚴(yán)格或更特殊的條件。
只有一個(gè)分支的代碼會(huì)被執(zhí)行,一旦某個(gè)條件滿(mǎn)足,后續(xù)的條件不再檢查。
else 是可選的,但在某些情況下可以處理所有前面條件都不滿(mǎn)足的情況,使邏輯更完整。
#python3.10 之后提供了match - case 語(yǔ)句
match expression:
case pattern1:
# 執(zhí)行的代碼塊 1
case pattern2:
# 執(zhí)行的代碼塊 2
...
case _:
# 當(dāng)所有前面的模式都不匹配時(shí)執(zhí)行的默認(rèn)代碼塊
'''
score = 40
# if score >= 90:
# print("優(yōu)秀")
# elif score >= 80:
# print("良好")
# elif score >= 70:
# print("中等")
# elif score >= 60:
# print("及格")
# else:
# print("不及格")
# match score:
# case score if score>=90:
# print("優(yōu)秀")
# case score if score>=80:
# print("良好")
# case score if score>=70:
# print("中等")
# case score if score>=60:
# print("及格")
# case _:
# print("不及格")
from PySide6.QtWidgets import *
from PySide6.QtCore import *
class MainWindow(QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.setWindowTitle("多條件分支示例")
self.resize(500,300)
# 創(chuàng)建按鈕
self.button1 = QPushButton("按鈕 1",self)
self.button2 = QPushButton("按鈕 2",self)
self.button3 = QPushButton("按鈕 3",self)
# 擺放位置
self.button1.setGeometry(40,40,80,30)
self.button2.setGeometry(40,80,80,30)
self.button3.setGeometry(40,120,80,30)
# 連接按鈕的點(diǎn)擊信號(hào)到槽函數(shù)
self.button1.clicked.connect(self.on_button_clicked)
self.button2.clicked.connect(self.on_button_clicked)
self.button3.clicked.connect(self.on_button_clicked)
def on_button_clicked(self):
# 根據(jù)發(fā)送信號(hào)的對(duì)象(按鈕)執(zhí)行不同的操作,sender() 方法獲取到發(fā)送這個(gè)信號(hào)的對(duì)象
sender = self.sender()
# if sender == self.button1:
# QMessageBox.information(self, "消息", "您點(diǎn)擊了按鈕 1")
# elif sender == self.button2:
# QMessageBox.information(self, "消息", "您點(diǎn)擊了按鈕 2")
# elif sender == self.button3:
# QMessageBox.information(self, "消息", "您點(diǎn)擊了按鈕 3")
#第二種寫(xiě)法
match sender:
case self.button1:
QMessageBox.information(self, "消息", "您點(diǎn)擊了按鈕 1")
case self.button2:
QMessageBox.information(self, "消息", "您點(diǎn)擊了按鈕 2")
case self.button3:
QMessageBox.information(self, "消息", "您點(diǎn)擊了按鈕 3")
app = QApplication([])
window = MainWindow()
window.show()
app.exec()
承擔(dān)因您的行為而導(dǎo)致的法律責(zé)任,
本站有權(quán)保留或刪除有爭(zhēng)議評(píng)論。
參與本評(píng)論即表明您已經(jīng)閱讀并接受
上述條款。