1. 程式人生 > >python 常用語法已經方法

python 常用語法已經方法


#python test
# coding:utf-8
import json
from MyClass001 import MyClass001
import bisect
import sys
from xml.dom.minidom import parse
import xml.dom.minidom
import xml.sax
import time
import random
#建立int 變數並賦值
a =123
#建立 float 變數並賦值
b=923.63
print(f"result{a}{b}");
#建立 int 陣列
c=[1,2,3,4,5,6,7,8,9]
#遍歷int陣列
for x in c:
    print(x);
arrr1 = [1, 4, 2, 5, 3, 7, 9, 0] 
#sort 排序
print("sort 排序")
arrr1.sort()
for x in arrr1:
   print(x)
#氣泡排序
print("氣泡排序1")
#整型陣列
arrr = [1, 4, 2, 5, 3, 7, 9, 0] 
# range是範圍的意思
for u in  range(0, len(arrr), 1):
     for n in  range(0, len(arrr)-u-1, 1):
        if arrr[n]> arrr[n+1]:
            temp=arrr[n+1]
            arrr[n+1]=arrr[n]
            arrr[n]=temp
for c in arrr:
     print(c)        
#整型陣列
arr = [1, 4, 2, 5, 3, 7, 9, 0] 
print("氣泡排序2")
for i in range(0, len(arr), 1):
    for j in range(0, len(arr)-i-1, 1):
        if arr[j] > arr[j+1]:
            temp = arr[j+1]
            arr[j+1] = arr[j]
            arr[j] = temp
#遍歷int 陣列
for i in arr:
    print(i, end="\t")
print("\n一個簡單的類例項\n")
#面向物件
class MyClass:
    i = 4561235689
    def f(self):
        return 'hello world'
# 例項化類
x = MyClass()
# 訪問類的屬性和方法
print("MyClass 類的屬性 i 為:", x.i)
print("MyClass 類的方法 f 輸出為:", x.f())

# Python 字典型別轉換為 JSON 物件
data = {
    'no' : 1,
    'name' : 'Runoob',
    'url' : 'http://www.runoob.com'
}
json_str = json.dumps(data)
print ("Python 原始資料:", repr(data))
print ("JSON 物件:", json_str)
# 將 JSON 物件轉換為 Python 字典
data2 = json.loads(json_str)
print ("data2['name']: ", data2['name'])
print ("data2['url']: ", data2['url'])

#讀寫檔案方法0 hello i  love chinas
print("讀寫檔案")
try:
    f = open('C:\\124.txt', 'r')
    print(f.read())
finally:
    if f:
        f.close()
print("寫檔案")
try:
   f = open('C:\\124.txt', 'a+') # 若是'wb'就表示寫二進位制檔案 w 建立或清除重寫,a+ 建立或追加
   f.write('\nHello, world!\n')
finally:
    if f:
        f.close()

#讀取檔案 方法1

print("讀寫檔案方法1")
try:
   f = open('C:\\124.txt', 'r')
   lines = f.readlines()      #讀取全部內容 ,並以列表方式返回 
   for x in lines:
       print(f"{x}\n")
finally:
    if f:
        f.close()
# 讀取檔案方法2
print("讀取檔案方法2")
try:
    with  open("C:\\124.txt","r") as f:
        print(f.read());
except :
#解析xml
#<collection shelf="New Arrivals">
#<movie title="Enemy Behind">
  # <type>War, Thriller</type>
  # <type>War, Thriller</type>
  # <format>DVD</format>
  # <year>2003</year>
 #  <rating>PG</rating>
  # <stars>10</stars>
  # <description>Talk about a US-Japan war</description>
#</movie>
#<movie title="Transformers">
 #  <type>Anime, Science Fiction</type>
 #  <format>DVD</format>
#   <year>1989</year>
 #  <rating>R</rating>
#   <stars>8</stars>
#   <description>A schientific fiction</description>
#</movie>
#   <movie title="Trigun">
 #  <type>Anime, Action</type>
 #  <format>DVD</format>
 #  <episodes>4</episodes>
 #  <rating>PG</rating>
 #  <stars>10</stars>
 #  <description>Vash the Stampede!</description>
#</movie>
#<movie title="Ishtar">
  # <type>Comedy</type>
  # <format>VHS</format>
 #  <rating>PG</rating>
  # <stars>2</stars>
  # <description>Viewable boredom</description>
#</movie>
#</collection>

# 使用minidom解析器開啟 XML 文件
DOMTree = xml.dom.minidom.parse("c:\\movies.xml")
collection = DOMTree.documentElement
if collection.hasAttribute("shelf"):
   print ("Root element : %s" % collection.getAttribute("shelf"))

# 在集合中獲取所有電影
movies = collection.getElementsByTagName("movie")

# 列印每部電影的詳細資訊
for movie in movies:
   print ("*****Movie*****")
   if movie.hasAttribute("title"):
      print ("Title: %s" % movie.getAttribute("title"))

   type = movie.getElementsByTagName('type')[0]
   print ("Type: %s" % type.childNodes[0].data)
   format = movie.getElementsByTagName('format')[0]
   print ("Format: %s" % format.childNodes[0].data)
   rating = movie.getElementsByTagName('rating')[0]
   print ("Rating: %s" % rating.childNodes[0].data)
   description = movie.getElementsByTagName('description')[0]
   print ("Description: %s" % description.childNodes[0].data)
  
#Python int與string之間的轉化
#string-->int
#10進位制string轉化為int
print(int('12'))
#16進位制string轉化為int
print(int('12', 16))
#int-->string
#int轉化為10進位制string
print(str(18))
#int轉化為16進位制string
print(hex(18))
#獲取時間資訊
print("獲取時間資訊")
datetime = time.localtime(time.time())
print(time.strftime('%Y-%m-%d',datetime))
strDateTime = time.strftime('%Y-%m-%d %H:%M:%S',datetime)
print(strDateTime)
#類的物件處理
print("類的物件處理")
myclass001=MyClass001;
myclass001.getuserinfo(myclass001)
myclass001.mywork()
myclass001.getramd()
myclass001.getramd()
print("產生隨機數字")
print(random.randint(100,1258489))
#退出
print("\n\n按下 e 鍵後退出。")
l=input()
print(l)
if l == "e":
   
    print("yes")
else:
    print("no")
input()