附录A 简明教程

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010819416/article/details/82288271

A1 基础知识
变量没有类型。
语句块只能通过缩进来表示。

x = 1
if x < 5 or (x > 10 and x < 20):
    print("The Value is OK.")

if x < 5 or 10 < x < 20:
    print("The value is OK.")

for i in [1,2,3,4,5]:
    print('This is iteration number', i)

x = 10
while x >= 0:
    print("x is still not negative.")
    x = x - 1

输入和输出:

x = float(input("Please enter a number: "))
print("The square of that number is ", x * x)

列表:
列表是使用方括号表示的,自然可以嵌套
可通过索引和切片访问其单个元素或一系列元素。

字典:
字典的每个元素都有键,可用来查找元素。

person = {"firstName":"Robin","lastName":"Hood","occupation":"Scoundrel"}
print(person['firstName'])

A2 函数
使用关键字def定义函数

def square(x):
    return x * x

print(square(2))

A3 对象及相关内容

使用关键字class来定义类

class Basket:

    # 千万别忘了参数self
    def __init__(self,contents=None):
        self.contents = contents or []

    def add(self, element):
        self.contents.append(element)

    def print_me(self):
        result = ""
        for element in self.contents:
            result = result + " " + repr(element)
        print("Contains:",result)

b = Basket([])
b.add(1)
b.print_me()

短路逻辑:
self.contents = contents or []
如果contents为真,则返回contents,否则返回[]

构造方法:

__init__

默认打印方法:

__str__

派生子类,支持多继承,括号内指定多个逗号分隔的超类:
class SpamBasket(Basket):
#…

实例化类:
x = Basket()

A4 知识点补充

在程序中可以通过导入来使用这些函数和类

import math
x = math.sqrt(y)

或者:

from math import sqrt
x = sqrt(y)

让程序即是可导入的模块又是可运行的程序,在末尾添加类似下面的代码:

# 如果这个模块是作为可执行的脚本运行的,就调用函数man。
if __name__ == "__main__": main()

在UNIX中,要创建可执行的脚本,可将下面的代码作为第一行:

#!/usr/bin/env python

异常:

def safe_division(a,b):
    try:
        return a/b
    except ZeroDivisionError: pass

学习箴言:利用源代码进行学习。

猜你喜欢

转载自blog.csdn.net/u010819416/article/details/82288271