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)