1. 程式人生 > >Python簡單例項

Python簡單例項

1,基礎語法

1)print自帶換行,取消換行?
x=raw_input()
y=raw_input()
z=raw_input()
lst=[]
lst.append(x)
lst.append(y)
lst.append(z)
lst.sort()
for i in range(0,3):
    print lst[i],
2)變數交換
a=1
b=2
a,b=b,a
print a,b
3)string.zfill()

str.zfill(x),在str前面填充0,以達到x寬度;
string.zfill(x,y),在x前面填充0,以達到y寬度。

import
string for i in range(6): print string.zfill(i,5) str="hello" print str.zfill(10)

output

00000
00001
00002
00003
00004
00005
00000hello

2,輸出九九乘法表

for i in range(1,10):
    for j in range(1,i+1):
        print i,'*',j,'=',i*j,
    print ''

3,輸出1-100之間的素數

import math
for i in range(1,101):
    if i==1:
        continue
else: flag=1 for j in range(2,int(math.sqrt(i))+1): if i%j==0: flag=0 break if(flag==1): print i

4,列印水仙花數

for i in range(1,10000+1):
    tmp=i
    s=0
    while(tmp!=0):
        s+=pow(tmp%10,3)
        tmp/=10
    if
(s==i): print i

5,分解質因數

import math
x=int(raw_input("raw_input"))
i=2
k=x
while(i<=k):
    if(x%i==0):
        x/=i
        if(x==1):
            print i
            break
        else:
            print i,'*',
    else:
        i+=1

6,統計字串中的字母,空格,數字及其他的個數

s=raw_input()
alpha=0
space=0
digit=0
other=0
for c in s:
    if c.isalpha():
        alpha+=1
    elif c.isspace():
        space+=1
    elif c.isdigit():
        digit+=1
    else:
        other+=1
print alpha,space,digit,other

7,素數快速打表(篩選法)

import math
lst=[1]*104
for i in range(2,int(math.sqrt(100))+1):
    if lst[i]==1:
        for j in range(i*2,100,i):
            lst[j]=0
for i in range(2,100):
    if lst[i]==1:
        print i,' '

8,排序

1)呼叫內嵌函式sort對list排序
a=[]
for i in range(5):
    a.append(int(raw_input()))
a.sort()
for i in range(5):
    print a[i],' ',
2)氣泡排序
a=[]
for i in range(5):
    a.append(int(raw_input()))
tmp=0
for i in range(5):
    for j in range(5-i-1):
        if (a[j]>a[j+1]):
            tmp=a[j]
            a[j]=a[j+1]
            a[j+1]=tmp 
for i in range(5):
    print a[i],' ',

9,list的使用

1)list的插入與遍歷
a=[0,10,20,30,40,50]
x=int(raw_input())
for i in range(0,len(a)):
    if a[i]>x:
        a.insert(i,x)
        break
for y in a:
    print y,

10,檔案讀寫

#-*-coding:utf-8-*-
f=open("test.txt",'w')
f.write("hello world ")
f.write("hello python ")
f.close()

f=open("test.txt",'r')
content=f.readlines() #讀取檔案中的所有行,儲存在列表中
print type(content)
for i in range(len(content)):
    print content[i],

output:

<type 'list'>
hello world hello python