Python Tutorial

Billy Su (@Billy4195)


About me

Billy Su(蘇炳立) - GitHub:Billy4195

  • 交大資工大四
  • 自由軟體愛好者
  • 吃飯工具
    • Python
    • C/C++
  • 2016 7~8月 普安科技實習
  • 2017 7~8月 聯發科技實習

投影片參考wdv4758h/Python-Introduction的內容


內容主要包含基本常用的東西,但不包含所有操作。


Outline

Introduction to Python

Guess number game(猜數字遊戲 4A0B)


Introduction


What is Python?


History

Python 是一個由 Guido van Rossum 在 1991 年 2 月釋出的程式語言, 發展至今大約過了 20 餘年, 廣泛使用於科學計算、網頁後端開發、系統工具等地方

Python 是源自於當時 Guido van Rossum 觀賞的 BBC 喜劇 「Monty Python's Flying Circus」


Features

  • 直譯式
  • 物件導向
  • 高階語言

Python2 & Python3

Python3在2008年12月3日首次釋出,與Python2不相容。

Python2 將在2020年後停止維護

所以~學新的比較潮(?)


Installation


Ubuntu

$ sudo apt-get install python3


Centos

$ sudo yum install yum-utils
$ sudo yum-builddep python
$ curl -O https://www.python.org/ftp/python/3.5.0/Python-3.5.0.tgz

$ tar xf Python-3.5.0.tgz
$ cd Python-3.5.0
$ ./configure
$ make
$ sudo make install

Windows

零基礎學網頁爬蟲 01_安裝Python環境


Mac OSX

$ brew install python3


Start

>>> print("Hello World!") Hello World!

Variable


A space for storing data


Example

>>> x = 123 >>> x 123 >>> y = 3.14 >>> y 3.14

Data types

  • int
  • float
  • str
  • list
  • dict

How to know the data type?

type()

>>> type(1) <class 'int'> >>> type(1.5) <class 'float'> >>> type("Hello") <class 'str'> >>> type([1,2,3]) <class 'list'>

list() element access

>>> friends = ["Joe","John","Jack"] >>> friends[0] Joe >>> friends[2] Jack

Comments

>>> #This is a comment >>> print("Hello World!") Hello World!

Arithemathic Operation


Integer(整數運算)

>>> 1 + 1 2 >>> 1 - 1 0 >>> 3 * 4 12 >>> 4 // 2 2 >>> 5 % 3 2

Floating Point(浮點數、小數運算)

>>> 1.1 + 1.2 2.3 >>> 1.5 - 3.5 -2.0 >>> 5.0 * 3.0 15.0 >>> 4.0 / 1.5 2.666666666665 >>> 6 / 3 2.0

Power (指數運算)

>>> 5 ** 2 25 >>> 5 ** 0.5 #5的平方根 2.23606797749979 >>> 27 ** (1/3) # 27的立方根

>>> x = 5 >>> x += 1 >>> x 6 >>> x += 4 >>> x 10 >>> x *= 2 >>> x 20

String(字串)

>>> msg = "Hello" + " world!" >>> msg Hello world!

List(列表)

>>> [2,3] + [4,6] [2,3,4,6]

Relational Operation


>>> 1 < 2 True >>> 1 > 2 False >>> 1 == 2 False >>> 1 != 2 True >>> 1 >= 2 False >>> 1 <= 2 True

Logical Operation


>>> x = 5 >>> y = 12 >>> x >= 1 and x <= 10 True >>> y <= 10 or y >= 15 False >>> not True False >>> not False True

Standard input & output


Output

>>> print(5) 5 >>> x = 60 >>> print(x) 60 >>> y = "Hello" >>> print(y) Hello >>> print(y * 4) HelloHelloHelloHello

Input

>>> x = input("Input something: ") Input something: 123 >>> print(x) 123 >>> x = input("Input something: ") Input something: Something >>> print(x) Something

If-else Statement

>>> score = input("Enter your score: ") Enter your score: 92 >>> if score >= 60: >>> print("Passed") >>> else: >>> print("Failed") Passed >>> if score >= 90: >>> print("Excellent!") >>> elif score >= 60: >>> print("Passed") >>> else: >>> print("Failed") Excellent!

for Loop Statement

>>> friends = ['John','Jack','Joe'] >>> for person in friends: >>> print(person) John Jack Joe

while Loop Statment

>>> F = input("Input x for calculating x! --- ") Input x for calculating x! --- 5 >>> i = 1 >>> result = 1 >>> while i <= int(F): >>> result *= i >>> i += 1 >>> print(result) 120

Function

>>> def plus1(input): >>> return input+1 >>> print(plus1(5)) 6

Module

Hello.py

def print_Hello(): print("Hello")

main.py

import Hello Hello.print_Hello()

Install module

pip3 install <Module name>


Using Standard Library

import random print(random.choice([1,2,3,4,5]))

寫遊戲囉!

猜數字~


出題目

從 0-9選出四個隨機排列的數字
random module

import random def generate_problem(): candidate = [0,1,2,3,4,5,6,7,8,9] candidate = random.sample(candidate,4) return candidate

主要結構

problem = generate_problem() print(problem) guess = input("Input your guess: ") result = check_correct(problem,guess) print( "{}A{}B".format(result[0],result[1]) ) if result[0] == 4: print("Congratulation! Your guess is correct.") else: print("Wrong answer. Try again :)")

怎麼確認答案對不對

def check_correct(problem,guess): for idx1,num in enumerate(problem): print(idx,num)

def check_correct(problem,guess): print(guess,type(guess)) for idx1,num in enumerate(problem): print(idx,num)

def check_correct(problem,guess): for idx2,digit in enumerate(guess): print(idx,digit,type(digit)) for idx1,num in enumerate(problem): print(idx,num)

把string換成integer

>>> s = "123" >>> int(s) 123

def check_correct(problem,guess): for idx2,digit in enumerate(guess): print(idx,type(int(digit))) for idx1,num in enumerate(problem): print(idx,num)

怎麼確認答案正不正確

確認答案的每一個數字有沒有在猜測的數字裡

再確認位置是不是正確的

def check_correct(problem,guess): for idx1,num in enumerate(problem): for idx2,digit in enumerate(guess): if num == digit: print("Match")

def check_correct(problem,guess): A = 0 B = 0 for idx1,num in enumerate(problem): for idx2,digit in enumerate(guess): if num == digit: if idx1 == idx2: A += 1 else: B += 1 return [A,B]

只能猜一次XD

用while loop解決

game_over = False problem = generate_problem() print(problem) while not game_over: guess = input("Input your guess: ") result = check_correct(problem,guess) print("{}A{}B".format(result[0],result[1])) if result[0] == 4: print("Congratulation! Your guess is correct.") game_over = True else: print("Wrong answer. Try again :)")

import random def generate_problem(): candidate = [0,1,2,3,4,5,6,7,8,9] candidate = random.sample(candidate,4) return candidate

def check_correct(problem,guess): A=0 B=0 for idxP,num in enumerate(problem): for idxG,digit in enumerate(guess): if int(digit) == num: if idxP == idxG: A += 1 else: B += 1 return [A,B]

game_over = False problem = generate_problem() print(problem) while not game_over: guess = input("Input your guess: ") result = check_correct(problem,guess) print("{}A{}B".format(result[0],result[1])) if result[0] == 4: print("Congratulation! Your guess is correct.") game_over = True else: print("Wrong answer. Try again :)")

More about Python