1. 程式人生 > >Python3學習筆記之基礎教程二

Python3學習筆記之基礎教程二

fibo.py

__author__ = 'Administrator'
def fib(n):
    a,b=0,1
    while b<n:
        print(b,end=' ')
        a,b=b,a+b
    print()
def fib2(n):
    result=[]
    a,b=0,1
    while b<n:
        result.append(b)
        a,b=b,a+b
    return result
if __name__ == '__main__':
	print('fibo.py 程式自身在執行')
else:
	print('fibo.py來自另一模組')


main.py
__author__="xxx"

#http://www.w3cschool.cc/python3/python3-module.html

#模組的呼叫
import fibo
print(fibo.fib(1000))
print(fibo.fib2(100))

#直接把模組內(函式,變數的)名稱匯入到當前操作模組。
#但是那些由單一下劃線(_)開頭的名字不在此例
from fibo import fib,fib2
print(fib(500))
print(fib2(5000))

#每個模組都有一個__name__屬性,當其值是'__main__'時,表明該模組自身在執行,否則是被引入。
if __name__ == '__main__':
	print('程式自身在執行')
else:
	print('我來自另一模組')
#dir() 函式會羅列出當前定義的所有名稱:
print(dir())
print(dir(fibo))
import sys
print(dir(sys))
#格式化字串
s = 'Hello, world.'
print(str(s))
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(math.pi)
print('The value of PI is approximately %5.3f.' % math.pi)
#操作檔案
import os
name="test.txt"
if os._exists(name):
    os.remove(name)
f = open(name, 'w+')
f.write('0123456789abcdef')
f.seek(0)
print(f.readline())
f.seek(5)     # 移動到檔案的第六個位元組
print(f.read(1))
#f.seek(-3, 2) # 移動到檔案的倒數第三位元組

f.close()
#try catch
try:
    f = open('test.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 this_fails():
        x = 1/0
try:
    this_fails()
except ZeroDivisionError as err:
    print('Handling run-time error:', err)
#自定義異常
class MyError(Exception):
        def __init__(self, value):
            self.value = value
        def __str__(self):
            return repr(self.value)
try:
    raise MyError("fuck")
    # raise MyError(2*2)
except MyError as e:
    print('My exception occurred, value:', e.value)
#http://www.w3cschool.cc/python3/python3-errors-execptions.html

__author__="xxx"

#類定義
class people:
    #定義基本屬性
    name = ''
    age = 0
    #定義私有屬性,私有屬性在類外部無法直接進行訪問
    __weight = 0
    #定義構造方法
    def __init__(self,n,a,w):
        self.name = n
        self.age = a
        self.__weight = w
    def speak(self):
        print("%s is speaking: I am %d years old weight=%s" %(self.name,self.age,self.__weight))

p = people('tom',10,30)
p.speak()

#單繼承示例
class student(people):
    grade = ''
    def __init__(self,n,a,w,g):
        #呼叫父類的構函
        people.__init__(self,n,a,w)
        self.grade = g
    #覆寫父類的方法
    def speak(self):
        print("%s is speaking: I am %d years old,and I am in grade %d"%(self.name,self.age,self.grade))
s = student('ken',20,60,3)
s.speak()

#另一個類,多重繼承之前的準備
class speaker():
    topic = ''
    name = ''
    def __init__(self,n,t):
        self.name = n
        self.topic = t
    def speak(self):
        print("I am %s,I am a speaker!My topic is %s"%(self.name,self.topic))

#多重繼承
class sample(speaker,student):
    a =''
    def __init__(self,n,a,w,g,t):
        student.__init__(self,n,a,w,g)
        speaker.__init__(self,n,t)

test = sample("Tim",25,80,4,"Python")
test.speak()#方法名同,預設呼叫的是在括號中排前地父類的方法

#http://www.w3cschool.cc/python3/python3-stdlib.html
import os
print(os.getcwd())
print(dir(os))
#print(help(os))
import glob
print(glob.glob('*.py'))
import math
print(math.cos(math.pi / 4))

import random
print(random.choice(['apple', 'pear', 'banana']))
print( random.sample(range(100), 10))   # sampling without replacement
print(random.random())   # random float
print(random.randrange(6))    # random integer chosen from range(6)

from datetime import date
now = date.today()
print(now)