Python基础语法(2)——字典、函数定义使用、控制流(if&for&while)

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)) Python基础语法(2)——字典、函数定义使用、控制流(if&for&while) 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) Python基础语法(2)——字典、函数定义使用、控制流(if&for&while) 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)