7.3 字典Dictionary(鍵值對) 創建字典:demoDic={"name":"Tom","age":10,"sex":1} 查看key對應的Value值:demoDic["name"] 刪除字典中元素:deldemoDic["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 repeateStringsgetStrings=repeated_strings("hello ", 3)print(getStrings)在函數中聲明全局變量使用global xx=80def 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_stringsprint(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=36guess=int(input("Enter a number:"))ifguess==num: print("You win!")elifguess<num: print("The number you input is smaller to the true number!")else: print("Thenumber you input is bigger to the true number!")print("Done")for用法,其中range(1,10)為1-9的數字,不包含10foriinrange(1,10): print(i)else: print("over")且for對于List、Tupel以及Dictionary依然適用a_list=[1,2,3,4,5]foriina_list: print(i) b_tuple=(1,2,3,4,5)foriinb_tuple: print(i)c_dict={"Bob":15,"Tom":12,"Lucy":10}foreleninc_dict: print(elen+":"+str(c_dict[elen]))9.2 while循環num=66guess_flag=Falsewhileguess_flag==False: guess=int(input("Enter an number:")) ifguess==num: guess_flag=True elifguess<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=66whileTrue: guess=int(input("Enter an number:")) ifguess==num: print("you win!") break elifguess<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!") continuepass執行下一條語句,相當于什么都不做a_list=[0,1,2]print("using continue:")foriina_list: ifnoti: continue print(i)print("using pass:")foriina_list: ifnoti: pass print(i)