Python2

这篇博客主要介绍了作者在学习Python2阶段的经历,包括熟悉Python的基本概念和语法,通过老师的代码示例进行学习和笔记记录。

现阶段主要是熟悉Python的各种定义,方法等等,以下是课程中老师所写的代码示范+笔记:


#列表
fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
# #统计列表元素
print(fruits.count('apple'))
# #索引列表元素
print(fruits.index('banana'))
#反转列表
fruits.reverse()
print(fruits)
#按照字典顺序排序
fruits.sort()
print(fruits)
print(fruits.pop())
print(fruits)

vec = [-4, -2, 0, 2, 4]
vec1 = [x*2 for x in vec]
print(vec1)
from math import pi
pi_list = [str(round(pi, i)) for i in range(1, 6)]
print(pi_list)

#del和pop的区别
#del是直接删除元素,没有返回值,pop则有返回值
del fruits[0]
print(fruits.pop())
print(fruits)
#元祖
t = 12345, 54321, 'hello!'
# print(t[0])
# 'tuple' object does not support item assignment
#元祖和string的index一样,不能被改变
#t[0] = 88888
v = ([1, 2, 3], [3, 2, 1])
# print(v[0][1])
#
# x,y,z = t
# print(x,y,z)

#sets集合  无序的 不重复的
# A set is an unordered collection with no duplicate elements.
#第一种定义方法,直接一个大括号
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket)
#第二种定义方法
a = set('abracadabra')
print(a)

#字典  和java的map有点类似
tel = {'jack': 4098, 'sape': 4139}
tel['guido'] = 4127
print(tel)
print(list(tel.keys()))
print(sorted(tel.keys()))
#生成字典的方式
dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{x: x**2 for x in (2, 4, 6)}
dict(sape=4139, guido=4127, jack=4098)

#遍历字典
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for k, v in knights.items():
   print(k+":"+v)

#两个返回值  一个是索引,另外一个才是value
for i, v in enumerate(['tic', 'tac', 'toe']):
   print(i, v)
#同时对两个列表进行遍历
questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):
   print('What is your {0}?  It is {1}.'.format(q, a))

#python运行时传参
#ZeroDivisionError
#print(1/0)
import sys

try:
    #我们读一个文件的时候,可能这个文件并不存在,这个时候会有异常
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except OSError as err:
    print("OS error: {0}".format(err))
except ValueError:
    print("Could not convert data to an integer.")
except:
    print("Unexpected error:", sys.exc_info()[0])
    raise

def divide(x, y):
   try:
     result = x / y
   except Exception:
       print("erro")
   else:
     print("result is", result)
   finally:
     print("executing finally clause")
divide(2, 1)
divide(2, 0)
divide("2", "1")

#The str() function is meant to return representations of values which are fairly human-readable, while repr() is meant to generate representations which can be read by the interpreter
s = 'Hello, world.'
print(str(s))
print(repr(s))
#字符串的标准输入输出
print('We are the '+'knights'+' who say "'+'Ni'+'!"')
print('We are the {} who say "{}!"'.format('knights', 'Ni'))
print('{0} and {1}'.format('spam', 'eggs'))
print('{1} and {0}'.format('spam', 'eggs'))
print('This {food} is {adjective}.'.format(food='spam', adjective='absolutely horrible'))
import math
#输出三位小数
print('The value of PI is approximately {0:.3f}.'.format(math.pi))

#python io流
#mode can be 'r' when the file will only be read, 'w' for only writing
#'a' opens the file for appending
# f = open('workfile', 'w')
# f.write("this is ruoze data for python")
# f = open('workfile', 'r')
# print(f.read())
# f = open('workfile', 'a')
# f.write("this is ruoze data for python\n")
# f.close()
#我们进行io流的时候,要记得关闭资源
f = open('workfile', 'r')
print(f.readline())
print(f.readline())
#!/usr/bin/pyhon3
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
    print("-- This parrot wouldn't", action, end=' ')
    print("if you put", voltage, "volts through it.")
    print("-- Lovely plumage, the", type)
    print("-- It's", state, "!")
parrot(1000)
print("---------------------华丽的分割线-----------")
parrot(voltage=1000)
print("---------------------华丽的分割线-----------")
#传给默认参数一个值,会覆盖掉原来的值
parrot(voltage=1000000, action='VOOOOOM')
print("---------------------华丽的分割线-----------")
parrot(action='VOOOOOM', voltage=1000000)
print("---------------------华丽的分割线-----------")
#如果参数都没有key,就按照函数传入参数的顺序来
parrot('a million', 'bereft of life', 'jump')

#接下来就是错误的演示
#dTypeError: parrot() missing 1 require positional argument: 'voltage'
#因为,第一参数没有默认值,所以一定要传入
#parrot()
#non-keyword argument after a keyword argument
#在keyword参数后面,不能传non-keyword
#parrot(voltage=5.0, 'dead')

#TypeError: parrot() got multiple values for argument 'voltage'
#parrot(110, voltage=220)

#TypeError: parrot() got an unexpected keyword argument 'actor'
#parrot(actor='John Cleese')

#如果我们需要传入n多个参数,或者是n多keyword参数
#*arguments可以传入多个单值参数
#**keywords可以传入多个keyvalue参数
def cheeseshop(kind, *arguments, **keywords):
    print("-- Do you have any", kind, "?")
    print("-- I'm sorry, we're all out of", kind)
    for arg in arguments:
        print(arg)
    print("-" * 40)
    for kw in keywords:
        print(kw, ":", keywords[kw])


cheeseshop("Limburger", "It's very runny, sir.",
           "It's really very, VERY runny, sir.",
           shopkeeper="Michael Palin",
           client="John Cleese",
           sketch="Cheese Shop Sketch")

#Lambda Expressions
def make_incrementor(n):
    return lambda x: x + n
f = make_incrementor(42)
print(f(0))

lambda_list = [1,2,3,4,5,6,7,8]

#map函数,就是对列表中每一个元素进行操作
map_lambda = map(lambda a:a+10,lambda_list)
print(list(map_lambda))
filter_lambda = filter(lambda b:b>6,lambda_list)
print(list(filter_lambda))


#python doc
#加\表示这一行还没有结束
def my_function():
    """\
    Do nothing, but document it.

    No, really, it doesn't do anything.
    """
    pass
print(my_function.__doc__)


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值