第二章:分支循環
1.三大結構
順序(語句一條一條執行下去,則爲順序,此處略過)
分支
循環
注:Python中沒有switch-case語句
2.分支—if
2.1 if
age = 19
if age > 19:
print("you can watch this video with us")
print("don't tell your parents")
注意if後面的冒號:不能丟
五星注意:if下面的每一條語句的縮進代表同屬於if的分支,不同的縮進則不屬於
2.2 if else
sex = input("請輸入你的性別:")
print("你輸入的性別是{0}".format(sex))
if sex = "nan":
print("很好,我們紀念一下,今天代碼抄10000遍,")
else:
print("好的,我最喜歡女同學了,請問你的聯繫方式是?")
print("我是分隔符————————————————")
age = input("請輸入你的年齡:")
age = int(age)
if age > 18:
print("你可以看這個錄像")
print("你已經是成年人了")
else:
print("小朋友去找你麻麻玩泥巴吧,嘻嘻嘻")
注:
Input函數的作用:
在屏幕上輸出括號內的字符串
接受用戶輸入的內容並返回到程序
input返回的內容一定是字符串(所以上述代碼需要用到age = int(age)強制轉換數據類型)
2.3 elif
與C中的else if 語句類似,下面使用該語句編寫C中比較常見的成績分級題
score = input(請輸入你的成績:)
score = int(score)
if score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 70:
print("C")
elif score >= 60:
print("D")
else:
print("我不是你爸爸,滾蛋")
2.4Python中沒有switch-case語句
3 循環—for
3.1 for循環
表達形式:(與C區別比較大)
for 變量 in 序列: (注:如果序列是字符串則用[ ]括號,如果是數字則用( ))
語句1
語句2
……
九九乘法表打印實例:(語言非常簡潔)
for rows in range(1,10):
for cols in range(1,rows+1):
print( rows * cols,ends = " ")
print(" ")
注:range函數:
生成一個數字序列,具體範圍可以定,如range(1,10)則生成1—9
3.2 for-else
當for循環結束的時候會執行else語句,易理解
for name in ["nana","lala","sasa"]:
if name == "sasa":
print("you are a beautiful girl")
else:
print("you are turely a beautiful girl")
3.3 break,continue,pass
break:無條件結束整個循環,即猝死
例:
for age in range(1,10):
if age == 6:
break
print(age)
結果:6
continue:無條件結束本次循環,直接進入下一次循環
for age in range(1,10):
if age == 6:
continue
print(age)
結果:9
pass:表示略過,通常用於必須要寫語句但是暫時不知道要些什麼語句的地方,如:在定義函數時
def func():
pass
print(func)
4 循環—while
4.1 while循環
一般情況下在不知道循環次數,但能確定循環成立條件的時候使用while
表達形式1:
while 條件表達式:
語句
表達形式2:
while 條件表達式:
語句
else:
語句
例:
#有本錢10萬,多少年之後可以翻倍
benqian = 100000
year = 0
while benqian < 200000:
benqian = benqian * (1 + 0.067)
year+=1
print("老子在第{}年,賺了{}元".format(year,benqian))
print("老子終於賺到20萬了,可以娶老婆了")
benqian = 100000
year = 0
while benqian < 200000:
benqian = benqian * (1 + 0.067)
year+=1
print("老子在第{}年,賺了{}元".format(year,benqian))
else:
print("老子終於賺到20萬了,可以娶老婆了")
print("終於可以買車了")