1.Temperature conversion tables
Requirement: Run and study the program named fahrenheit_to_celsius.py. Then write a program named celsius_to_fahrenheit.py that displays a conversion table from Celsius degrees to Fahrenheit degrees, with the former ranging from 0 to 100 in steps of 10.
這題有兩個練習(xí)點(diǎn)膳汪,一個是built_in的range()函數(shù)唯蝶,另一個是格式化輸出。
1.1 range()
兩種寫法遗嗽,一種是單一參數(shù)range(stop)粘我,產(chǎn)生從0到stop-1數(shù)的arithmetic progressions,stop必須是int痹换,不可以是float等其他類型征字。range() generate的結(jié)果很像list,但并不是娇豫。按照3.6.2tutorial的定義匙姜,“ It is an object which returns the successive items of the desired sequence when you iterate over it, but it doesn’t really make the list, thus saving space.”為了表達(dá)方便,以下程序用list()將range產(chǎn)生的序列轉(zhuǎn)化為列表顯示冯痢。
list(range(4))
>>> [0, 1, 2, 3]
另一種是range(start, stop, step = 1)氮昧,如果start >= stop或详,產(chǎn)生空的arithmetic progressions。
print(list(range(-5, -1)))
print(list(range(2, 9, 2)))
print(list(range(3, 1)))
>>>
[-5, -4, -3, -2]
[2, 4, 6, 8]
[]
1.2格式化輸出
python3.5格式化輸出:%[(name)][flags][width].[precision]typecode
%標(biāo)記轉(zhuǎn)換說明符開始郭计;
(name)為命名霸琴;
flags有+, -, ' '或0:+表示右對齊且添加正號,-表示左對齊昭伸,' '為空格梧乘,表示在正數(shù)左側(cè)填充一個空格從而與負(fù)數(shù)對齊,0表示使用0填充對齊庐杨;
width表示寬度选调;
precision表示小數(shù)點(diǎn)后精度;
typecode是類型碼灵份。
類型碼
%s 字符串(使用str轉(zhuǎn)換任意python對象)
%r 字符串(使用repr轉(zhuǎn)換任意python對象)
%c 單個字符
%b 二進(jìn)制整數(shù)
%d 帶符號的十進(jìn)制整數(shù)
%i 帶符號的十進(jìn)制整數(shù)
%o 不帶符號的八進(jìn)制整數(shù)
%x 不帶符號的十六進(jìn)制整數(shù)(小寫)
%X 不帶符號的十六進(jìn)制整數(shù)(大寫)
%e 科學(xué)計數(shù)法表示的浮點(diǎn)數(shù)(基底寫為e)
%E 科學(xué)計數(shù)法表示的浮點(diǎn)數(shù)(基底寫為E)
%f 十進(jìn)制浮點(diǎn)數(shù)
%F 十進(jìn)制浮點(diǎn)數(shù)
%g 如果指數(shù)大于-4或者小于精度值則和e相同仁堪,其他情況和f相同
%G 如果指數(shù)大于-4或者小于精度值則和E相同,其他情況和F相同
%% 字符"%"
print("I'm %s. I'm %d year old." % ("Tom", 99))#簡單輸出
print("I'm %(name)s. I'm %(age)d year old." % {'name':'Tom', 'age':99})#(name)的映射
print("%10.3f" % 231.2345)#字段寬10填渠,精度3
print("%10.3f" % -231.2345)#負(fù)數(shù)弦聂,字段寬10,精度3
print("%*.3f" % (9, 231.2345))#用*從后面的元組中讀取字段寬度或精度
print("%+10.3f" % 231.2345)#右對齊氛什,加正號
print("%-10.3f" % 231.2345)#左對齊
print("% 10.3f" % 231.2345)#空格
print("%010.3f" % 231.2345)#用0填充空白
print("%x" % 33)
print("%X" % 33)
print("%e" % -231.2345)
print("%E" % -231.2345)
>>>
I'm Tom. I'm 99 year old.
I'm Tom. I'm 99 year old.
231.234
-231.234
231.234
+231.234
231.234
231.234
000231.234
21
21
-2.312345e+02
-2.312345E+02
python3.6之后有了更簡便的形式莺葫,用f引導(dǎo)輸出內(nèi)容進(jìn)行format。
name = 'Tom'
Age = 99
print(f"I'm {name}. I'm {Age:0.1f} year old.")
>>>
I'm Tom. I'm 99.0 year old.
除此之外枪眉,本題還涉及到\t的輸出位置控制捺檬。\t代表Tab,\t的下一個字符一定在從開始進(jìn)行計算的8的倍數(shù)的位置上贸铜。
print('Fahrenheit \tCelsius')
print('Celsius \tFahrenheit')
print('Fahrenheit\tCelsius')
print('Celsius\tFahrenheit')
for i in range(17):
print('a' * i, '\tb', sep ='')
text = 'I major in Information Technology in UNSW.'
for i in range(len(text)):
if text[i] == ' ':
print(text[:i], '\t', text[i+1:], sep = '')
>>>
Fahrenheit Celsius
Celsius Fahrenheit
Fahrenheit Celsius
Celsius Fahrenheit
b
a b
aa b
aaa b
aaaa b
aaaaa b
aaaaaa b
aaaaaaa b
aaaaaaaa b
aaaaaaaaa b
aaaaaaaaaa b
aaaaaaaaaaa b
aaaaaaaaaaaa b
aaaaaaaaaaaaa b
aaaaaaaaaaaaaa b
aaaaaaaaaaaaaaa b
aaaaaaaaaaaaaaaa b
I major in Information Technology in UNSW.
I major in Information Technology in UNSW.
I major in Information Technology in UNSW.
I major in Information Technology in UNSW.
I major in Information Technology in UNSW.
I major in Information Technology in UNSW.
1.3題目解析
min_temp = 0
max_temp = 100
step = 10
print('Celsius \tFahrenheit')
for celsius in range(min_temp, max_temp + step, step):
fahrenheit = celsius * 9 / 5 + 32
print("%7d \t%10.0f" % (celsius, fahrenheit))
#print(f"{celsius:7d} \t{fahrenheit:10.0f}")
>>>
Celsius Fahrenheit
0 32
10 50
20 68
30 86
40 104
50 122
60 140
70 158
80 176
90 194
100 212
2.Max element and span in a list
Requirement: Run and study the program max_in_list.py. Then write a program span.py that prompts the user for a seed for the random number generator, and for a strictly positive number, nb_of_elements, generates a list of nb_of_elements random integers between 0 and 99, prints out the list, computes the difference between the largest and smallest values in the list without using the builtins min() and max(), prints it out, and check that the result is correct using the builtins.
random.seed(X)堡纬,這里的X稱為隨機(jī)數(shù)種子,種子不同蒿秦,產(chǎn)生的隨機(jī)數(shù)序列也不同烤镐,反之。隨機(jī)數(shù)種子都是全局種子
from random import seed, randint
import sys
#from X import X是python運(yùn)行方法中講解過的內(nèi)容渤早,從random庫中導(dǎo)入了兩個函數(shù)seed, randint职车。
#seed用來確定隨機(jī)數(shù)產(chǎn)生的種子,目的是為了每次產(chǎn)生一樣的隨機(jī)數(shù)鹊杖,方便和Eric的PDF結(jié)果比照(所以說這是偽隨機(jī))
#randint根據(jù)seed隨機(jī)產(chǎn)生int
arg_for_seed = input('Input a seed for the random number generator: ')
#input的基礎(chǔ)方法,arg_for_seed應(yīng)該是argument for seed的含義
try:
arg_for_seed = int(arg_for_seed)
except ValueError:
print('Input is not an integer, giving up.')
sys.exit()
#exception的基礎(chǔ)方法扛芽,實驗輸入給arg_for_seed的變量是不是int骂蓖,如果不是拋出提示再終止程序。
nb_of_elements = input('How many elements do you want to generate? ')
try:
nb_of_elements = int(nb_of_elements)
except ValueError:
print('Input is not an integer, giving up.')
sys.exit()
if nb_of_elements <= 1:
print('Input should be strictly larger than 1, giving up.')
sys.exit()
#除了和arg_for_seed相同的類型異常檢驗外川尖,還要求產(chǎn)生的數(shù)據(jù)量必須是大于1的正數(shù)登下,否則無法完成span,拋出提示再終止程序。
seed(arg_for_seed)
L = [randint(0, 99) for _ in range(nb_of_elements)]
#循環(huán)語句的元素使用'_'的含義是告訴其他程序員這里循環(huán)的元素沒有實際作用被芳,換言之是為了符合語法而這樣表征的
print('\nThe list is:', L)
max_element = 0
min_element = 99
#初始化最大/小值缰贝,因為范圍是0-99,所以要把max和min都初始化到邊界值畔濒。
for e in L:
if e > max_element:
max_element = e
if e < min_element:
min_element = e
print('\nTThe maximum difference between largest and smallest values in this list is:', max_element - min_element)
print('Confirming with builtin operation:', max(L) - min(L))
3.Classifying elements in a list
Requirement: The operators /, // and % are used for floating point division, integer division, and remainder, respectively. Run and study the program named modulo_4.py . Then write a program named intervals.py that pPrompts the user for a strictly positive integer, nb_of_elements, generates a list of nb_of_elements random integers between 0 and 19, prints out the list, computes the number of elements strictly less 5, 10, 15 and 20, and prints those out.
from random import seed, randrange
import sys
#randrange(stop)是從0到stop-1產(chǎn)生隨機(jī)數(shù)
arg_for_seed = input('Input a seed for the random number generator: ')
try:
arg_for_seed = int(arg_for_seed)
except ValueError:
print('Input is not an integer, giving up.')
sys.exit()
nb_of_elements = input('How many elements do you want to generate? ')
try:
nb_of_elements = int(nb_of_elements)
except ValueError:
print('Input is not an integer, giving up.')
sys.exit()
if nb_of_elements <= 0:
print('Input should be strictly positive, giving up.')
sys.exit()
seed(arg_for_seed)
L = [randrange(20) for _ in range(nb_of_elements)]
#注意題中要求的range范圍變了
print('\nThe list is:' , L)
print()
quotient = [0] * 4
#創(chuàng)建一個list[0, 0, 0, 0]用來存儲L中小于5剩晴,10,15侵状,20數(shù)字的個數(shù)赞弥。
for i in range(nb_of_elements):
quotient[L[i] // 5] += 1
#L[i]//5是判斷每一個L中數(shù)字屬于哪個范圍,如果L[i]//5=3趣兄,即屬于15-19的范圍绽左,所以讓quotient[3]中記錄這個范圍個數(shù)的數(shù)字加1。
for i in range(4):
#range(4)是因為有4種情況的輸出艇潭,分別是小于5拼窥,10,15蹋凝,20
if quotient[i] == 0:
print('There is no element', end = ' ')
elif quotient[i] == 1:
print('There is 1 element', end = ' ')
else:
print(f'There are {quotient[i]} elements', end = ' ')
#分為三種情況是因為print的文字不同闯团,這些文字只處理到輸出內(nèi)容的'between'之前,所以print中要有end = ' '仙粱,這樣可以不換行房交。
print(f'between {i*5} and {i*5+4}.')
#處理各種情況輸出內(nèi)容從'between'到最后的部分
4.Statistics on numbers in a list
Requirement:Write a program named mean_median_standard_deviation.py that prompts the user for a strictly positive integer, nb_of_elements, generates a list of nb_of_elements random integers between -50 and 50, prints out the list, computes the mean, the median and the standard deviation in two ways, that is, using or not the functions from the statistics module, and prints them out.
import sys
from random import seed, randrange
from statistics import mean, median, pstdev
#增加了從statistic module導(dǎo)入function
arg_for_seed = input('Input a seed for the random number generator: ')
try:
arg_for_seed = int(arg_for_seed)
except ValueError:
print('Input is not an integer, giving up.')
sys.exit()
nb_of_elements = input('How many elements do you want to generate? ')
try:
nb_of_elements = int(nb_of_elements)
except ValueError:
print('Input is not an integer, giving up.')
sys.exit()
if nb_of_elements <= 0:
print('Input should be strictly positive, giving up.')
sys.exit()
seed(arg_for_seed)
L = [randrange(-50, 51) for _ in range(nb_of_elements)]
#randrange()這次輸入了兩個變量,下限和上限
print(f'\nThe list is: {L}')
print()
sort_L = sorted(L)
#對L進(jìn)行排序變成sort_L伐割,方便取median候味。這里不能用sort_L = L.sort(),因為sort()之后返回None
mean_sum = 0
for i in range(nb_of_elements):
mean_sum += sort_L[i]
mean_L = mean_sum / nb_of_elements
if nb_of_elements % 2 == 1:
median_L = float(sort_L[nb_of_elements//2])
else:
median_L = (sort_L[nb_of_elements//2] + sort_L[nb_of_elements//2-1])/2
pstdev_sum = 0
for i in range(nb_of_elements):
pstdev_sum += (sort_L[i] - mean_L) ** 2
pstdev_L = (pstdev_sum / nb_of_elements) ** 0.5
print(f'The mean is {mean_L:0.2f}.')
print(f'The median is {median_L:0.2f}.')
print(f'The standard deviation is {pstdev_L:0.2f}.\n')
print('Confirming with functions from the statistics module:')
print(f'The mean is {mean(L):0.2f}.')
print(f'The median is {median(L):0.2f}.')
print(f'The standard deviation is {pstdev(L):0.2f}.')
5.Drawing pictures with turtle
5.1 An hexagram
Requirement: write a program hexagram.py that draws an hexagram that is centred horizontally in the window that displays it, with the colour of the tips alternating red and blue.
Python Turtle Totorials (P.S. 源自LOGO語言)
Turtle的默認(rèn)初始方向是向右隔心。
from turtle import *
#從turtle module中導(dǎo)入所有function
edge_length = 60
angle = 120
def draw_triangle(colour, direction = 'up'):
#圖形是由兩個三角形組合而成白群,但是一個正三角一個倒三角,所以添加一個direction來控制
color(colour)
for _ in range(3):
fd(edge_length/3)
pu()
#抬筆硬霍,三角形邊的中間1/3不劃線
fd(edge_length/3)
pd()
fd(edge_length/3)
if direction == 'up':
lt(angle)
else:
rt(angle)
#正三角左轉(zhuǎn)帜慢,倒三角右轉(zhuǎn)
def change_origin():
pu()
lt(60)
fd(edge_length * 2 / 3)
lt(120)
fd(edge_length / 3)
rt(180)
pd()
#為了精確走到起始點(diǎn),走了三角形的路徑唯卖,而不是直線粱玲,因為直線的數(shù)值是不精確的。
draw_triangle('red')
change_origin()
draw_triangle('blue', 'down')
5.2 An octagram
Requirement: write a program octagram.py that draws an octagram, the inscribed octagon being coloured yellow, and the colour of the triangles alternating red and blue.
from turtle import *
import math
inscribed_length = 100 / (math.cos(math.pi/8))
#正八邊形內(nèi)部三角形的斜邊長
edge_length = 100 * (math.tan(math.pi/8)) * 2
#正八邊形的邊長
triangle_length = ((edge_length/2)**2 + 80**2)**0.5
#外嵌三角形的斜邊長
triangle_bottom_angle = math.atan(80/(edge_length/2))/(math.pi)*180
#外嵌三角形的底角角度值
print(inscribed_length, edge_length, triangle_length)
pu()
fd(inscribed_length)
lt(180-(180-45)/2)
pd()
#根據(jù)100的條件計算正八邊形內(nèi)部三角形斜邊長拜轨,準(zhǔn)備開始繪圖
def draw_triangle(colour):
color(colour)
begin_fill()
fd(edge_length)
rt(180-triangle_bottom_angle)
fd(triangle_length)
rt(2*triangle_bottom_angle)
fd(triangle_length)
rt(180-triangle_bottom_angle)
end_fill()
#畫外接三角形
pu()
fd(edge_length)
lt(360/8)
pd()
#轉(zhuǎn)移位置到下一個三角形
def draw_octagram(colour):
color(colour)
begin_fill()
for i in range(8):
fd(edge_length)
lt(360/8)
end_fill()
for i in range(8):
if i % 2 == 0:
draw_triangle('red')
else:
draw_triangle('blue')
#畫外圍8個三角形
draw_octagram('yellow')
#填充內(nèi)部八邊形