Python 簡介
出自KMU Wiki
(修訂版本間差異)
| 在2008年12月3日 (三) 11:05所做的修訂版本 (編輯) Cch (對話 | 貢獻) ←上一個 |
在2008年12月3日 (三) 14:46所做的修訂版本 (編輯) (撤銷) Cch (對話 | 貢獻) (→檢查一個數是否為質數) 下一個→ |
||
| 第34行: | 第34行: | ||
| ===檢查一個數是否為質數=== | ===檢查一個數是否為質數=== | ||
| + | #!/usr/local/bin/python | ||
| + | |||
| + | # This program tests wether an integer is a prime | ||
| + | |||
| + | import sys | ||
| + | import string | ||
| + | |||
| + | print 'This program tests wether an integer is a prime' | ||
| + | while 1 : | ||
| + | sys.stdout.write('Please input an integer: ') | ||
| + | s = raw_input() | ||
| + | n = string.atol(s) | ||
| + | ub = n / 2 + 1 | ||
| + | is_prime = 1 | ||
| + | f = 2 | ||
| + | while f < ub : | ||
| + | if n % f == 0: | ||
| + | is_prime = 0 | ||
| + | print n, ' has a factor ', f | ||
| + | break | ||
| + | else : | ||
| + | f = f + 1 | ||
| + | if is_prime == 1 : | ||
| + | print n, ' is a prime' | ||
| + | else : | ||
| + | print n, ' is not a prime' | ||
在2008年12月3日 (三) 14:46所做的修訂版本
本條目所指的 Python 是 Python 程式語言
目錄 |
概覽
A Byte of Python 對 Python 的簡介(中譯版)
根據 2008 年 11 月 TIOBE Programming Community Index,Python 的普及率在全世界排名第 6
免費電子書
下載
參考資料
練習
檢查一個數是否為質數
- !/usr/local/bin/python
- This program tests wether an integer is a prime
import sys import string
print 'This program tests wether an integer is a prime' while 1 :
sys.stdout.write('Please input an integer: ')
s = raw_input()
n = string.atol(s)
ub = n / 2 + 1
is_prime = 1
f = 2
while f < ub :
if n % f == 0:
is_prime = 0
print n, ' has a factor ', f
break
else :
f = f + 1
if is_prime == 1 :
print n, ' is a prime'
else :
print n, ' is not a prime'
