【一】while循環
【1】什么是循環結構
- 循環結構是一種程序控制結構,用于反復執行一組語句,直到滿足某個條件為止。
- 循環結構使得程序可以更有效地重復執行某段代碼,節省了編寫重復代碼的工作。
[1]語法
while condition: # while 是循環的關鍵字。
# 循環體 # condition是循環的條件,當條件為真時,循環體會一直執行。
[2]使用
count = 0
while count < 5:
print("Current count:", count)
count += 1
print("Loop finished!")
# Current count: 0
# Current count: 1
# Current count: 2
# Current count: 3
# Current count: 4
# Loop finished!
【2】案例
# 設定好用戶年齡,用戶通過輸入猜測的年齡進行匹配
# 最大嘗試次數:用戶最多嘗試猜測3次
# 最大嘗試次數后:如3次后,問用戶是否還想繼續玩
## 如果回答Y或y,就再給3次機會,提示【還剩最后三次機會】
### 3次都猜錯的話游戲結束
## 如果回答N或n,游戲結束!
# 如果格式輸入錯誤,提示【輸入格式錯誤,請重新輸入:】
# 如果猜對了,游戲結束!
age = 18
count = 0
while count < 3:
age_input = int(input("請猜測年齡: >>>>>>"))
if age_input > age:
print("太大了")
elif age_input < age:
print("太小了")
else:
print("剛剛好")
break
count = count + 1
if count == 3:
again = input("是否要繼續 y/n:")
if again not in ["y","n"]:
print("程序錯誤")
break
if again == "y":
count = 0
else:
print("下次再來玩")
break
【二】for 循環
【1】語法
for variable in sequence:
# 循環體
# for是循環的關鍵字。
# variable是循環變量,它會在每次循環中取 `sequence` 中的一個值。
# sequence 是一個序列,可以是列表、元組、字符串等。
【2】使用
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print("Current fruit:", fruit)
# Current fruit: apple
# Current fruit: banana
# Current fruit: cherry
【三】退出循環(break)
【1】語法
while condition:
# 循環體3
if some_condition:4
break # 退出循環
【2】使用
count = 0
while count < 5:
print(count)
if count == 3:
break # 當 count 等于 3 時,退出循環
count += 1
【3】案例
username = "Dream"
password = "123"
# 記錄錯誤驗證的次數
count = 0
while count < 3:
inp_name = input("請輸入用戶名:")
inp_pwd = input("請輸入密碼:")
if inp_name == username and inp_pwd == password:
print("登陸成功")
break # 用于結束本層循環
else:
print("輸入的用戶名或密碼錯誤!")
count += 1
【4】while多層循環嵌套-break
username = "Dream"
password = "123"
count = 0
while count < 3: # 第一層循環
inp_name = input("請輸入用戶名:")
inp_pwd = input("請輸入密碼:")
if inp_name == username and inp_pwd == password:
print("登陸成功")
while True: # 第二層循環
cmd = input('>>: ')
if cmd == 'quit':
break # 用于結束本層循環,即第二層循環
print('run <%s>' % cmd)
break # 用于結束本層循環,即第一層循環
else:
print("輸入的用戶名或密碼錯誤!")
count += 1
【四】退出循環(continue)
【1】語法
while condition:
# 循環體
if some_condition:
continue # 跳過當前循環,繼續下一次循環
【2】使用
count = 2
while count < 5:4
count += 15
if count == 3:6
continue # 當count 等于 3 時,跳過當前循環,繼續下一次循環
print(count)
break 用于完全退出循環,而 continue 用于跳過當前循環的剩余部分,直接進入下一次循環
【五】無限循環(死循環)
- 有時候,我們需要程序在滿足某個條件時一直執行,這就需要用到無限循環。
- 最簡單的無限循環可以通過
while 語句實現,條件永遠為真。
while True:
print("This is an infinite loop!")
- 在實際編程中,我們可能會在無限循環中加入某個條件來實現根據需要退出循環的邏輯
while True:
user_input = input("Enter 'exit' to end the loop: ")
if user_input.lower() == 'exit':
break
else:
print("You entered:", user_input)
- 這個例子中,用戶需要輸入 'exit' 才能結束循環。這樣就可以靈活地在需要的時候退出無限循環。
【六】標志位
【1】語法
flag = True # 初始化標志位
while flag:
# 循環體
if some_condition:
flag = False # 修改標志位,退出循環
【2】使用
flag = True # 初始化標志位
while flag:
user_input = input("請輸入:")
if user_input == 'exit':
flag = False # 當用戶輸入 'exit' 時,修改標志位,退出循環
else:
print("用戶輸入:", user_input)
【3】案例(while循環嵌套+tag標志位)
# 登錄認證練習
# 用列表套字典存儲用戶數據
# 有一個輸入框輸入用戶名和密碼 ,增加重試次數 讓他一直重試知道正確位置
# 正確的話就斷掉了
user = [{"name": "zhangsan","password": "123"},
{"name": "song","password" : "456"},
{"name": "zhang","password" : "789"}]
tage = True
while tage:
username_input = input("請輸入用戶名: >>>")
userpassword_input = input("請輸入密碼: >>>")
for users in user:
users_username = users["name"]
users_password = users["password"]
if username_input == users_username:
if userpassword_input == users_password:
print("登錄成功")
tage = False
break
else:
print("登錄失敗")
continue
【七】循環分支(else)
- 在while循環的后面
- 當while 循環正常執行完并且中間沒有被break 中止的話
count = 0
while count <= 5 :
count += 1
print("Loop",count)
else:
print("循環正常執行完啦")
print("-----out of while loop ------")
輸出
Loop 1
Loop 2
Loop 3
Loop 4
Loop 5
Loop 6
循環正常執行完啦 #沒有被break打斷,所以執行了該行代碼
-----out of while loop ------
count = 0
while count <= 5 :
count += 1
if count == 3:
break
print("Loop",count)
else:
print("循環正常執行完啦")
print("-----out of while loop ------")
輸出
Loop 1
Loop 2
-----out of while loop ------ #由于循環被break打斷了,所以不執行else后的輸出語句
【八】range關鍵字
【1】語法
for i in range(stop):
# 循環體
for i in range(start, stop):
# 循環體
for i in range(start, stop, step):
# 循環體
【2】使用
for i in range(5):
print(i)
# 輸出:
# 0
# 1
# 2
# 3
# 4
for i in range(2, 6):
print(i)
# 輸出:
# 2
# 3
# 4
# 5
for i in range(1, 10, 2):
print(i)
# 輸出:
# 1
# 3
# 5
# 7
# 9
【3】步長
# [1]語法
range(start, stop, step)
# range 關鍵字
# 幫我們生成指定區間內的整數列表
# 顧頭不顧尾
# [2]使用
for i in range(1, 10, 2):
print(i)
# 輸出:
# 1
# 3
# 5
# 7
# 9
【4】案例
while 1:
score = input("請輸入您的成績>>") # "100"
if score.isdigit():
score = int(score) # 100
if score > 100 or score < 0:
print("您的輸入有誤!")
elif score > 90:
print("成績優秀")
elif score > 70: # else if
print("成績良好")
elif score > 60:
print("成績及格")
else:
print("成績不及格")
else:
print("請輸入一個數字")
【九】整數類型的內置方法
# 整型 (int)
# num = '123'
# 【1】類型強轉 -- 符合 int類型格式的字符串可以強轉成整數類型
# print(num, type(num)) # 123 <class 'str'>
# print(int(num), type(int(num))) # 123 <class 'int'>
# score = input(":》》》")
# print(score, type(score))
# 浮點型(float)
# score = int(score)
# print(score, type(score))
# 【2】十進制數轉為 其他進制
# print(bin(999)) # 0b1111100111 -- 0b 開頭 最大只能到 1
# print(oct(999)) # 0o1747 -- 0o 開頭就是八進制 --- 八進制
# print(hex(999)) # 0x3e7 -- 0x 開頭就是十六進制 有英文字符的情況就是十六進制
# (1)十進制轉八進制 0o
# print(oct(999)) # 0o 1747
# (2)十進制轉十六進制 0x
# print(hex(999)) # 0x 3e7
# (3)十進制轉二進制 0b
# print(bin(999)) # 0b 1111100111
# (4)其他進制數轉換為十進制數 , int也支持轉換進制
# num = '0b1111100111'
# print(int(num, 2))
# num = '0o1747'
# print(int(num, 8))
# num = '0x3e7'
# print(int(num, 16))
# 【2】浮點數的內置方法
# salary = 100.01
# 強制類型轉換 轉換符合浮點數的字符串 可以將整數轉換為 浮點數
# num = 100
# print(float(num))
# num = '100.111'
# print(float(num))
# 【3】判斷當前類型是否是整數或者浮點數
num1 = b'4' # <class 'bytes'>
num2 = '4' # unicode,Python 3 中不需要在字符串前加 'u'
num3 = '四' # 中文數字
num4 = 'Ⅳ' # 羅馬數字
# 判斷當前字符串類型是否是指定的數據格式
# (1)判斷當前是否為數字類型 isdigit
# print(num1.isdigit())
# print(num2.isdigit())
# print(num3.isdigit())
# print(num4.isdigit())
# (2)判斷是否是小數點類型
# print(num1.isdecimal())
# num = 100.01
# print(num.isdecimal())
# print(num2.isdecimal())
# age = input("請輸入年齡 :>>>> ")
# if age.isdigit():
# age = int(age)
# print(type(age))
# else:
# print(f"語法不規范")
【十】字符串內置方法
# 【一】字符串的語法格式
# name = "dream"
# 【二】內置方法 --- 優先記住和學習
# 【1】字符串拼接
# (1)直接字符串 + 法
# name = "dream"
# name_one = "hope"
# print(name + name_one)
# (2).join字符串拼接
# print(','.join(name_one))
# 【2】索引取值
# 正索引 從 0開始取值
# 負索引從 -1 開始取值
# 索引取值可以但是不能修改
# 【3】切片 給定一個起始位置和結束位置 截取這之間的元素
# 切片也是顧頭不顧尾
# name = "dream"
# 正常語法:[起始索引位置:截止索引位置]
# print(name[2:4])
# 不正常語法: [起始索引位置:截止索引位置:步長]
# 步長;隔幾個去一個
# print(name[0:4:2])
# print(name[0:-1:-2])
# 負索引切片 遵循坐標軸的規范 左小右大
# print(name[-4:-1])
# 【4】計算長度
# print(len(name))
# 【5】成員運算
# print("d" in name)
# 【6】去除空格
# username = input(">>>>")
# 去除手動產生的空格
# username = username.strip()
# if username == "dream":
# print(username)
# 默認是去除兩側的空格
# 去除兩邊的特殊字符
# name = " dream "
# print(name.strip(' '))
# name = "$dream$"
# print(name.strip("$"))
# # 去除指定一側的特殊字符
# # right :右側
# print(name.rstrip("$"))
# # left 左側
# print(name.lstrip("$"))
# 【7】切分字符串
# username_password = "dream|521"
# 參數是按照什么去切 切完以后這個編制就沒了
# username, password = username_password.split("|")
# print(username, password)
# name = "dream 521"
# print(name.split())
# 【8】遍歷
# 就是將里面的每一個元素看一遍
# name = 'dream'
# for i in name:
# print(i)
# range : 顧頭不顧尾
# for i in range(len(name)):
# print(name[i])
# 【9】重復當前元素
# print("*" * 10)
# 【10】大小寫轉換
# name = 'Dream'
# print(name.upper())
# print(name.lower())
#
# name = "dream"
# print(name.islower())
# print(name.isupper())
# 【11】判斷當前字符串以 .. 開頭或者結尾
# name = "dream"
# 判斷開頭
# print(name.startswith("d"))
# 判斷結尾
# print(name.endswith("m"))
# 【11】格式化疏忽語法
# %s %d占位
name = "dream"
age = 18
print("my name is %s " % name)
print("my name is %s ,my age is %s" % (name, age))
# format
# 按位置傳參數
print('my name is {} ,my age is {}'.format(name, age))
# 按關鍵字傳參數
print('my name is {name_location} ,my age is {age_location}'.format(name_location=name, age_location=age))
# f+ {}
print(f"my name is {name} . my age is {age}")
# 【12】join拼接
print(','.join("drema"))
print('|'.join(["drema","521"]))
print('|'.join(("drema","521")))
# 【三】內置方法 -- 了解