i=2
prime=0
num = int(input("輸入一個整數:"))
while (i<=num**0.5):
if (num%i==0):
prime=1
i+=1
if (prime==1):
print("%s不是質數"%num)
else:
print("%s是質數"%num)
num = int(input("請輸入一個數字: "))
if num > 1:
# 查看因子
for i in range(2,num):
if (num % i) == 0:
print(num,"不是質數")
print(i,"乘與",num//i,"是",num)
break
else:
print(num,"是質數")
# 如果輸入的數字小於或等於 1,不是質數
else:
print(num,"不是質數")
九九乘法表
for i in range(1,10):
for j in range(1,10):
print(i,"*",j," = ","%2d"%(i*j),sep='',end=' ')
print()
計算輸入的數的平均和總和
nums = count = 0
while True:
num = int(input("輸入一個成績"))
if num == -1:
print('總成績為:',nums,'平均成績為:',nums/count)
break
nums += num
count += 1
2017/10/12
2017/10/19
point = [
[-1, 3],
[-1, -1],
[1, 1],
[2, 0.5],
[2, -1],
[3, 3],
[4, 2],
[4, -0.5]
]
def distance(A, B):
return((A[0]-B[0])**2 + ((A[1]-B[1])**2))**0.5
for a in point:
for b in point:
print(round(distance(a,b),1),'',end='')
print()
輸出一亂數
判斷是否為奇數,若是的話就把這數字「*3+1」,若否的話就「/2」,這是一個迴圈,直到數字n變為1才停止
import random
rand_num = random.randint(100,1000)
orig_rand_num = rand_num
loop_count = 0
every_step = []
while True:
every_step.append(int(rand_num))
if(rand_num == 1): break
if(rand_num % 2 == 0):
rand_num = rand_num/2
else:
rand_num = rand_num*3 + 1
loop_count +=1
print("亂數 = ",orig_rand_num)
print("運算次數 = ",loop_count)
print("運算過程 : ",every_step)
建立一個字典
搜尋字典內的Key,然後輸出Value
name_dict = {}
key = ""
SearchKey = ""
print("Create dictionary:")
while key != "end":
key = input("key:")
if key == "end":
break
else:
value = input("value:")
name_dict[key] = value
while SearchKey != "end":
SearchKey = input("Search key:")
if SearchKey == "end":
break
else:
if(SearchKey in name_dict) == False:
print("Value:no such key")
else:
print("Value:"+name_dict[SearchKey])
open()使用方法
content = '''hello python
逢甲應用數學系
Welcome'''
f = open("file1.txt",'w')
f.write(content)
f.close()
f = open("file1.txt",'r')
for line in f:
print(line)
f.close()
with open("file1.txt",'r')as f:
for line in f:
print(line)
Tk1
import tkinter as tk
#主視窗名稱 = tk.Tk()
win = tk.Tk()
win.geometry("200x100")
win.title("這是主視窗")
lable = tk.Label(win,text = "hello world")
lable.pack()
cont = 0
def b():
global cont
cont += 1
textvar.set("按我")
lable.pack()
textvar = tk.StringVar()
button = tk.Button(win,textvariable = textvar,command = b)
textvar.set("按我")
button.pack()
win.mainloop()
Tk2
import tkinter as tk
win = tk.Tk()
win.title("這是主視窗")
frame1 = tk.Frame(win)
frame1.pack()
lable1 = tk.Label(frame1,text = "username:")
entry1 = tk.Entry(frame1)
lable1.grid(row = 0,column = 0)
entry1.grid(row = 0,column = 1)
frame2 = tk.Frame(win)
frame2.pack()
button1 = tk.Button(frame2,text = "yes")
button2 = tk.Button(frame2,text = "NO")
button1.grid(row = 0,column = 0)
button2.grid(row = 0,column = 1)
win.mainloop()
沒有留言:
張貼留言