範例一、亂數產生1到45其中一個數字
1 2 | import random print(random.randint(1, 45)) |
執行結果:
29
範例二、亂數產生45個1到45數字
1 2 3 | import random for i in range(45): print(random.randint(1, 45), end=' ') |
執行結果:
16 1 28 33 41 23 31 28 25 6 25 29 35 11 20 28 13 18 37 27 37 32 38 19 45 34 44 31 4 45 10 39 1 40 16 18 7 7 22 45 34 41 44 44 1
範例三、亂數產生45個1到45數字,不能有重複。
1 2 3 4 5 6 7 8 | import random SeatOrder = [] for i in range(45): number = random.randint(1, 45) while number in SeatOrder: number = random.randint(1, 45) SeatOrder.append(number) print(number, end=' ') |
執行結果:
12 39 43 9 18 38 27 17 13 30 8 10 45 11 15 28 31 32 33 2 26 36 44 16 20 6 40 37 22 4 1 35 25 29 21 19 14 42 24 5 7 34 23 41 3
範例四、亂數產生45個1到45數字,不能有重複,每印出8個換行。
1 2 3 4 5 6 7 8 9 10 11 | import random SeatOrder = [] for i in range(45): number = random.randint(1, 45) while number in SeatOrder: number = random.randint(1, 45) SeatOrder.append(number) if (i+1) % 8: print(number, end=' ') else: print(number, end='\n') |
執行結果:
43 5 20 45 13 35 29 42
36 11 17 24 3 31 8 4
1 39 28 30 32 26 12 44
2 15 33 27 23 37 41 10
21 18 38 6 7 14 19 9
16 22 34 25 40
範例五、承上題,排列整齊
1 2 3 4 5 6 7 8 9 10 11 | import random SeatOrder = [] for i in range(45): number = random.randint(1, 45) while number in SeatOrder: number = random.randint(1, 45) SeatOrder.append(number) if (i+1) % 8: print(f'{number:2}', end=' ') else: print(f'{number:2}', end='\n') |
執行結果:
沒有留言:
張貼留言