Python

by 吳若喬

課程簡介:

基礎語法

  • Input/Output
  • Deta type
  • if-else
  • loop
  • ...

進階語法

  • Lambda
  • Class&Object
  • tuple
  • ...

數據分析

  • read
  • series
  • numpy
  • ...

自我介紹:

吳若喬 @zsisc29_phoebewu

中山女高資訊研究社 教學長

興趣: 動漫遊戲小說廣播劇迷因鬼畜追番(號)

🈸🈸

Rules:

  • 聽課
  • 不會要問問題
  • 打開電腦
  • 有空練習題目
  • 不用請假
  • 簡報有錯歡迎指正 (學弟妹請電爛我Orz)

Python 10/19:

課程錄影存放區(有些忘記錄真的很抱歉QQ):

Python 11/2:

Python 11/9:

Python 12/14:

Introduction

  • Application
  • Advantages
  • IDE
  • Practice Resources

Application:

  • Google搜尋引擎
  • NASA緊急任務系統專案
  • 股票交易
  • 大數據分析
  • 機器學習

Advantages:

  • 通用
  • 直譯
  • 簡單且直覺
  • 龐大函式庫

IDE:

自動存雲端、分區域執行

智慧提示、分斷點debug

Practice Resources:

從零開始解釋,適合初學者

註解

#單行

'''
多行
使用 ' or " 都可以
'''

Deta Type

資料型別

先介紹之後會常用的:

int(整數):

  • 整數
  • 5
  • 13
  • 114514
  • 999999

float(浮點數):

  • 小數
  • 3.1415926
  • 2.28922
  • 0.5
  • 0.000001

