Python 学习笔记

来源:互联网 发布:十大元帅 知乎 编辑:程序博客网 时间:2024/06/11 09:00

第一部分 Python基础

  • 直接打印一个值
>>>print 4 4
  • 如果不确定一个值的类型,则可以使用
>>>type(“Hello World!”)<type ‘str’>>>>type(17)<type ‘int’>>>>type(3.2)<type ‘float’>
  • Python的关键字
and del from not whileas elif global or withassert else if pass yieldbreak except import printclass exec in raisecontinue finally is returndef for lambda try
  • 运算符和操作符
    – + - * /和C语言一样
    – **代表指数,如5**2=25
    – %代表取余
    – +操作符可以用于string类型,比如
>>>first=”100”>>>second=”200”>>>print first+second100200
  • 请求用户输入
>>> input = raw_input()Some silly stuff>>> print inputSome silly stuff
  • 使用#进行注释

第二部分 条件执行

  • 可以直接使用 and or not三种逻辑符
>>>17 and TrueTrue
  • 条件语句
if x>0:   print ‘x is positive’#使用if的时候需要注意:在if语句的后面必须要有冒号,在if的内含语句中,需要有缩进。
  • if和else共同使用
if x%2==0:   print ‘x is even’else:   print ‘x is odd’
  • 更多条件语句
if x<y:   print ‘x is less than y’elif x>y:   print ‘x is greater than y’else:   print ‘x and y are equal’
  • 在else中庸if else
if x=y:   print ‘x and y are equal’else:   if x<y:       print ‘x is less than y’   else:       print ‘x is greater than y’
  • 使用try 和except 来捕捉异常
inp=raw_input(“Enter the number what you want:”)try:      value=float(inp)      print valueexcept:      print “please enter a number!”

第三部分 函数

  • 内嵌函数:可以直接拿来用
>>> max('Hello world')'w'>>> min('Hello world')' '
  • len函数,判断字符串的长度
>>> len('Hello world')11
  • 使用类型转换函数
#不必要的转换>>> int('32')32#错误的示例>>> int('Hello')ValueError: invalid literal for int(): Hello#从浮点到整型>>> int(3.99999)3>>> int(-2.3)-2#从整型到浮点型>>> float(32)32.0>>> float('3.14159')3.14159#从字符串(数字)到整型/浮点型>>> str(32)'32'>>> str(3.14159)'3.14159'
  • 随机数读取(进行随机数输出,需要读取模块random)
#通过import倒入模块random#函数random会返回一个在0.0到1.0之间的数,包含0.0,却不包含1.0。#range(10)表示从0-9循环import randomfor i in range(10):    x = random.random()print x#会得到类似以下的输出0.3019270917050.5137870758670.3194704308810.2851459172520.8390690451230.3220270807310.5507221102480.3665916778120.3969814839640.838116437404
#randint()函数会在指定的范围内返回一个整数。>>> random.randint(5, 10)5>>> random.randint(5, 10)9#或者以这种形式进行>>> t = [1, 2, 3]>>> random.choice(t)2>>> random.choice(t)3
  • 数学函数(需要调用math模块)
#在使用时需要先写模块名,然后点出函数名。>>> ratio = signal_power / noise_power>>> decibels = 10 * math.log10(ratio)>>> radians = 0.7>>> height = math.sin(radians)
  • 自己写函数(使用def关键字)
def print_lyrics():    print "I'm a lumberjack, and I'm okay."    print 'I sleep all night and I work all day.'

第五部分 循环

  • 使用while循环
n = 5while n > 0:      print n      n = n-1print 'Blastoff!'
  • 使用break终止循环(后面不加任何标点)
while True:      line = raw_input('> ')      if line == 'done':         break      print lineprint 'Done!'
  • continue终止当次循环(后面不加任何标点)
while True:      line = raw_input('> ')      if line[0] == '#' :         continue      if line == 'done':         break      print lineprint 'Done!'
  • for循环(for的第一个参数是之后要在循环中引用的参数,for的第二个参数是存储了循环值的列表)
