exercise 37 符号复习-待续

来源:互联网 发布:seo网络营销技术 编辑:程序博客网 时间:2024/06/03 20:24

Keywords

KeywordDescriptionExampleandLogical and.True and False == FalseasPart of the with-as statement.with X as Y: passassertAssert (ensure) that something is true.assert False, "Error!"breakStop this loop right now.while True: breakclassDefine a class.class Person(object)continueDon't process more of the loop, do it again.while True: continuedefDefine a function.def X(): passdelDelete from dictionary.del X[Y]elifElse if condition.if: X; elif: Y; else: JelseElse condition.if: X; elif: Y; else: JexceptIf an exception happens, do this.except ValueError, e: print eexecRun a string as Python.exec 'print "hello"'finallyExceptions or not, finally do this no matter what.finally: passforLoop over a collection of things.for X in Y: passfromImporting specific parts of a module.from x import YglobalDeclare that you want a global variable.global XifIf condition.if: X; elif: Y; else: JimportImport a module into this one to use.import osinPart of for-loops. Also a test of X in Y.for X in Y: pass also1 in [1] == TrueisLike == to test equality.1 is 1 == TruelambdaCreate a short anonymous function.s = lambda y: y ** y; s(3)notLogical not.not True == FalseorLogical or.True or False == TruepassThis block is empty.def empty(): passprintPrint this string.print 'this string'raiseRaise an exception when things go wrong.raise ValueError("No")returnExit the function with a return value.def X(): return YtryTry this block, and if exception, go to except.try: passwhileWhile loop.while X: passwithWith an expression as a variable do.with X as Y: passyieldPause here and return to caller.def X(): yield Y;X().next()

Data Types

For data types, write out what makes up each one. For example, with strings write out how you create a string. For numbers write out a few numbers.

TypeDescriptionExampleTrueTrue boolean value.True or False == TrueFalseFalse boolean value.False and True == FalseNoneRepresents "nothing" or "no value".x = NonestringsStores textual information.x = "hello"numbersStores integers.i = 100floatsStores decimals.i = 10.389listsStores a list of things.j = [1,2,3,4]dictsStores a key=value mapping of things.e = {'x': 1, 'y': 2}

String Escape Sequences

For string escape sequences, use them in strings to make sure they do what you think they do.

EscapeDescription\\Backslash\'Single-quote\"Double-quote\aBell\bBackspace\fFormfeed\nNewline\rCarriage\tTab\vVertical tab

String Formats

Same thing for string formats: use them in some strings to know what they do.

EscapeDescriptionExample%dDecimal integers (not floating point)."%d" % 45 == '45'%iSame as %d."%i" % 45 == '45'%oOctal number."%o" % 1000 == '1750'%uUnsigned decimal."%u" % -1000 =='-1000'%xHexadecimal lowercase."%x" % 1000 == '3e8'%XHexadecimal uppercase."%X" % 1000 == '3E8'%eExponential notation, lowercase 'e'."%e" % 1000 == '1.000000e+03'%EExponential notation, uppercase 'E'."%E" % 1000 == '1.000000E+03'%fFloating point real number."%f" % 10.34 == '10.340000'%FSame as %f."%F" % 10.34 == '10.340000'%gEither %f or %e, whichever is shorter."%g" % 10.34 == '10.34'%GSame as %g but uppercase."%G" % 10.34 == '10.34'%cCharacter format."%c" % 34 == '"'%rRepr format (debugging format)."%r" % int == "<type'int'>"%sString format."%s there" % 'hi' == 'hi there'%%A percent sign."%g%%" % 10.34 == '10.34%'

Operators

Some of these may be unfamiliar to you, but look them up anyway. Find out what they do, and if you still can't figure it out, save it for later.

OperatorDescriptionExample+Addition2 + 4 == 6-Subtraction2 - 4 == -2*Multiplication2 * 4 == 8**Power of2 ** 4 == 16/Division2 / 4.0 == 0.5//Floor division2 // 4.0 == 0.0%String interpolate or modulus2 % 4 == 2<Less than4 < 4 == False>Greater than4 > 4 == False<=Less than equal4 <= 4 == True>=Greater than equal4 >= 4 == True==Equal4 == 5 == False!=Not equal4 != 5 == True<>Not equal4 <> 5 == True( )Parenthesislen('hi') == 2[ ]List brackets[1,3,4]{ }Dict curly braces{'x': 5, 'y': 10}@At (decorators)@classmethod,Commarange(0, 10):Colondef X():.Dotself.x = 10=Assign equalx = 10;semi-colonprint "hi"; print "there"+=Add and assignx = 1; x += 2-=Subtract and assignx = 1; x -= 2*=Multiply and assignx = 1; x *= 2/=Divide and assignx = 1; x /= 2//=Floor divide and assignx = 1; x //= 2%=Modulus assignx = 1; x %= 2**=Power assignx = 1; x **= 2
新知识点:
1.Assert 用法:
mylist = ['item']assert len(mylist) >= 1   ##此时列表里有一个元素‘item’ 使用assert语句时,语句正确 无报错mylist.pop()              ##pop函数默认移除列表中最后一个元素 即将列表中唯一元素删除assert len(mylist) >= 1   ##此时列表为空 长度小于1 语句错误 显示AssertionError

显示

Traceback (most recent call last):  File "C:/Users/xhu63/PycharmProjects/untitled/assert.py", line 7, in <module>    assert len(mylist) >= 1AssertionError

2.Except 用法:(跟try raise finally 一起处理异常 有点混乱!!!!!  下面网址有所有)

http://www.cnblogs.com/ybwang/archive/2015/08/18/4738621.html

这是应用实例:http://blog.csdn.net/u013088799/article/details/39100881

try:    <语句>except <name>:    <语句>          #如果在try部份引发了名为'name'的异常,则执行这段代码else:    <语句>          #如果没有异常发生,则执行这段代码

处理异常的三种方法:

1)捕获所有异常  

try:  
    a=b  
    b=c  
except Exception,e:  
    printException,":",e

2)采用trackback模块查看异常

#引入python中的traceback模块,跟踪错误
import traceback  
try:  
    a=b  
    b=c  
except:  
    traceback.print_exc()

3)采用sys模块回溯异常

#引入sys模块
import sys  
try:  
    a=b  
    b=c  
except:  
    info=sys.exc_info()  
    printinfo[0],":",info[1]

try: <...............>  #可能得到异常的语句except <.......>:      #锁定是哪种异常    <...............>  #出现异常的处理方法

3. exec 用法:

exec语句用来执行储存在字符串或者文件中的python语句。可以生成一个包含python代码的字符串,然后使用exec语句执行这些语句。

>>>exec 'print "hello word"'hello world

4. yeild用法:

5.finally 用法:


0 0