1. 程式人生 > >Learn Python the Hard Way

Learn Python the Hard Way

world target python 2 set works vid names article con

Reference

Zed Shaw - Learn Python the Hard Way

Ex0: The Setup

Windows

Python 2, Atom, Terminal.

Ex1: A Good First Program

Keyword

1 print
2 print "Hello World! "

技術分享圖片

Run the file

1 python ex1.py

Error

Garbled Chinese

技術分享圖片

Possible Solutions (Unfortunately, none of them works.)

1. Add ASCII encodings

1 # -*- coding: utf-8 -*-

2. decode & encode01

1 print 中文.decode("utf-8").encode("gb2312")
2 print 中文.decode("utf-8").encode("gbk")

3. CHCP command01, 02

1 chcp 65001

01 關於win終端下python輸出中文亂碼問題

02 Windows設置CMD命令行編碼

Ex2: Comments and Pound Characters

Keywork

1 #
2 # Comments

Q: If # is for comments, then how come # -*- coding: utf-8 -*-

works?

A: Python still ignores that as code, but it‘s used as a kind of "hack" or workaround for problems with setting and detecting the format of a file. You also find a similar kind of comment for editor settings.

Q: Why does the # in print "Hi # there." not get ignored?

A: The # in that code is inside a string, so it will be put into the string until the ending " character is hit. These pound characters are just considered characters and aren‘t considered comments.

Ex3: Numbers and Math

Keywords

1 + # plus
2 - # minus
3 / # slash: 7 / 4 = 1; 7.0 / 4.0 = 1.75
4 * # asterisk
5 % # percent; modulus: X divided by Y with J remaining, The result of % is the J part. 
6 < # less-than
7 > # greater-than
8 <= # less-than-equal
9 >= # greater-than-equal

Ex4: Variables and Names

Ex5: More Variables and Printing

Keywords

1 my_eyes = Black
2 my_hair = Black
3 print "She‘s got %s eyes and %s hair." % (my_eyes, my_hair)

技術分享圖片

03 String Formatting Operations

04 python中%r和%s的區別

Learn Python the Hard Way