friends = ['Joseph', 'Glenn', 'Sally']for friend in friends:      print 'Happy New Year:', friendprint 'Done!'
  • 一个求最大值的程序
#注意程序中使用print函数进行连接打印时,中间用逗号隔开。largest = Noneprint 'Before:', largestfor itervar in [3, 41, 12, 9, 74, 15]:      if largest is None or itervar > largest :         largest = itervar      print 'Loop:', itervar, largestprint 'Largest:', largest
#程序的输出Before: NoneLoop: 3 3Loop: 41 41Loop: 12 41Loop: 9 41Loop: 74 74Loop: 15 74Largest: 74

第六部分 字符串

  • 一般可以如此定义字符串
#定义字符串>>> fruit = 'banana'#取字符串中的第二个字母>>> letter = fruit[1]
  • 同样可以用len函数来判别字符串的长度
>>> fruit = 'banana'>>> len(fruit)6>>> length=len(fruit)>>> last= fruit[length-1]
  • 字符串截断([x:y]可以获得从x开始到y的前一个字符的子字符串,前后任意一方设置为空,而以为着到头/到尾)
>>> s = 'Monty Python'>>> print s[0:5]Monty>>> print s[6:13]Python
>>> fruit = 'banana'>>> fruit[:3]'ban'>>> fruit[3:]'ana'
  • 字符串可以相加
>>> greeting = 'Hello, world!'>>> new_greeting = 'J' + greeting[1:]>>> print new_greetingJello, world!
  • 计算一个字母的出现次数
word = 'banana'count = 0for letter in word:      if letter == 'a':          count = count + 1print count
  • in操作符(其是一个布尔运算符,它可以确认一个子字符串是否在一个字符串中,返回true或false)
>>> 'a' in 'banana'True>>> 'seed' in 'banana'False
  • 字符串的比较
#两个字符串可以直接比较,例如if word == 'banana':   print 'All right, bananas.'#同样,可以使用大小于if word < 'banana':   print 'Your word,' + word + ', comes before banana.'elif word > 'banana':   print 'Your word,' + word + ', comes after banana.'else:   print 'All right, bananas.'
  • 字符串的方法(函数)
    python有一个函数 dir,可以针对特定的类型,列出其所能进行的操作(函数方法),例如
>>> stuff = 'Hello world'>>> type(stuff)<type 'str'>>>> dir(stuff)['capitalize', 'center', 'count', 'decode', 'encode','endswith', 'expandtabs', 'find', 'format', 'index','isalnum', 'isalpha', 'isdigit', 'islower', 'isspace','istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip','partition', 'replace', 'rfind', 'rindex', 'rjust','rpartition', 'rsplit', 'rstrip', 'split', 'splitlines','startswith', 'strip', 'swapcase', 'title', 'translate','upper', 'zfill']
  • 函数find可以找出指定寻找对象的索引,例如
>>> word = 'banana'>>> index = word.find('a')>>> print index1
  • 使用strip方法可以去除字符串中的前后空白
>>> line = ' Here we go '>>> line.strip()'Here we go'
  • startswith函数是布尔函数,返回真假值
>>> line = 'Please have a nice day'>>> line.startswith('Please')True>>> line.startswith('p')False
  • 可以多个方法一起使用
>>> line = 'Please have a nice day'>>> line.startswith('p')False>>> line.lower()'please have a nice day'>>> line.lower().startswith('p')True
  • 格式化操作符
    该处存在两个%,在模板中的%加上字母表示以什么格式输出,第二个为模板和数据的分离符
>>> camels = 42>>> 'I have spotted %d camels.' % camels'I have spotted 42 camels.'

第七部分 文件

  • 打开文件
    打开文件后,仅仅只是建立了一个通道,把通道信息赋给fhand,所以对fhand进行打印操作时,输出的是打开文件的信息和打开方式与地址。
>>> fhand = open('mbox.txt')>>> print fhand<open file 'mbox.txt', mode 'r' at 0x1005088b0>
0 0
原创粉丝点击