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.
这题有两个练习点,一个是built_in的range()函数,另一个是格式化输出。
1.1 range()
两种写法,一种是单一参数range(stop),产生从0到stop-1数的arithmetic progressions,stop必须是int,不可以是float等其他类型。range() generate的结果很像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.”为了表达方便,以下程序用list()将range产生的序列转化为列表显示。
list(range(4))
>>> [0, 1, 2, 3]
另一种是range(start, stop, step = 1),如果start >= stop,产生空的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
%标记转换说明符开始;
(name)为命名;
flags有+, -, ' '或0:+表示右对齐且添加正号,-表示左对齐,' '为空格,表示在正数左侧填充一个空格从而与负数对齐,0表示使用0填充对齐;
width表示宽度;
precision表示小数点后精度;
typecode是类型码。
类型码
%s 字符串(使用str转换任意python对象)
%r 字符串(使用repr转换任意python对象)
%c 单个字符
%b 二进制整数
%d 带符号的十进制整数
%i 带符号的十进制整数
%o 不带符号的八进制整数
%x 不带符号的十六进制整数(小写)
%X 不带符号的十六进制整数(大写)
%e 科学计数法表示的浮点数(基底写为e)
%E 科学计数法表示的浮点数(基底写为E)
%f 十进制浮点数
%F 十进制浮点数
%g 如果指数大于-4或者小于精度值则和e相同,其他情况和f相同
%G 如果指数大于-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)#负数,字段宽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引导输出内容进行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的下一个字符一定在从开始进行计算的8的倍数的位置上。
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称为随机数种子,种子不同,产生的随机数序列也不同,反之。随机数种子都是全局种子
from random import seed, randint
import sys
#from X import X是python运行方法中讲解过的内容,从random库中导入了两个函数seed, randint。
#seed用来确定随机数产生的种子,目的是为了每次产生一样的随机数,方便和Eric的PDF结果比照(所以说这是伪随机)
#randint根据seed随机产生int
arg_for_seed = input('Input a seed for the random number generator: ')
#input的基础方法,arg_for_seed应该是argument for seed的含义
try:
arg_for_seed = int(arg_for_seed)
except ValueError:
print('Input is not an integer, giving up.')
sys.exit()
#exception的基础方法,实验输入给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相同的类型异常检验外,还要求产生的数据量必须是大于1的正数,否则无法完成span,抛出提示再终止程序。
seed(arg_for_seed)
L = [randint(0, 99) for _ in range(nb_of_elements)]
#循环语句的元素使用'_'的含义是告诉其他程序员这里循环的元素没有实际作用,换言之是为了符合语法而这样表征的
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产生随机数
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
#创建一个list[0, 0, 0, 0]用来存储L中小于5,10,15,20数字的个数。
for i in range(nb_of_elements):
quotient[L[i] // 5] += 1
#L[i]//5是判断每一个L中数字属于哪个范围,如果L[i]//5=3,即属于15-19的范围,所以让quotient[3]中记录这个范围个数的数字加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的文字不同,这些文字只处理到输出内容的'between'之前,所以print中要有end = ' ',这样可以不换行。
print(f'between {i*5} and {i*5+4}.')
#处理各种情况输出内容从'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导入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进行排序变成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的默认初始方向是向右。
from turtle import *
#从turtle module中导入所有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)
#正三角左转,倒三角右转
def change_origin():
pu()
lt(60)
fd(edge_length * 2 / 3)
lt(120)
fd(edge_length / 3)
rt(180)
pd()
#为了精确走到起始点,走了三角形的路径,而不是直线,因为直线的数值是不精确的。
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))
#正八边形内部三角形的斜边长
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()
#根据100的条件计算正八边形内部三角形斜边长,准备开始绘图
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()
#转移位置到下一个三角形
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')
#填充内部八边形