python 简单的python入门语法
当前位置:以往代写 > Python教程 >python 简单的python入门语法
2019-06-14

python 简单的python入门语法

python 简单的python入门语法
python">#!/usr/bin/python3

# 开始学习python
print("hello,world")

# 条件语句
a, b = 3, 1
if a < b:
    print('a({}) is less than b({})'. format(a,b))
else:
    print('a({}) is great than b({})'. format(a,b))

# ?: 模仿三元表达式
print("foo" if a < b else "bar");

# while循环 fabonacci
a,b = 0,1 # 赋值 a = 0 , b = 1

while b < 50:
    print(b)
    a, b = b, a+b

print("Done.")  

# for循环,迭代输出文本信息
#lines.txt
#01 This is a line of text
#02 This is a line of text
#03 This is a line of text
#04 This is a line of text
#05 This is a line of text

fh = open("lines.txt")
for line in fh.readlines():
    print(line, end='')

# 计算素数的函数,素数(只能被1和自己整除的数)
def isprime(n):
    if n == 1:
        #print("1 is special")
        return False
    for x in range(2, n):
        if n%x == 0:
            #print("{} equals {} x {}".format(n, x, n // x))
            return False
    else:
        #print(n, "is a prime")
        return True

for n in range(1, 30):
    isprime(n)

# 迭代函数 primes, phper表示很难理解.
# yield返回当前的素数,primes下次迭代时,将会从yield返回的数字开始。

def primes(n = 1):
    while(True):
        if isprime(n): yield n
        n += 1

for n in primes():
    if n > 100: break
    print(n)

# oop 基本类的定义
class Fibonacci():
    def __init__(self, a, b):
        self.a = a
        self.b = b
    # 含有yield语法的应该都是一个构造器,可以内部迭代
    def series(self):
        while (True):
            yield(self.b)
            self.a, self.b = self.b, self.a + self.b

# 迭代构造器 Fibonacci.series()
f = Fibonacci(0,1)
for r in f.series():
    if r > 100: break
    print(r, end=' ')

# 一个简单的mvc模式
# oop2 继承与多态,高级概念
# Duck,Person,Dog都继承AnimalActions

# --- VIEW ---
class AnimalActions:
    def quack(self): return self._doAction('quack')
    def feathers(self): return self._doAction('feathers')
    def bark(self): return self._doAction('bark')
    def fur(self): return self._doAction('fur')

    def _doAction(self, action):
        if action in self.strings:
            return self.strings[action]
        else:
            return "The {} has no {}".format(self.animalName(), action)

    def animalName(self):
        return self.__class__.__name__.lower()

# --- MODEL ---
class Duck(AnimalActions):
    strings = dict(
        quack = "Quaaaak!",
        feathers = "The duck has gray and white feathers."      
    )

class Person(AnimalActions):
    strings = dict(
        quack = "The person iitates a duck!",
        feathers = "The person takes a feather from the ground and shows it.",
        bark = "The person says woof.",
        fur = "The person puts on a fur coat."
    )

class Dog(AnimalActions):
    strings = dict(        
        bark = "Arf!",
        fur = "The dog has white fur with black spots."
    )

# --- CONTROLLER ---
def in_the_doghouse(dog):
    print(dog.bark())
    print(dog.fur())

def in_the_forest(duck):
    print(duck.quack())
    print(duck.feathers())

def main():
    donald = Duck()
    john = Person()
    fido = Dog()
    # 三个对象都能在不同的地方拥有同样的行为
    print("- In the forest:")
    for o in ( donald, john, fido ):
        in_the_forest(o)

    print("- In the doghouse:")
    for o in ( donald, john, fido ):
        in_the_doghouse(o)

if __name__ == '__main__': main()

# 异常 phper表示很强大
# 尝试打开一个不存在的文件
try:
    fh = open("xline.txt")
    for line in fh.readlines():
        print(line)
except IOError as e:
    print("something bad happend {}.".format(e))

标签:python

    关键字:

在线提交作业