python基础练习
1 ''' 2 Created on 2018年7月28日 3 4 @author: liupf 5 ''' 6 print("hello world!") 7 ''' 8 print("%s%%" % '23') 9 age = 10 10 if age >= 18: 11 print("your age is", age) 12 print("adult") 13 else: 14 print("your age is", age) 15 print("teenager") 16 17 s = input("birth: ") 18 birth = int(s) 19 if birth < 2000: 20 print('00前') 21 else: 22 print('00后') 23 -------------------------- 24 25 name = [ 'Michael', 'Bob', 'Tracy' ] 26 scores = [95, 75, 85] 27 d = {'Michael':95, 'Bob':75, 'Tracy':85} 28 29 print(d['Bob']) 30 d['Bob'] = 99 31 print(d['Bob']) 32 33 ------------------------------------ 34 35 s = set([1,2,3]) 36 print(s) 37 38 s.add(4) 39 print(s) 40 41 s.remove(4) 42 print(s) 43 44 s2 = set([2,3,4]) 45 s3 = s & s2 46 print(s3) 47 48 ss = s | s2 49 print(ss) 50 51 a = ['c', 'b', 'a'] 52 a.sort() 53 print(a) 54 55 a = 'abc' 56 b = a.replace('a', 'A') 57 print(b) 58 print(a.replace('a', 'A')) 59 print(a) 60 61 '''
1 ''' 2 def my_abs(x): 3 if not isinstance(x, (int, float)): 4 raise TypeErr("bad operand type") 5 if x>=0: 6 return x 7 else: 8 return -x 9 10 print(my_abs(-11)) 11 12 print(my_abs(9)) 13 ----------------------------------------- 14 15 import math 16 def move(x, y, step, angle=0): 17 nx = x + step * math.cos(angle) 18 ny = y - step * math.sin(angle) 19 return nx, ny 20 21 x, y = move(100, 100, 60, math.pi /6) 22 print(x, y) 23 24 #返回一个turple 25 r = move(100, 100, 60, math.pi /6) 26 print(r) 27 28 29 def quadratic(a, b, c): 30 delt = b*b-4*a*c 31 if delt >= 0: 32 sqrt_delt = math.sqrt(b*b-4*a*c) 33 return ((-1*b + sqrt_delt)/(2*a) , (-1*b - sqrt_delt)/(2*a)) 34 else: 35 print("复数解") 36 return (0,0) 37 38 a=2 39 b=3 40 c=1 41 42 print(quadratic(a,b,c)); 43 -------------------------------------- 44 45 #位置参数 46 def power(x): 47 return x*x; 48 49 def n_power(x, n = 2): 50 if not isinstance(x, (int)): 51 raise TypeErr("bad operand type") 52 s = 1 53 while n > 0: 54 n = n-1 55 s = s*x 56 return s 57 58 print(n_power(2)) 59 print(n_power(2,10)) 60 61 def add_end(L=None): 62 if L is None: 63 L=[] 64 L.append('END') 65 return L 66 67 print(add_end([1,2,3])) 68 print(add_end()) 69 print(add_end()) 70 71 72 #可变参数 73 #number 被作为一个tuple处理,number 可以是一个list 74 def calc(*number): 75 sum = 0 76 for n in number: 77 sum = sum + n*n 78 return sum 79 80 print(calc(1, 2, 3)) 81 82 #关键字参数 83 #允许传入任意个参数 84 def person(name, age, **kw): 85 print('name', name, 'age', age, 'other', kw) 86 87 person('Michael', 30, city='ab', job='worker') 88 89 extra = {'city':'Beijing', 'job':'Engineer'} 90 person('Jack', 24, city=extra['city'], job=extra['job']) 91 92 person('Jessy', 26, **extra) 93 94 95 #命名关键字参数 96 def person(name, age, **kw): 97 if 'city' in kw: 98 pass 99 if 'job' in kw: 100 pass 101 print('name:', name, 'age:', age, 'other:', kw) 102 103 person('Jack', 24, city='Beijing', addr='Chaoyang', zipcode=123456) 104 105 106 def product(*arg): 107 y = 1 108 for i in arg: 109 y = y*i 110 return y 111 112 print(product(5)) 113 print(product(5,6)) 114 print(product(5,6,7)) 115 print(product(5,6,7,9)) 116 ''' 117 118 ''' 119 尾递归是指,在函数返回的时候,调用自身本身,并且,return语句不能包含表达式。 120 这样,编译器或者解释器就可以把尾递归做优化,使递归本身无论调用多少次,都只 121 占用一个栈帧,不会出现栈溢出的情况。 122 ''' 123 ''' 124 def fact(n): 125 return fact_iter(n, 1) 126 127 def fact_iter(num, product): 128 if num == 1: 129 return product 130 return fact_iter(num-1, num*product) 131 132 133 134 from tkinter import * 135 import tkinter.messagebox as messagebox 136 137 class Application(Frame): 138 def __init__(self, master=None): 139 Frame.__init__(self, master) 140 self.pack() 141 self.createWidgets() 142 143 def createWidgets(self): 144 self.nameInput = Entry(self) 145 self.nameInput.pack() 146 self.alertButton = Button(self, text='Hello', command=self.hello) 147 self.alertButton.pack() 148 149 def hello(self): 150 name = self.nameInput.get() or 'world' 151 messagebox.showinfo('Message', 'Hello, %s' % name) 152 153 app = Application() 154 # 设置窗口标题: 155 app.master.title('Hello World') 156 # 主消息循环: 157 app.mainloop() 158 ------------------------------------------ 159 160 #汉诺塔 递归 161 def move(n, a, b, c): 162 if n == 1: 163 print('move', a, '-->', c) 164 else: 165 move(n-1, a, c, b) 166 move(1, a, b, c) 167 move(n-1, b, a, c) 168 169 move(4, 'A', 'B', 'C') 170 171 L = list(range(100)) 172 L1 = L[:]#复制了一个L对象,由L1指向之 173 174 L[0] = 9 175 print(L[0]) 176 print(L1[0]) 177 178 print((0,1,2,3,4,)[:3]) 179 ----------------------- 180 ''' 181 #实现trim函数,去除字符串前后的空格 182 def trim(s): 183 #起始位置 184 a = 0 185 #结束位置 186 b = 0 187 for c in s: 188 if c.isspace(): 189 a += 1 190 else: 191 break 192 193 for c in s: 194 if c.isspace(): 195 b += 1 196 else: 197 b = 0 198 b = len(s) - b 199 print(a,b) 200 return s[a:b] 201 202 #print(trim(' hello ')) 203 ''''''''' 204 205 #使用递归 206 def trim(s): 207 if s[:1] == ' ': 208 return trim(s[1:]) 209 elif s[-1:] == ' ': 210 return trim(s[:-1]) 211 else: 212 return s 213 214 215 s = ' hello ' 216 print(trim(s)) 217 ------------------------------------ 218 219 dict = {'a':1, 'b':2, 'c':3} 220 for key in dict: 221 print(key) 222 223 from collections import Iterable 224 225 a = 123 226 227 if( isinstance(a, Iterable)): 228 print(a, "is iterable") 229 print("%s is iterable" % a) 230 else: 231 print(a, "is not iterable") 232 print("%s is not iterable" % a) 233 234 ------------------------------------- 235 L = []#[1, 3, 4, 9] 236 237 def findMinAndMax(L): 238 if not len(L): 239 return (None, None) 240 max = min = L[0] 241 for i in L: 242 if (i < min): 243 min = i 244 if (i > max): 245 max = i 246 247 return (min, max) 248 249 print(findMinAndMax(L)) 250 251 print([m + n for m in 'ABC' for n in 'XYZ']) 252 253 import os 254 print([d for d in os.listdir('.')]) 255 256 d = {'x':'A', 'y':'B', 'z':'C'} 257 for v, k in d.items(): 258 print(k, '=', v) 259 260 --------------------------------------------- 261 L1 = ['Hello', 'World', 18, 'Apple', None] 262 #if条件放到了最后==! 263 L2 = [s.lower() for s in L1 if(isinstance(s, str))] 264 265 print(L2) 266 --------------------------------------------- 267 g = (x*x for x in range(10)) 268 for n in g: 269 print(n) 270 ------------------------- 271 272 def fib(max): 273 n, a, b = 0, 0, 1 274 while n < max: 275 print(b) 276 a, b = b, a+b 277 278 n = n+1 279 return 'done' 280 print(fib(3)) 281 282 def f(max): 283 n, a, b = 0, 0, 1 284 while n < max: 285 yield b 286 a, b = b, a+b 287 n = n+1 288 return 'done' 289 290 d = f(10) 291 for i in d: 292 print(i) 293 294 ''' 295 296 297 #杨辉三角 298 def triangles(): 299 a=[1] 300 while True: 301 yield a 302 a=[sum(i) for i in zip([0]+a,a+[0])] 303 n=0 304 for t in triangles(): 305 print(t) 306 n=n+1 307 if n == 10: 308 break