python总结01
1 注意点
1.1 banana, apple = apple, banana
apple = 1
banana = 2
banana, apple = apple, banana
print('apple = ', apple, ', banana = ', banana)
说明:
- 第三行代码中的“banana, apple = apple, banana”是同时进行的,而不是先apple给banana赋值,再banana给apple赋值;
1.2 for 循环
1)第一种情况
apple = 3
val = [6, 5, 4, 3, 2, 1, 0]
for apple in range(-2, 6):
print('The value is ',apple)
print('The value_1 of apple is ',apple)
for apple in val:
print('The value is ',apple)
print('The value_2 of apple is ',apple)
for apple in range(6):
print('The value is ',apple)
print('The value_3 of apple is ',apple)
if apple in val:
print('The value_4 of apple is ',apple)
说明:
- range(a, b):含头不含尾;
- range(a):从0往正方向数,包括0本身;
- for 循环内的变量会重新初始化,覆盖之前定义的,并且在循环外也是可以使用的;if 判断则是使用之前定义的变量,并且in前后都要是字符串变量;
2)第二种情况
基本版:
apple = 'cesbdh'
banana = 'xsd'
cabbage = ['cly', 'lyc', 'ycl']
diary = ['dia', 'iar']
for goods in apple, banana:
print('goods = ', goods)
for goods in cabbage, diary:
print('goods = ', goods)
复杂版:
apple = 'cesbdh'
banana = 'xsd'
cabbage = ['cly', 'lyc', 'ycl']
diary = ['dia', 'iar']
def convert(apple, banana):
fruits = []
for goods in apple, banana:
fruit = goods[:]
#fruit = goods 效果同上
fruits.append(fruit)
print('fruits = ', fruits)
return fruits
print('---------------')
cat, dog = convert(apple, banana)
print('cat = ', cat)
print('dog = ', dog)
print('---------------')
rabbit, carrot = convert(cabbage, diary)
print('rabbit = ', rabbit)
print('carrot = ', carrot)
说明:for goods in apple, banana: 的理解,一维列表参数对其所属的二维列表 相当于 字符串或数值等参数对所属的一维列表,前者(即参数)都是“一次处理到位的”;
1.3 input()函数
1)Python3 中 input() 函数接受一个标准输入数据,返回为 string 类型。
code_1 = 000
code_2 = '000'
guess = input("[Keypad]> ")
print(code_1 == guess)
print(code_2 == guess)
如果输入的是“000”,则为“True”;如果输入的是000,则为“False”;
改进方法:
1)int()函数 — 将一个由数值构成的字符串或数值转换为整型(去尾)。
print(code_1 == int(guess))
2)str()函数 — 将对象转化为适于人阅读的形式。
print(str(code_1) == guess)
但该中方法有一定风险,比如str(000) = ‘0’ ≠ ‘000’;
2 疑难点
2.1 List list()-用于将元组或字符串转换为列表
类型1:
PHRASES = {'fruit': 'apple', 'vegetable': 'cabbage', 'tool': 'pen'}
snippets = list(PHRASES.keys())
print('PHRASES.keys() = ', PHRASES.keys())
print('snippets = ',snippets)
说明:
- 类型1中,经过python 3的改版,PHRASES.keys()返回的是一个可迭代对象,可以使用 list() 来转换为列表,即snippets是一个列表变量;