盒子
盒子
文章目录
  1. Coding conventions
  2. Built-in data types
    1. Numbers
    2. Lists [1, 2, 3, 4] or [1]
    3. Tuples (1, 2, 3, 4) or (1, )
      1. Tuples <-> Lists
    4. Strings
    5. Dictionaries {1: “one”, 2: “two”}
    6. Sets
    7. File objects
  3. Control flow
    1. Boolean values and expressions
    2. The if-elif-else
    3. The while loop
    4. The for loop
  4. Function definition
  5. Exceptions
  6. Module creation
  7. Object-oriented programming

Python 101

Coding conventions

  • Module/package names: short, all lowercase, underscores only if needed e.g. imp, sys
  • Function names: all lowercase, underscores_for_readability, e.g. foo(), my_func()
  • Variable names: all lowercase, underscores_for_readability, e.g. my_var
  • Class names: CapitablizeEachWord, e.g. MyClass
  • Constant names: ALL_CAPS_WITH_UNDERSCORES, e.g. PI, TAX_RATE
  • Indentation: 4 spaces per level
  • Comparisons: Don’t compare explicityly to True of False, e.g. if my_var: if not my_var:

Built-in data types

Python has a number of build-in data types. Varialbes don’t have to be declared and can have any built-in data type.

Numbers

  • Integers

arithmetic operators:
(+ addition)
(- subtraction)
( multiplication)
(/ division)
(// division with trunction)
(*
exponentiation)
(% modulus)

  • Floats

built-in function round
library module math.ceil

  • Complex numbers

  • Booleans
    True and False, when used with numbers, True is 1 and False is 0

Lists [1, 2, 3, 4] or [1]

A list can contain a mixture of other types.
A list can be indexed from its front or back. You can also refer to a subsegment, or slice, of a list using slice notation

1
2


built-in functions: len, max, min
operators : in + * (+ and * create a new list, leaving the original unchanged)
statement : del
list methods : append, count, extend, index, insert, pop, remove, reverse, sort

Tuples (1, 2, 3, 4) or (1, )

Tuples are similar to lists but are immutable.

Operators: in, +, *
Built-in functions: len, max, min, count, index
Index and slice notition also work the same way as they do on lists.

1
2
3
4
5
6
7
x = (1, 2, 3, 4)
x.index(2)
1
x.count(x)
0
x.count(2)
1

Tuples <-> Lists

tuple(x)
list(x)

Strings

Strings are also immutable
in + * len max min operate on strings as they do on lists and tuples

split()
re library module
print()

Dictionaries {1: “one”, 2: “two”}

Dictionary data type provides associative array functionality implemented using hash tables.

built-in functions: len, del, clear, copy, get, has_key, items, keys, update and values

Sets

Membership and uniqueness are teh main things you need to know.
create a set by using set on a sequence, like a list.
in is used to check for membership on an object in a set.

File objects

  • read/write
  • chdir

Control flow

Boolean values and expressions

  • Boolean constant False, 0
  • Python nil value None
  • empty values, like empty list [ ] or empty string “” are False
  • Boolean constant True and everything else are considered True

The if-elif-else

1
2
3
4
5
6
7
8
9
10
11
12
13
14

x = 5

if x < 5:
y = -1
x = 5
elif x > 5:
y = 1
z = 11
else:
y = 0
z = 10

print(x, y, z)

The while loop

1
2
3
4
5
6
7
8
9
10
11
12
13
14
u, v, x, y = 0, 0, 100, 30

while x > y:
u = u + y
x = x - y

if x < y + 2:
v = v + x
x = 0
else:
v = v + y + 2
x = x - y -2

print(u, v)

The for loop

1
2
3
4
5
6
7
8
9
item_list = [3, "string1", 23, 14.0, "string2", 49, 64, 70]

for x in item_list:
if not isinstance(x, int):
continue

if not x % 7:
print("found an integer divisible by sever: %d" % x)
break

Function definition

return statement:
If no returen statement is encountered, Python’s None value is returned

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def funct1(x, y, z):
value = x + 2*y + z**2

if value > 0:
return x
else:
return 0

funct1(3, 4, 2)

others:
def funct2(x, y=1, z=1):
def funct3(x, y=1, z=1, *tup)
def funct4(x, y=1, z=1, **dictionary)

Exceptions

try-except-finally-else compound statement

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
for file in filename:
try:
f = open(file, 'r')
line = f.readline()

if line == "":
f.close()
raise EmptyFileError("%s: is empty" % file)

except IOError as error:
print("%s: could not be opened; %s" % (file, error.strerror))

except EmptyFileError as error:
print(error)

else:
print("%s: %s" % (file, f.readline()))

finally:
print("Done processing", file)

Module creation

1
2
3
4
5
6
7
8
9
10
# File wo.py

def words_occur():

print("some thing")


# This allows the program to also be run as a script by typing python wo.py at a command line
if __name__ == '__main__':
words_occur()

Object-oriented programming

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File sh.py

""" sh module. Contains classes Shape, Square ans Circle"""
class Shape:
""" Shape class: has method move """
# instance variables x and y are created and initialized in __init__
# first argument is always self
def __init__(self, x, y):
self.x = x
self.y = y

def move(self, deltaX, deltaY):
self.x = self.x + deltaX
self.y = self.y + deltaY

class Square(Shape):
""" Square class: inherits from Shape"""
def __init(self, side = 1, x = 0, y = 0):
Shape.__init(self, x, y)
self.side = side

class Circle(Shape):
""" Circle class: inherits from Shap and has method area """
pi = 3.14159

def __init__(self, r=1, x=0, y=0):
Shape.__init__(self, x, y)
self.radius = r

def area(self):
""" Circle area method: returns the area of the circle. """
return self.radius * self.radius * self.pi


# __str__ is used by the print function
def __str__(self):
return "Circle of radius %s at coordinates (%d, %d) "\
% (self.radius, self.x, self.y)
支持一下
扫一扫,支持forsigner
  • 微信扫一扫
  • 支付宝扫一扫