str(字串):

  • 使用單引號(')或雙引號(")都可
  • "hello"
  • 'World'
  • 'a'

chr/ord(轉換ASCII碼):

chr:

  • 輸入數字轉字元

  • chr(65)='A'

  • chr(97)='a'

ord:

  • 輸入字元轉數字

  • ord('A')=65

  • ord('a')=97

bool(布林值):

結果只有True/False

 

以下情況皆為False:

  • 0
  • 0.0
  • 空集合
  • False
  • 資料為空

Input/Output

輸入/輸出

Output:

print(*objs,sep=' ',end='\n',file=sys.stdout,flush=False)#預設

補充:file&flush

flush=False(不刷新):

print(*objs) 內容全部獲取、遇到'\n'(換行符號)、緩衝區滿,才會輸出內容

 

flush=True(每次刷新):

直接印出

關於換行:

\n:換行

\r:回車

\r\n:換行並回車

print("Hello",'\n',"World",sep='')#Unix
print("Hello",'\r',"World",sep='')#Mac
print("Hello",'\r\n',"World",sep='')#Windows

'''
Hello
World
World
Hello
World
'''

Input:

預設為字串(str)

Variable

變數

用於儲存未知的變數:

例如:

輸入兩個數字,想要得到相加的結果

或者是字串

O X
英文字母 數字開頭
底線 資料型態(Python自行判斷)
數字 大小寫相通
(不可用a表示變數A)
一次宣告多個

變數宣告須知:

Operator

運算子

+ 加法
- 減法
* 乘法
/ 除法
// 整除
%(mod/模) 取餘數
** 次方
==/is 相等
>=、<=、>、< 同數學符號意義
and 且(兩者相符則成立)
or 或(兩者擇一則成立)
!= 不等於

運算:

比較:

and/or:

Input&Output&Operator Practice

Snakify Practice:

題目:

Write a program that takes three numbers and prints their sum. Every number is given on a separate line.

輸入三個數字,並印出他們的和。

題目:

Write a program that greets the person by printing the word "Hi" and the name of the person. See the examples below.

輸入人名,並在前面加上"Hi"、"空白"

題目:

Write a program that greets the user by printing the word "Hello", a comma, the name of the user and an exclamation mark(驚嘆號) after it. See the examples below.

題意:輸入人名後,在前方加上"Hello ,"並於後方加入"!"

題目:

N students take K apples and distribute them among each other evenly. The remaining (the undivisible) part remains in the basket. How many apples will each single student get? How many apples will remain in the basket?

 

題意:

有N個學生要分配K個蘋果,並且每人拿到的蘋果數要一致(均勻分配),請問一個學生可以拿幾個?分完後籃子剩下幾個蘋果?

題目:

A school decided to replace the desks in three classrooms. Each desk sits two students. Given the number of students in each class, print the smallest possible number of desks that can be purchased.The program should read three integers: the number of students in each of the three classes,a ,b and c respectively.

題意:

有三間教室,給予三個數字代表各教室的學生數,每兩個學生要有一張桌子,若只有一個人也需要一張桌子,輸出三個班級最少需要幾張桌子。

題目:

Given an integer. Print its tens digit.

題意:

輸出一整數的十位數字

題目:

Given a positive real number, print its fractional part.

題意:

給予一小數,輸出其小數

題目:

Given a positive real number, print its first digit to the right of the decimal point.

題意:

輸出小數第一位

題目:

H hours, M minutes and S seconds are passed since the midnight (0 ≤ H < 12, 0 ≤ M < 60, 0 ≤ S < 60). Determine the angle (in degrees) of the hour hand on the clock face right now.

題意:

輸入小時、分鐘和秒,輸出時鐘走的角度

Solution

**輸入預設為字串型態,需使用(int)更改資料型別**

EX:

輸入5 3 4應輸出12,

但上面的結果會直接輸出534

(字串型態相加的結果)

','在Python的輸出中預設為一格空白,符合題目要求輸出,不用另外更動sep or end

先看輸出格式'Hello, '之後要接一個空白,使用','(預設為空一格),接著放上名字,最後的驚嘆號先使用單引號變成字串,才可以跟名字直接加上去(同型態才可相加)

N個人分K個蘋果,算一人平均分到幾顆以及剩下幾顆:

求商數和餘數

先計算有幾組兩個人,要使用整除運算

餘數只可能為1或0,餘1代表有多出來的人

因此桌子數量直接加上餘數就可以判斷是否有多出來的人

 

取十位數字:

1.使數字變成兩位數(取除以100的餘數)

2.除10(使用整除)

Ex: 121要先變成21,接著除10,答案為2

取小數

已知將小數轉變成整數(int)型態會無條件捨去小數位,因此將原本的數字減去整數位即是答案

Ex:

17.9轉成整數是17,17.9-17留下的就會是小數位

跟求10位數那題思路差不多

已知如何求得個位數,那就把小數第一位往前一位(乘以10)

接著再求個位數字就好

 

EX: 1.79 先乘10,變成17.9,再%10,即可得7

計算小時、分鐘、秒移動時對時針角度的影響

  • 時:360/12
  • 分:360/12/60(一小時60分鐘)
  • 秒:360/12/60/60(一分鐘60秒)

Conditions

條件判斷

if-else:

if A條件:
  do...
elif B條件:
  do...
else:
  do...

輸入60

60>=90 False

60>=80 False

60>=70 False

60>=60 True

輸出D

比較:

輸入60

答案仍為D

but

輸入60

輸入90

答案為ABCD

特殊寫法:

變數 = (條件) and True的執行敘述 or False的執行敘述

變數 = [False的執行敘述, True的執行敘述][條件]

變數 = True的執行敘述 if 條件 else False的執行敘述

Conditions Practice

題目:

Given three integers, determine how many of them are equal to each other. The program must print one of these numbers: 3 (if all are the same), 2 (if two of them are equal to each other and the third is different) or 0 (if all numbers are different)

題意:

輸入三個數字,有三個相同輸出3,兩個相同數字輸出2,全部不相同輸出1

題目:

Given two cells of a chessboard. If they are painted in one color, print the word YES, and if in a different color-NO.

題意:

給予兩個座標點位,判斷他們的顏色是否一致

題目:

In chess, the bishop moves diagonally, any number of squares. Given two different squares of the chessboard, determine whether a bishop can go from the first to the second in one move.

題意:

給予一棋子的行動規則,輸入初始位置和目的地,判斷棋子是否能夠達到目的地

題目:

Given the year number. You need to check if this year is a leap year. If it is, print LEAP(閏年), otherwise print COMMON.

題意:

輸入年分,判斷是平年還是閏年

規則:

1.年分整除4且不整除100為閏年

2.年分整除400者為閏

3.平年皆與以上相反

Solution

只有兩種情況:

  1. 黑去黑 (x和y除2的餘數相等)
  2. 白去白 (x和y除2的餘數不相等)

判斷給予的兩個座標是否在同一情況內

x到y軸的距離和y到x的距離要相同

需注意除以4餘0和除以100不為0必須"同時"成立,且此條件與除以400餘0是擇一成立

 

要注意and or使用的時機以及()先後的作用

Loop

迴圈

While迴圈:

while 條件:
  do...

條件為True時進迴圈執行

for迴圈:

for 變數 in 序列:
  do...

序列包括但不僅限於:

range、list、tuple

for 變數 in range(起始點,結束點,間距):
  do...
#起始點默認為0
#間距默認為1

for...in range():

**起始從0開始且有頭無尾**

break&continue:

else:

for 迴圈"完整"執行後才會執行

**無break**

小練習:

輸出1-50的偶數,並計算總合

for Loop Practice

題目:

Given two integers A and B. Print all numbers from A to B inclusively, in ascending order(升序), if A < B, or in descending order(降序), if A ≥ B.

題意:

輸入兩個數字A,B,如果A<B則遞增輸出由A到B的數字,若A>B則遞減輸出由A到B的數字

題目:

N numbers are given in the input. Read them and print their sum.

The first line of input contains the integer N, which is the number of integers to follow. Each of the next N lines contains one integer. Print the sum of these N integers.

題意:

先輸入一個數字N,代表接下來有N行整數輸入,輸出這N個數字的加總

題目:

For the given integer n calculate the value n!

題意:

給予一整數,輸出其階乘

階乘定義:

n!=1*2*3*...*(n-2)*(n-1)*n

題目:

Given an integer n, print the sum 1!+2!+3!+...+n!.

題意:

輸入一整數n,輸出1!+2!+3!+...+n!的總和

Solution

1.

(a,b+1)為由a直接印到b,由於有頭無尾的特性需要再加上1,間格數預設為1可以不用更動

2.

(a,b-1,-1)為由a印到b,但是是遞減,需要b-1也是因為有頭無尾,例如我結束點為1,但其實只會印到2,因此需要再減1,間格數需要更改為-1才會遞減

第一個輸入值(變數times)是判斷有幾個數字需要被加起來,所以放到迴圈裡。

接著會有(times)個數字,依題目要求需要輸入,並計算總合。

設定一個變數儲存這些數字的總和,一輸入進去就加起來。

if n==5

ans=1*2*3*4*5 (符合for 迴圈遞增的特性)

初始設定需設為1(因為階乘要用乘的,初設0會直接變成0)

初始預設為0要記得調整。

while Loop Practice

題目:

Given a sequence of non-negative integers(非負整數), where each number is written in a separate line. Determine the length of the sequence, where the sequence ends when the integer is equal to 0. Print the length of the sequence (not counting the integer 0). The numbers following the number 0 should be omitted.

題意:

給予非負整數的數列,0為一序列的結束,請輸出該序列的長度

A sequence consists of integer numbers and ends with the number 0. Determine the largest element of the sequence.

給予一數字序列並且最後的數字為0,輸出裡面最大的數字

A sequence consists of integer numbers and ends with the number 0. Determine the index of the largest element of the sequence. If the highest element is not unique, print the index of the first of them

給予一數列並且最後為0,輸出其中最大數字的索引值,若最大值不只一個,則輸出第一個最大數的索引值。

The sequence consists of distinct positive integer numbers and ends with the number 0. Determine the value of the second largest element in this sequence.

給予一數列且最後一個數字為0,輸出第二大的數字。

Given a sequence of integer numbers ending with the number 0. Determine the length of the widest fragment where all the elements are equal to each other

給予一數列並最後為0,輸出該序列內最多數字連成的寬度

nested loop

巢狀迴圈

雙重迴圈:

  • 排序
  • 九九乘法表
  • 印三角形
  • 印菱形
  • 印聖誕樹
  • ...

矩形:

輸入兩個數字M,N,輸出M*N的矩形

觀察:

九九乘法表:

row/col 1 2 3 4 5 6 7 8 9
1 1*1 1*2 1*3 1*4 1*5 1*6 1*7 1*8 1*9
2 2*1 - - - - - - - -
3 3*1 -
4 4*1 -
5 5*1 -
6 6*1 -
7 7*1 -
8 8*1 -
9 9*1 -

假設乘數為i,被乘數為j:

row/col 1 2 3 4 5 6 7 8 9
1 1*1 1*2 1*3 1*4 1*5 1*6 1*7 1*8 1*9
2 2*1 - - - - - - - -
3 3*1 -
4 4*1 -
5 5*1 -
6 6*1 -
7 7*1 -
8 8*1 -
9 9*1 -

i

j

i=1,j=1,2,3,4,..,9,ans=i*j

i=2,j=1,2,3,4,...,9,ans=i*j

i=3,j=1,2,3,4,...,9,ans=i*j

.

.

.

i=9,j=1,2,3,4,...,9,ans=i*j

翻譯:

Practice:

印出九九乘法表

印三角形:

   *
  ***
 *****
*******

星星

空白

星星:

*
***
*****
*******
*

***

*****

*******

 

i=1

i=0

i=2

i=3

層數為4

1

3

5

7

星星數=i*2+1

加上空白

   *

  ***

 *****

*******

 

空白數:

3

2

1

0

i=1

i=0

i=2

i=3

層數為4

空白數=4-i-1

將星星和空白結合起來!

更改為輸入多少就印出多少層數的三角形:

String

字串

slice:
變數=字串[起始:結尾:間隔]
#起始預設為0
#結尾預設為該字串的末端
#間隔預設為1

**起始從0開始且有頭無尾**

len():計算字串長度

變數=len(字串)

split():

指定要以什麼字元分割字串,預設為空白

字串變數.split('分隔標準',起始,結束)
#分隔標準預設為空白
#起始預設為開頭
#結束預設為字串末端

count():

計算字串中有幾個相同元素

字串.count('搜尋字串',起始,結束)
#起始預設為開頭
#結束預設為字串末端

find():

在字串中搜尋想要找尋的字串內容,回傳該字串第一次出現的索引值,若無匹配則回傳-1

字串.find('搜尋字串',起始,結束)
#起始預設為字串開頭
#結束預設為字串結尾

rfind():

在字串中搜尋想要找尋的字串內容,回傳該字串最後一次出現的索引值,若無匹配則回傳-1

字串.rfind('搜尋字串',起始,結束)
#起始預設為字串開頭
#結束預設為字串結尾

replace():取代、替換指定字串

字串.replace('舊字串','新字串',MAX)
#字串最多替換MAX次
#替換次數預設無限制

String Practice

題意:

1.輸出第三個

2.輸出倒數第二個

3.輸出前五個

4.輸出除了倒數兩個以外(輸出到倒數第三個為止)

5.輸出偶數的索引值

6.輸出奇數的索引值

7.倒著輸出

8.從最後一個開始輸出,間隔為2

9.輸出該字串長度

題目:

Given a string consisting of words separated by spaces. Determine how many words it has. To solve the problem, use the method "count".

給予數個單字並用空格分開,請輸出有幾個單字

題目:

Given a string consisting of exactly two words separated by a space. Print a new string with the first and second word positions swapped (the second word is printed first).

給予兩個用空白分隔的字串,將兩個字串調換

題目:

Given a string in which the letter h occurs at least twice. Remove from that string the first and the last occurrence of the letter h, as well as all the characters between them.

給予一字串,將第一個h到最後一個h中間清除,輸出未被清除的字串。

Given a string. Remove from this string all the characters @.

給予一字串,刪除裡面所有的字元'@'

Given a string. Replace every occurrence of the letter h by the letter H, except for the first and the last ones.

除了第一個和最後一個字母h,其餘皆替換成大寫H

List

串列

  • 使用[]包起
  • 可存取不同型態的資料
  • 命名與變數相同(不可數字開頭...)
  • 可疊代
  • 可更改
list名稱 = [值0,值1,值2,值3,值4,...]

其他宣告方法:

a = [1, 2, 3, 4, ...]
#第0格:1
#第1格:2
#第2格:3
#第3格:4
slice:
變數=串列[起始:結尾:間隔]
#起始預設為0
#結尾預設為該字串的末端
#間隔預設為1

直接更改:

append():

list.append(元素)
#從最後方插入元素

insert():

list.insert(索引值,元素)
#在索引值的那格插入元素

pop():

list.pop()
#將最後一個值刪除

del:

del list[slice]
#刪除list中slice的內容

sort():

list.sort(reverse=True|False, key=myFunc)
#True為降序、False為升序(預設)
#key可為自定義函式

remove():

list.remove(元素)
#不確定刪除範圍時使用
#僅刪除第一個出現的元素

clear():

list.clear()
#全部清空

尋找元素:

 

index():

 

 

 

 

 

count():

list.index(元素)
#回傳元素的索引值
##若元素不再串列中則會error
list.count(元素)
#回傳有幾個元素

小練習:

輸入若干數字,並和後面的元素比較,若前者較大,則和後者交換。

list=[int(i) for i in input().split()]
print(' '.join([str(i) for i in list]))

List Practice

Given a list of numbers, find and print all elements that are an even number. In this case use a for-loop that iterates over the list, and not over its indices! That is, don't use range().

給予一串列,印出其中的偶數元素。嘗試不使用range完成。

Given a list of numbers, find and print the first adjacent elements which have the same sign. If there is no such pair, leave the output blank.

給予一串列,找出相同正負號的鄰居,若無則不用輸出。

Given a list of numbers. Determine the element in the list with the largest value. Print the value of the largest element and then the index number. If the highest element is not unique, print the index of the first instance.

給予一串列找出最大的數字並輸出其值和索引值(從0開始)。

Given a list of numbers, swap adjacent items in pairs (A[0]with A[1], A[2]with A[3], etc.). Print the resulting list. If a list has an odd number of elements, leave the last element in place.

和隔壁的元素交換。

Given a list of unique numbers, swap the minimal and maximal elements of this list. Print the resulting list.

給予一串列,交換其中最大和最小的數字,並印出交換後的結果。

Function

函式

def 函式名稱(參數,參數): #可為空
  ...
  • f(x)=...
  • 自定義函式
  • 函數命名規則和變數同
  1. 輸入y
  2. 將y代進year函式中
  3. 在year函式計算答案回傳
  4. 印出

return and pass:

return: 回傳值並結束

pass: 不讓空白函式錯誤

def arbitrary_argument(*參數名稱):
  #不受宣告參數數量限制

def arbitrary_keyword_arguments(**參數名稱):
  #不受宣告參數數量限制外,可以像dict一樣自訂索引值

def default_parameter_value(參數名稱 = 參數預設值):
  #可以先設定參數預設值

應用於sort():

list.sort(reverse=True|False, key=myFunc)
#True為降序、False為升序(預設)
#key可為自定義函式

自定義key

Recursion

遞迴

費氏數列:

  • F(0)=0
  • F(1)=1
  • F(n)=F(n-1)+F(n-2)

計算F(5):

F(5)=F(4)+F(3)

         F(4)=F(3)+F(2)

                  F(3)=F(2)+F(1)

                           F(2)=F(1)+F(0)

                                    1     +   0

1 2 3 4 5 6 7 8 9 10
1 1 2 3 5 8 13 21 34 55
11 12 13 14 15 16 ..
89 144 233 377 610 987 ..
  • F(0)和F(1)是特例(需特別設定)
  • 往下拆分

其餘經典:

  • 輾轉相除法
  • 階乘
  • 河內塔

找規律

設定最終條件

完成

階乘:

n!=1*2*...*(n-1)*n

計算5!:

 

5!=5*4!

         4!=4*3!

                  3!=3*2!

                           2!=2*1!

  • 到1停止(return 1)
  • 其餘皆需要再拆分

Two-dimensional lists

二維串列

Snakify step9

Snakify step11

test:

3

1 2 3 4

5 6

7 8 9

Snakify step12

test:

3

1 2 3 4

5 6

7 8 9

印出的方法:

join

nested loop

(原題目太長省略) 首先給予兩個數字n,m,代表接下來有n*m個數字,找出裡面最大的數字並印出他們的索引值。

n,m=[int(i) for i in input().split()]
num=[[int(j) for j in input().split()]for i in range(n)]

給予兩個數n,m代表有n*m的棋盤

3*4範例

Set

集合

  • 可放置不同型態的元素
  • 無法更改元素但可增減加元素
  • 無排序性
  • 過濾重複元素

Add items:

Remove items:

交集:

對稱差:

確認元素是否在集合中:

Set Practice

給予兩個序列,印出有幾個唯一的數字

印出兩個序列中相同的元素

如果出現的數字未曾出現在此序列,則輸出'NO",若先前已經出現過則輸出'YES'

1 2 3 2 3 4

NO

NO

NO 

YES

YES

NO

首先輸入一個數字n,代表接下來有n行輸入,請印出這n行裡面未重複字母的數量

Dictionary

基礎宣告:

key&value&item

是否有在字典中:

補充:

dict.get(key,value) 若找不到key的value則會回傳此指令中的value

更新字典內容:

匯入items:

Remove:

清空(仍保有空間)

使用迴圈印出

copy():

巢狀dictionary

3
Hello Hi
Bye Goodbye
List Array
Goodbye

Bye

5
McCain 10
McCain 5
Obama 9
Obama 8
McCain 1

McCain 16
Obama 17

1
apple orange banana banana orange

banana

題目練習

有超連結!!!!

思路:

一加一減取結果的絕對值

tips:使用string型態儲存再轉型成int

Lambda

只有一個表示式

一個變數

兩個變數

用function搭配lambda:

filter(lambda 參數: 表示式, 序列)
#回傳符合表示式條件的序列內容

map(lambda 參數: 表示式, 序列)
#回傳經過表示式運算的序列內容

sorted(序列, key = lambda 參數: 表示式)
#可用lambda寫sorted的key

Tuple

基礎宣告:

更改元素:

update:

unpack:

印出tuple:

count&index

Python

By Wu Phoebe

Python

  • 371