目录
一、 函数
1.1 内建函数
所谓内建函数:在python版本安装完成后可以使用,是“自带”的
5.2 创建函数
- def (即define定义) :创建函数
- arg (即argument, 参数) = parameter
- return 即返回结果
注意:
- def 和 return 是关键字(keyword)
- 在闭合括号后面的冒号不可以少(只能使用英文输入法输入)
- 在IDE中冒号后面回车(换行),可自动得到一个缩进(表明语句与逻辑的从属关系)。
def fahrenheit_converter(C):
fahrenheit = C * 9 / 5 + 32
print(type(C))
return str(fahrenheit) + '。F'
C2F = fahrenheit_converter(35)
print(C2F)
输出:
<class 'int'>
95.0。F
return调用情况
def calculateTax(price, tax_rate):
total = price + (price * tax_rate)
return total
方式1 :
my_price = float(input("enter a price"))
total = calculateTax(my_price, 0.06)
print("price = ", my_price, "total price = ",total)
方式二:直接调用
print(calculateTax (8, 0.88))
total_money = calculateTax(8, 0.1) + calculateTax(9,0.3)
print(total_money)
方式三:对返回值不做任何处理
calculateTax(10, 0.5)
若没有return
def fahrenheit_converter(C):
fahrenheit = C * 9 / 5 + 32
print(type(C))
print(str(fahrenheit) + '。F')
C2F = fahrenheit_converter(35)
print(C2F)
输出:
<class 'int'>
95.0。F
None
可以看出,return不是关键字,如果没有return也没有关系,返回值为‘None’.
例子:
1:设计一个重量转换器
def g2kg(g):
return str(g/1000) + 'kg'
print(g2kg(2000))
输出:
2.0kg
2:设计一个求直角三角形斜边长
方法一:
def zhouchang(a, b):
import cmath
sum = a * a + b * b
num_sqrt = cmath.sqrt(sum)
return num_sqrt
cc = zhouchang(3, 4)
print(cc)
输出:
(5+0j)
方法二:
def theorrm(a, b):
return 'the righr triangle third side \' s length is {}'.format((a**2 + b**2)**(1/2))
print(theorrm(3,4))
输出:
the righr triangle third side ' s length is 5.0
5.3 传递参数与参数类型
🎗向函数传递参数:
单个参数
传递多个参数
若函数超过5到6个参数,可以将所有参数收集到列表中,然后用列表传递到函数
🎗传递参数方式:
- 位置参数(position argument)
- 关键词参数(keyword argument)
def area(uo, down, height):
return 1/2 * (up + down) * height
area(1, 2, 3) //位置参数
area(up = 1, down =2, height = 3) // 关键词参数
第一行、第二行:反序传入, 第一行正确——因为关键词参数,
第三行,第四行:正序传入
5.4 变量作用域
局部变量
尝试打印一个局部变量:
def calculateTax(price, tax_rate): total = price + (price * tax_rate) print(my_price) return total my_price = float(input("enter a price")) total = calculateTax(my_price, 0.06) print("price = ", my_price, "total price = ",total) print(price)
ANS:
print(price)
NameError: name 'price' is not defined This line explains the error
这一行解释了错误说明price仅仅只有在函数中起作用
5.5 例子
//创建censored_text_creat函数:功能在桌面创建一个文本在其输入文字,若信息中含有敏感字会被默认过滤写入文件
file = open('C://Users/pql/Desktop/filename.txt', 'w')
file.write('HELLO Python!')
def text_create(name, msg):
desk_path = 'C://Users/pql/Desktop/'
full_path = desk_path + name +'.txt'
file = open(full_path, 'w')
file.write(msg)
file.close()
print('Done')
text_create('hello', 'hello newmsg')
def text_filter(wxd, censored_word = 'lame', changed_word = 'Awesome'):
return wxd.replace(censored_word, changed_word)
wss = text_filter('python is lame')
print(wss)
def censored_text_creat(name, msg):
clean_msg = text_filter(msg)
text_create(name, clean_msg)
censored_text_creat('Try', 'lame!lame!!lame!!!')
问题定义text_create()函数时提示:
SyntaxError: invalid syntax
答:原因是定义函数忘记加冒号 :
六、循环与判断
6.1 逻辑控制与循环
-
逻辑控制——True & False
注意:不同类型的对象不能用“> < >= <=”比较, 可用“== !=”
特殊点:布尔类型比较运算
- 成员运算符与身份运算符 Membership & Identify Operators
关键词:in 、 not in(是否存在于in后面的集合中,归属关系)与 is 、is not(进行身份对比,身份鉴别)
>>> the_edit = 'edit'
>>> name = 'edit'
>>> the_edit == name
True
>>> the_edit is name
True
alu = ['Black', 'David Bowie', 25, True]
alu.append('new ')
print(alu[0], alu[-1])
'Black' in alu
print('Black' in alu)
注意:python中任何对象均可以判断其布尔值,除0、None和所有空的序列与集合(列表、字典、集合)为False,其余为True
>>> bool(0) False >>> bool(None) False >>> bool([]) False >>> bool('') False >>> bool(False) False
- 布尔运算符(Boolean Operators)
>>> 1 < 3 and 2 < 5
True
>>> 1 < 3 and 2 > 5
False
>>> 1 < 3 or 2 > 5
True
>>> 1 > 3 or 2 > 5
False
6.2 条件控制
单条件判断:
def acount_login():
password = input('Password')
if password == '123456':
print('Login success!')
else:
print('Wrong password or invalid input!')
acount_login()
acount_login()
输出:
Password12131343
Wrong password or invalid input!
Password233`13
Wrong password or invalid input!
Password123456
Login success!
多条件判断:
//可更新密码
pascord_list = ['*#*#', '12345']
def account_login():
password = input('Password')
password_correct = password == pascord_list[-1]
password_reset = password == pascord_list[0]
if password_correct:
print('Login success!')
elif password_reset:
new_password = input('Enter a new password:')
pascord_list.append(new_password)
print('Your password has changed successfully!')
account_login()
else:
print('Wrong password or invalid input!')
account_login()
account_login()
输出:
Password1245
Wrong password or invalid input!
Password*#*#
Enter a new password:152125
Your password has changed successfully!
Password12345
Wrong password or invalid input!
Password152125
Login success!
6.3 循环(Loop)
🙃for循环
- for关键词,后面根着一个可以容纳‘每个元素’的元素,名称不可和关键词重名
- in 后面是具有“可迭代的”或像列表的集合形态的对象,即可连续地提供其中每个元素的对象
例子一:
for every_letter in 'hello world':
print(every_letter)
输出:
h
e
l
l
o
w
o
r
l
d
例子二:
方法一:
listx = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for x in listx:
print(str(x) + '+ 1 =', x + 1)
方法二:
for x in range(1, 11):
print(str(x) + '+ 1 =', x + 1)
输出:
1+ 1 = 2
2+ 1 = 3
3+ 1 = 4
4+ 1 = 5
5+ 1 = 6
6+ 1 = 7
7+ 1 = 8
8+ 1 = 9
9+ 1 = 10
10+ 1 = 11
例子3:
song_list = ['Holy Diver', 'Thunderstruck', 'Rebel Rebel']
for i in song_list:
if i =='Holy Diver':
print('Dio')
elif i == 'Thunderstruck':
print('AC/DC')
elif i == 'Rebel Rebel':
print('David Bowie')
输出:
Dio
AC/DC
David Bowie
🙃while循环
在循环过程中,需要制造某种可以使循环停下来的条件
coun = 0
while True:
print('Repeat this line !')
print(coun)
coun = coun + 1
if coun == 5:
break
🙃嵌套循环
输出乘法表:
方法一:
for i in range(1, 10):
for j in range(1, 10):
print(str(i) + ' * ' + str(j) + ' = ', i * j)
方法二:
for i in range(1, 10):
for j in range(1, 10):
print('{} X {} = {}'.format(i, j, i*j))
嵌套循环 —— 常用于排列和组合
如:学校开个热狗店,做个广告海报,用数字显示如何订购热狗、小面包、番茄酱、芥末酱和洋葱的所有可能的组合。所以我们需要得出总共有多少种可能的组合。
print("\tDog\tBun\tKerchup\tMustard\tOnions") count = 1 for dog in [0, 1]: for bun in [0, 1]: for ketchup in [0, 1]: for mustard in [0, 1]: for onion in [0, 1]: print("#", count, "\t",dog, "\t", bun, "\t", ketchup, "\t", mustard, "\t", onion) count = count + 1 修改加卡路里: og_cal = 140 bun_cal = 120 mus_cal = 20 ket_cal = 80 onion_cal = 40 print("\tDog\tBun\tKerchup\tMustard\tOnions\tCalories") count = 1 for dog in [0, 1]: for bun in [0, 1]: for ketchup in [0, 1]: for mustard in [0, 1]: for onion in [0, 1]: total_cal = (dog * dog_cal) + (bun * bun_cal) + (mustard * mus_cal) +\ (ketchup * ket_cal) + (onion * onion_cal) print("#", count, "\t",dog, "\t", bun, "\t", ketchup, "\t", mustard, "\t", onion, "\t", total_cal) count = count + 1
补充:
一条捷径——range()
range():创建一个列表,其中包含某个范围内的数。
①、range定义范围:
提供一个数字列表,从给定的第一个数开始,在给定的最后一个数之前结束
>>> print range(1, 5)
[1, 2, 3, 4]
②、range简写:
都从 0 开始循环而不是从 1 开始
>>> for i in range (0, 5):
print(i)
0
1
2
3
4
③、range关于字符串:
>>> for loop in ["abcderfghki"]:
print(loop)
abcderfghki
>>> for loop in "abcderfghki":
print(loop)
a
b
c
d
e
r
f
g
h
k
i
④、range按步长计数:正序 / 倒序
>>> for i in range(1, 10, 2):
print(i)
1
3
5
7
9
倒序:
>>> for i in range(10, 1, -2):
print(i)
10
8
6
4
2
例子:定时器程序:
import time
for i in range(10, 0, -1):
print(i)
time.sleep(1)
print("OFF!")
=============================== RESTART: E:/PycharmProjects/ifd.py ===============================
10
9
8
7
6
5
4
3
2
1
OFF!
>>>
参考:编程小白的第一本Python入门书
父与子的编程之旅