Learn Python the Hard Way

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的区别

猜你喜欢

转载自www.cnblogs.com/princemay/p/9342447.html