# Course Formalities

# Being Pythonic

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

# Keys to success

Jot down algorithms (pseudo code)
Jot down keynotes along the way
Run and tweak plenty of the scripts included in the course
Divide and conquer approach to algorithms
Keep thoughts simple => thinking clearly
Generate ideas for final project!

# Coding layout logic

# Tabs versus spaces?

Spaces are the preferred indentation method.
空格是首选缩进方法。

Coding layout preferred: Use 4 spaces per indentation level.
首选编码布局:每个缩进级别使用 4 个空格。

Tabs should be used solely to remain consistent with code that is already indented with tabs.
Tab 仅用于与已经用 Tab 缩进的代码保持一致。

Python 3 disallows mixing the “use” of tabs and spaces for indentation.
Python 3 不允许混合使用制表符和空格进行缩进。

Python 2 code indented with a mixture of tabs and spaces should be converted to using spaces exclusively.
混合使用制表符和空格缩进的 Python 2 代码应转换为仅使用空格。

# Maximum Line Length

Limit all lines to a maximum of 79 characters
将所有行限制为最多 79 个字符

For flowing long blocks of text with fewer structural restrictions (docstrings or comments), the line length should be limited to 72 characters.
对于结构限制较少的长文本块(docstrings 或注释),行长度应限制为 72 个字符。

The Python standard library is conservative and requires limiting lines to 79 characters (and docstrings/comments to 72)
Python 标准库是保守的,要求将行限制为 79 个字符 (docstring/comments 限制为 72 个字符)

# Comments (good for documentation/debugging)

#single line comment 
'''
This is a multiline
comment.
'''

