Python的基础语法(二)
生活随笔
收集整理的這篇文章主要介紹了
Python的基础语法(二)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Tuple數據類型:
mixed_tuple = (1 , 2, ['a','b']) print("mixed_tuple:" + str(mixed_tuple)) mixed_tuple[2][0]='c' mixed_tuple[2][1]='d' print("mixed_tuple after:" + str(mixed_tuple))字典的應用:
# coding: utf-8# 創建一個詞典 phone_book= {'Tom':123,'sunliyuan':456,'shi':789}mixed_dict={"Tom":'boy',11:23.5}# 字典的調用 print ("sunliyuan has phone numbr:"+ str(phone_book["sunliyuan"]))# 修改字典的值 phone_book['sunliyuan']=521 print ("sunliyuan has phone numbr:"+ str(phone_book["sunliyuan"]))# 添加一個值 phone_book['sunli']=888 print ("sunliyuan has phone numbr:"+ str(phone_book))# 刪除字典中的元素和本身 del phone_book['sunli'] print ("sunli after del is:"+ str(phone_book))# 清空字典的值 phone_book.clear() print ("sunli after del is:"+ str(phone_book))# 清空字典本身 del phone_book print ("sunli after del is:"+ str(phone_book))運行的效果圖:
?
# 特性 # 不允許同一個鍵出現兩次 rep_test={'Name':'aa','age':5,'Name':'sun'} print("rep_test:"+str(rep_test))# 鍵必須不可變 用數字和字符串充當鍵 不能用list充當 # list_dict={['Name']:'sun','Age':13}#Tuple是可以的 (可變的) list_dict={('Nam'):'sun','Age':13}
?
函數:
# coding: utf-8# 沒有參數和返回的函數 def say_hi():print ("sunliyuan")say_hi()say_hi()# 有參數 無返回值def print_sum(a,b):c=a+bprint (c)print_sum(1,2)def hellow(str):print("hellow" + str + "!")# 有參數有返回值的 def repatstr(str,times):repeated_strs=str*timesreturn repeated_strsrepatstr_string=repatstr("sunliyuan",4)print(repatstr_string)# 全局變量和局部變量 x = 60 def foo(x):print("x is :"+str(x))x=3print("change local x to"+str(x))foo(x)print ('x is still',str(x))# 默認參數 def repeat_str(s, times = 1):repeated_strs = s * timesreturn repeated_strsrepeated_strings = repeat_str("Happy Birthday!") print(repeated_strings)repeated_strings_2 = repeat_str("Happy Birthday!" , 4) print(repeated_strings_2)#不能在有默認參數后面跟隨沒有默認參數 #f(a, b =2)合法 #f(a = 2, b)非法# 關鍵字參數: 調用函數時,選擇性的傳入部分參數 def func(a, b=4, c=8):print('a is', a, 'and b is', b, 'and c is', c)func(13, 17) func(125, c=24) func(c=40, a=80)
# VarArgs參數 def print_paras(fpara, *nums, **words):print("fpara: " + str(fpara))print("nums: " + str(nums))print("words: " + str(words))print_paras("hello", 1, 3, 5, 7, word="python", anohter_word="java")
?
轉載于:https://www.cnblogs.com/sunliyuan/p/6308908.html
總結
以上是生活随笔為你收集整理的Python的基础语法(二)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 线上图片批量更换脚本记录
- 下一篇: 哈哈