7.3 字典Dictionary(鍵值對)
創建字典:demoDic={"name":"Tom","age":10,"sex":1}
查看key對應的Value值:demoDic["name"]
刪除字典中元素:del
demoDic["name"]
清空字典:demoDic.clear()
向字典中插入新的元素:demoDic["school"]="XD"
字典中元素可以是混合數據類型,且Key值不可變,Key元素可以爲數字、字符串、元組(tuple)等,不能爲List,字典中Key值必須唯一。
8 函數(Funciton)
8.1 函數定義聲明
不帶參數及帶參數的函數定義
def say_hi():
print("hi!")
say_hi()
say_hi()
def print_two_sum(a,b):
print(a+b)
print_two_sum(3, 6)
def repeated_strings(str,times):
repeateStrings=str*3
return repeateStrings
getStrings=repeated_strings("hello
", 3)
print(getStrings)
在函數中聲明全局變量使用global x
x=80
def foo():
global x
print("x is
",str(x))
x=3
print("x changed
",str(x))
foo()
print("x is
",str(x))
8.2 參數
默認參數:調用函數時,未給出參數值,此時使用默認參數
def repeated_string(string,times=1):
repeated_strings=string*times
return repeated_strings
print(repeated_string("hello
"))
print(repeated_string("hello
",4))
默認參數之後的參數也必須是默認參數
關鍵字參數:在函數調用時,指明調用參數的關鍵字
def fun(a,b=3,c=6):
print("a:"+str(a)+"
b:"+str(b)+" c:"+str(c))
fun(1,4)
fun(10,c=8)
VarArgs參數:參數個數不確定情況下使用
帶*參數爲非關鍵字提供的參數
帶**參數爲含有關鍵字提供的參數
def func(fstr,*numbers,**strings):
print("fstr:",fstr)
print("numbers:",numbers)
print("strings:",strings)
func("hello",1,2,3,str1="aaa",str2="bbb",str3=4)
9 控制流
9.1 if語句&for循環
if用法
num=36
guess=int(input("Enter
a number:"))
if
guess==num:
print("You
win!")
elif
guess<num:
print("The
number you input is smaller to the true number!")
else:
print("The
number you input is bigger to the true number!")
print("Done")
for用法,其中range(1,10)爲1-9的數字,不包含10
for
i
in
range(1,10):
print(i)
else:
print("over")
且for對於List、Tupel以及Dictionary依然適用
a_list=[1,2,3,4,5]
for
i
in
a_list:
print(i)
b_tuple=(1,2,3,4,5)
for
i
in
b_tuple:
print(i)
c_dict={"Bob":15,"Tom":12,"Lucy":10}
for
elen
in
c_dict:
print(elen+":"+str(c_dict[elen]))
9.2 while循環
num=66
guess_flag=False
while
guess_flag==False:
guess=int(input("Enter
an number:"))
if
guess==num:
guess_flag=True
elif
guess<num:
print("The
number you input is smaller to the true number!")
else:
print("The
number you input is bigger to the true number!")
print("You
win!")
9.3 break&continue&pass
num=66
while
True:
guess=int(input("Enter
an number:"))
if
guess==num:
print("you
win!")
break
elif
guess<num:
print("The
number you input is smaller to the true number!")
continue
else:
print("The
number you input is bigger to the true number!")
continue
pass執行下一條語句,相當於什麼都不做
a_list=[0,1,2]
print("using
continue:")
for
i
in
a_list:
if
not
i:
continue
print(i)
print("using
pass:")
for
i
in
a_list:
if
not
i:
pass
print(i)