最近在学Python,写了一些简单的小程序,先记录下来。。。。
1 # 判断狗的年龄 2 age = int(input("Age of the dog: ")) 3 print() 4 if age < 0: 5 print("This can hardly be true!") 6 elif age == 1: 7 print("about 14 human years") 8 elif age == 2: 9 print("about 22 human years") 10 elif age > 2: 11 human = 22 + (age - 2) * 5 12 print("Human years: ", human) 13 14 input('press Return>') 15 16 # 求和 17 n = 100 18 sum = 0 19 counter = 1 20 while counter <= n: 21 sum = sum + counter 22 counter += 1 23 24 print("sum of 1 umtil %d: %d" % (n, sum)) 25 26 列表for循环遍历 27 arr = ['w', 'y', 'j'] 28 for x in arr: 29 print(x) 30 if x == 'y': 31 break 32 else: 33 print("ok") 34 35 # print不换行 36 arr = ['my', 'name', 'is', 'jack'] 37 a = '' 38 for i in arr: 39 a = a + i + ' ' 40 print(a) 41 42 range()函数,前闭后开 43 for i in range(5): 44 print(i) 45 46 # 使range以指定数字开始并指定不同的增量(甚至可以是负数;有时这也叫做'步长'): 47 for i in range(2, 10, 2): 48 print(i) 49 50 # 结合range()和len()函数以遍历一个序列的索引 51 arr = ['my', 'name', 'is', 'jack'] 52 for i in range(len(arr)): 53 print(i, arr[i]) 54 55 # 用range()创建列表 56 arr = list(range(5)) 57 print(arr) 58 59 # 函数 60 61 def func(x, y): 62 return x + y 63 64 print(func('2', 'x'))