初学Python语言编程基础(二)
把代码过一遍,比文字理论记忆更久,在了解理论的基础上,动手试代码吧!
01 创建字典
字典由键和对应值成对组成。
代码
# -*- coding:utf-8 -*-
#01 创建一个词典 {} 键:对应值
phone_book={'Tom':123,'Jerry':456,'Kim':789}
mixed_dict={'Tom':'boy',11:23.5} #可以不同类型
#访问其中的对应值
print("Tom has phone number: " + str(phone_book['Tom']))
#修改字典里面的值
phone_book['Tom']=999
print("Tom has phone number: " + str(phone_book['Tom']))
#添加
phone_book['Heath']=888
print("The added book is: " + str(phone_book))
#删除字典里的元素以及本身
del phone_book['Tom']
print("The book after del is: " + str(phone_book))
phone_book.clear()
print("The book after del is: " + str(phone_book))
del phone_book
# print("The book after del all is: " + str(phone_book))
#特性
#不允许同一个值出现两次
rep_test={'Name':'aa','age':5,'Name':'bb'}
print("rep_test: "+str(rep_test)) #只识别了一个
#键是不可以变的,所以我们可以用数字、字符串或者元祖充当,但是不能用list
# list_dict={['Name']:'Tom','Age':12}
list_dict={('Name'):'Tom','Age':12}
运行结果
Tom has phone number: 123
Tom has phone number: 999
The added book is: {'Heath': 888, 'Tom': 999, 'Jerry': 456, 'Kim': 789}
The book after del is: {'Heath': 888, 'Jerry': 456, 'Kim': 789}
The book after del is: {}
rep_test: {'Name': 'bb', 'age': 5}
02 函数(没有参数和返回的函数)
函数定义def 后一定要有:
代码
#02 没有参数和返回的函数
def say_hi():
print("hi!")
say_hi()
say_hi()
运行结果
hi!
hi!
03 函数(有参数,无返回位)
代码
#03 有参数,无返回位
def print_sum_two(a,b):
c=a+b
print(c)
print_sum_two(3,6)
运行结果
9
04 函数(字符串)
代码
#04 字符串
def hello_some(str):
print("hello "+str+"!")
hello_some("China")
hello_some("Python")
运行结果
hello China!
hello Python!
05 函数(有参数,有返回值)
代码
#05 有参数,有返回值
def repeat_str(str,times):
repeat_strs=str*times
return repeat_strs
repeated_strings=repeat_str("Happy Birthday!",4)
print(repeated_strings)
运行结果
Happy Birthday!Happy Birthday!Happy Birthday!Happy Birthday!
06 全局变量与局部变量
代码
x=60
def foo(x):
print("x is: "+str(x)) #全局
x=3
print("change local x to "+str(x)) #局部
foo(x)
print('x is still',str(x)) #全局
运行结果
x is: 60
change local x to 3
x is still 60
07 默认参数
代码
#07 默认参数
def repeat_str(s,times=1):
repeated_strs = s * times
return repeated_strs
repeated_strings=repeat_str("Happy Birthday!")
print(repeated_strings)
repeated_strings_2 = repeat_str("Happy Birthday!",4)
print(repeated_strings_2)
运行结果
Happy Birthday!
Happy Birthday!Happy Birthday!Happy Birthday!Happy Birthday!
08 不能在有默认参数后面跟随没有默认参数
代码
#08 不能在有默认参数后面跟随没有默认参数
f(a,b=2) #合法
# f(a=2,b) #非法
09 关键字参数
代码
#09 关键字参数:调用函数时,选择性的传入部分参数
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 = 48,a = 80)
运行结果
a is 13 and b is 17 and c is 8
a is 125 and b is 4 and c is 24
a is 80 and b is 4 and c is 48
10 VarArgs参数
代码
#VarArgs参数
def print_paras(fpara,*nums,**words):
print("fpara: "+ str(fpara))
print("nums: "+ str(nums)) #nums当作一系列元组
print("words: "+str(words)) #当作字典的形式
print_paras("hello",1,3,5,7,word="python",another_word="java") #1,3,5,7没有用对应值的方式,所以对应*nums
运行结果
fpara: hello
nums: (1, 3, 5, 7)
words: {'word': 'python', 'another_word': 'java'}