Use ''' and """ to comment out a block.

IDLE IDE has options like Comment out region and Uncomment regions (shortcuts: Alt+3 for Win and Alt+4 respectively, Ctrl + 3 and Ctrl 4 for Mac respectfully) under Format menu. Now it is more easier than ever!

Documentation Strings - Python Enhancement Proposals (PEP)

Conventions for writing good documentation strings (a.k.a. "docstrings") are immortalized in PEP 257.

Write docstrings for all public modules, functions, classes, and methods. Docstrings are not necessary for non-public methods, but you should have a comment that describes what the method does. This comment should appear after the def line.

For one liner docstrings, please keep the closing """ on the same line.

# Multiple assignment statements

The basic rule is that Python evaluates the entire right-hand side of the = statement. Then it matches values with destinations on the left-hand side. If the lists are different lengths, an exception is raised, and the program stops.
基本规则是 Python 计算 = 语句的整个右侧。然后将值与左侧的目的地匹配。如果列表长度不同,则引发异常,程序停止。

Because of the complete evaluation of the right-hand side, the following construct works nicely to swap to variables.
由于右侧的完整计算,下面的构造可以很好地转换为变量。

#ex. swap vars
a,b = 1,4
b,a = a,b
print (a,b)
Example line.py
#!/usr/bin/env python
# Compute line between two points.
x1,y1 = 2,3 # point one
x2,y2 = 6,8 # point two
m,b = float(y1-y2)/(x1-x2), y1-float(y1-y2)/(x1-x2)*x1
print ("y=",m,"*x +",b)
./line.py

y = 1.25 *x + 0.5

Assignment chaining allowed

num1 = num2 = 1;

# Variables

  • Keyword avoidance! 关键词回避!
  • Declarations (LOCAL VS. GLOBAL VS. MODULE) 声明 (本地 VS. 全局 VS. 模块)
  • Conventions 公约

Note – no constants in Python!!!
注意 - Python 中没有常量!

What to do then…help!!!

  • Use of strings
    字符串的使用
  • methods (Study chapter / slides)
    方法
  • indexing thru
    通过索引

# Multi-Line Statements

var1 = 'Hello World!'
var2 = "Python Programming"
print ("var1[0]: ", var1[0])
print ("var2[1:5]: ", var2[1:5]) # string slicing

Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation character \ to denote that the line should continue.
Python 中的语句通常以换行符结尾。然而,Python 确实允许使用行续接符 \ 来表示该行应该继续。

total = item_one + \
        item_two + \
        item_three

Statements contained within the [] , {} , or () brackets do not need to use the line continuation character.
包含在 []{}() 括号内的语句不需要使用行续行符。

days = ['Monday', 'Tuesday', 'Wednesday',
        'Thursday', 'Friday']

# Quotations in Python

Python accepts single ' , double " and triple ( ''' or """ ) quotes to denote string ‘literals’, as long as the same type of quote starts and ends the string. Triple quotes are used to span the string across multiple lines.
Python 接受单引号、双引号和三引号来表示字符串 “文字”,只要相同类型的引号开始和结束字符串。三重引号用于跨越多行的字符串。

For example, all the following are legal.
例如,以下所有内容都是合法的

word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""

…or use concat operator +

# Operators

# Python Basic Arithmetic Operators

OperatorDescriptionExample
+ AdditionAdds values on either side of the operator.a + b = 31
- SubtractionSubtracts right hand operand from left hand operand.a – b = -11
* MultiplicationMultiplies values on either side of the operatora * b = 210
/ DivisionDivides left hand operand by right hand operandb / a = 2.1
% ModulusDivides left hand operand by right hand operand and returns remainderb % a = 1
** ExponentPerforms exponential (power) calculation on operatorsa**b =10 to the power of 20
//Floor Division - The division of operands where the result is the quotient in which the digits after the decimal point are removed. But if one of the operands is negative, the result is floored, i.e., rounded away from zero (towards negative infinity):9//2 = 4 and 9.0//2.0 = 4.0 , -11//3 = -4 , -11.0//3 = -4.0

# Division differences

– IMPORTANT for processing, printing detail!

*(Data types important for operator choice!)

True Division
True division is where the result is always the real floating-point quotient, regardless of operand type.
真除法是指无论操作数类型如何,结果始终是实数浮点商。
>>> 1 / 2               # returns real quotient
0.5
>>> 1.0 / 2.0           # returns real quotient
0.5
Floor Division
A new division operator // always truncates the fraction and rounds it to the next smallest whole number toward the left on the number line, regardless of the operands' numeric types.
无论操作数的数字类型如何,新的除法运算符 // 总是截断分数,并将其四舍五入到数字行左侧的下一个最小整数。
>>> 1.0 // 2.0      # floors result, returns float
0.0
>>> -1 // 2         # negatives move left on number line
-1

# Bitwise Operators

OperatorDescriptionExample
& Binary ANDOperator copies a bit to the result if it exists in both operands(a & b) (means 0000 1100)
| Binary ORIt copies a bit if it exists in either operand.(a | b) = 61 (means 0011 1101)
^ Binary XORIt copies the bit if it is set in one operand but not both.(a ^ b) = 49 (means 0011 0001)
~ Binary Ones ComplementIt is unary and has the effect of 'flipping' bits.(~a ) = -61 (means 1100 0011 in 2's complement form due to a signed binary number.
<< Binary Left ShiftThe left operands value is moved left by the number of bits specified by the right operand.a << 2 = 240 (means 1111 0000)
>> Binary Right ShiftThe left operands value is moved right by the number of bits specified by the right operand.a >> 2 = 15 (means 0000 1111)

# Operator precedence

  • Arithmetic Operators
  • Bitwise Operators
  • Comparison (Relational) Operators
  • Equality
  • Assignment Operators
  • Identity Operators
  • Membership Operators
  • Logical Operators

Shortcut assignments avoid pitfall! Example in shell mode (IDLE)

>>> c = 2
>>> a = 1
>>> b = 2
>>> c*=a+b  #s/b 4???
>>> print (c)
6
>>>

Bitwise bit shifts

# I/O input / output formalities

Main I/O Functions
input()
print()

Conversion functions
float()
int()
str()

Built in Functions ( int(), str(), float(), input(), print() )

Format Specifiers (Frequently Used)

Specifics: 10.2f
10 => field width
2 => precision
f => format specifier

Samples specifiers in action:
10.2f Format the float item with width 10 and precision 2.
5d Format the integer item in decimal with width 5.
50s Format the string item with width 50.
<10.2f Left-justify the formatted item.
>10.2f Right-justify the formatted item.

Format String Syntax

\t\n --easiest!

currency style

value = 12233.335
print ("${:,}".format(round(value,2)))

Format strings contain “replacement fields” surrounded by curly braces {} .
格式字符串包含由大括号 {} 包围的 “替换字段”。
Anything that is not contained in braces is considered ‘literal’ text, which is copied unchanged to the output - If you need to include a brace character in the literal text, it can be escaped by doubling: {{` and `}} .
大括号中不包含的任何内容都被视为 “文字” 文本,它会原封不动地复制到输出中 - 如果需要在文字文本中包含大括号字符,可以通过加倍来转义: {{`和`}}

PADDING!

Make use of negation!
利用否定!

print ('%-10s is todays date' % str); #includes padding of string if necessary 必要时包括字符串填充

justifications/paddings

string.ljust(s, width[, fillchar])
string.rjust(s, width[, fillchar])

example follows…

The method ljust() returns the string left justified in a string of length width.
ljust() 返回在长度宽度的字符串中左对齐的字符串。
Padding is done using the specified fillchar (default is a space).
填充使用指定的填充字符 (缺省为空格)。
The original string is returned if width is less than len(s) .
如果宽度小于 len(s) ,则返回原始字符串。

Following is the syntax for ljust() method −

str.ljust(width[, fillchar])

Parameters

  • width : This is string length in total after padding.
  • fillchar : This is filler character, default is a space.
str = "this is string example....wow!!!";
print (str.ljust(50, '0'));
this is string example....wow!!!000000000000000000

format specifiers ( d vs. f ), aka utilizing specifiers within print method

s1 = "cats"; s2 = "dogs"
s3 = " %s and %s living together" % (s1, s2)

NOT!

s3 = " %s and %s living together" , (s1, s2)

TAKES AS LITERAL INFO!

print (s3)

end , sep args

  • end - helps to avoid newline
  • sep - help to avoid spacing between display values

# Importing modules

import time, keyword
print("hello",end =' ') 
print("hey"," man", "cow", sep="       ") 
print (keyword.kwlist)

Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.
导入始终放在文件顶部,在任何模块注释和文档字符串之后,以及模块全局和常量之前。

Imports should be grouped in the following order:
导入应按以下顺序分组:

  • standard library imports (Python’s built-in modules)
    标准库导入(Python 的内置模块)
  • related third party imports (modules that are installed and do not belong to the current application)
    相关第三方导入 (已安装且不属于当前应用程序的模块)
  • local application imports (modules that belong to the current application)
    本地应用程序导入 (属于当前应用程序的模块)

You should put a blank line between each group of imports.
应该在每组导入之间放置一个空行。

# Keynotes

What we really want to learn from the basics!

  • lists
  • tuples
  • sets
  • dicts

Know definitions, usages and differences of the following terms

  • Compilers
  • Interpreters
  • Transpilers

# Reviews

  1. In script mode, the interpreter reads the contents of a file that contains Python statements and executes each statement.

  2. A bit that is turned off is represented by the value -1.

    1000111
    1 = on bit - MEANS YES, TRUE
    0 = off bit - MEANS NO, FALSE

  3. What type of error produces incorrect results but does not prevent the program from running?

    • syntax
    • logic
    • grammatical
    • human
  4. The line continuation character is a .

    • #
    • %
    • &
    • \
  5. What is the output of the following print statement? print('The path is D:\\sample\\test.')

    • ‘The path is D:\\sample\\test.’
    • The path is D:\\sample\\test.
    • The path is D\\sample\\test.
    • The path is D:\sample\test.
  6. According to the behavior of integer division, when an integer is divided by an integer, the result will be a float.

  7. When applying the .3f formatting specifier to the following number, 76.15854 , the result is 76.159.

  8. A(n) chart is also known as a structured chart.

    • flow
    • data
    • hierarchy
    • organizational
  9. What will be the outcome of the following statement? num1, num2 = 6

    • An exception will be raised
    • num1 and num2 will both equal 6
    • num1 will equal 0 and num2 will equal 6.
    • None of the above
  10. What will print given the following code snippets?

    str = "Python Superstars!!";
    print (str.rjust(10));
    • An exception will be raised
    • Python Superstars!!
    • Python Superstars!!
    • Absolutely nothin’
  11. What will print given the following code snippets?

    str = "Python Superstars!!";
    print (str.rjust(20));
    • An exception will be raised
    • Python Superstars!!
    • Python Superstars!!
    • Absolutely nothin’
  12. What will print given the following code snippet?

    str = "Python Superstars!!";
    print (str.ljust(20),"the end", sep="");
    • An exception will be raised
    • Python Superstars!!the end
    • Python Superstars!! the end
    • Python Superstars!! the end
  13. Write a print statement to format the string variable str which is assigned the value of “Python” to be displayed followed by the word “power” on one line. Keep exactly 10 spaces between words.

    example of display:

    Python          power
    
    str = "Python"
    print ('%-15s power' % str);