Python Basic

重新编辑部分

先简单概括一下常用的几种数据类型String、Ints、Lists、Dicts。简单的区别以及常使用的用法

首先是String, 和JS有很多相似的地方,字符串的拼接,新版的ES6的 写法和P3的format有的拼接

上代码

1
2
3
4
5
6
7
8
name = 'Corey'
age = 28

# greeting = 'My name is ' + name + ' and I am ' + str(age) + ' years old'

greeting = 'I am {age} years old and my name is {name}'.format(name=name, age=age)

print greeting

然后就是接下来的例子

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74

person = {'name': 'Jenn', 'age': 23}

# sentence = 'My name is ' + person['name'] + ' and I am ' + str(person['age']) + ' years old.'
# print(sentence)

# sentence = 'My name is {} and I am {} years old.'.format(person['name'], person['age'])
# print(sentence)

# sentence = 'My name is {0} and I am {1} years old.'.format(person['name'], person['age'])
# print(sentence)

# tag = 'h1'
# text = 'This is a headline'

# sentence = '<{0}>{1}</{0}>'.format(tag, text)
# print(sentence)


sentence = 'My name is {0} and I am {1} years old.'.format(person['name'], person['age'])
print(sentence)


class Person():

def __init__(self, name, age):
self.name = name
self.age = age

p1 = Person('Jack', '33')

sentence = 'My name is {0.name} and I am {0.age} years old.'.format(p1)
print(sentence)

# sentence = 'My name is {name} and I am {age} years old.'.format(name='Jenn', age='30')
# print(sentence)

# sentence = 'My name is {name} and I am {age} years old.'.format(**person)
# print(sentence)

# for i in range(1, 11):
# sentence = 'The value is {}'.format(i)
# print(sentence)


# pi = 3.14159265

# sentence = 'Pi is equal to {}'.format(pi)

# print(sentence)


sentence = '1 MB is equal to {} bytes'.format(1000**2)

print(sentence)


import datetime

my_date = datetime.datetime(2016, 9, 24, 12, 30, 45)

# print(my_date)

# March 01, 2016

sentence = '{:%B %d, %Y}'.format(my_date)

print(sentence)

# March 01, 2016 fell on a Tuesday and was the 061 day of the year.

sentence = '{:%B %d, %Y} fell on a {} and was the {} day of the year'.format(my_date)

print(sentence)

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
接下来就是字符串的截取操作


my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
# -10,-9,-8,-7,-6,-5,-4,-3,-2,-1

# list[start:end:step]

# print my_list[::-1]


sample_url = 'http://coreyms.com'
print sample_url

# Reverse the url
# print sample_url[::-1]

# # Get the top level domain
# print sample_url[-4:]

# # Print the url without the http://
# print sample_url[7:]

# # Print the url without the http:// or the top level domain
print sample_url[7:-4]
整数的常用操作
# Arithmetic Operators:
# Addition:       3 + 2
# Subtraction:    3 - 2
# Multiplication: 3 * 2
# Division:       3 / 2
# Floor Division: 3 // 2
# Exponent:       3 ** 2
# Modulus:        3 % 2


# Comparisons:
# Equal:            3 == 2
# Not Equal:        3 != 2
# Greater Than:     3 > 2
# Less Than:        3 < 2
# Greater or Equal: 3 >= 2
# Less or Equal:    3 <= 2
列表的定义以及操作
# Empty Lists
empty_list = []
empty_list = list()

# Empty Tuples
empty_tuple = ()
empty_tuple = tuple()

# Empty Sets
empty_set = {} # This isn't right! It's a dict
empty_set = set()

简单的一些demo 需要自己手敲一下哈

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
39
40
41
42
# Mutable
list_1 = ['History', 'Math', 'Physics', 'CompSci']
list_2 = list_1

print(list_1)
print(list_2)

# list_1[0] = 'Art'

# print(list_1)
# print(list_2)


# Immutable
# tuple_1 = ('History', 'Math', 'Physics', 'CompSci')
# tuple_2 = tuple_1

# print(tuple_1)
# print(tuple_2)

# tuple_1[0] = 'Art'

# print(tuple_1)
# print(tuple_2)

# Sets
cs_courses = {'History', 'Math', 'Physics', 'CompSci'}

print(cs_courses)


# Empty Lists
empty_list = []
empty_list = list()

# Empty Tuples
empty_tuple = ()
empty_tuple = tuple()

# Empty Sets
empty_set = {} # This isn't right! It's a dict
empty_set = set()
接下来就是最常使用的函数了,很多时候和JS都是差不多的
condition = 'Test'

if condition:
    print('Evaluated to True')
else:
    print('Evaluated to False')

还是老样纸,和js对比着来

def outer():
    x = 10
    def inner():
        y = 20
    inner()
    return x + y

my_func = outer

print my_func()

# h1_tag = html_tag('h1')
# print h1_tag

# def html_tag(tag):
#     def print_tag(text):
#         return '<{0}>{1}</{0}>'.format(tag,text)
#     return print_tag

# h1_tag = html_tag('h1')
# print h1_tag('This is a headline!')


function html_tag(tag) {
  function print_tag(text) {
    return '<'+tag+'>'+text+'</'+tag+'>'
  };
  return print_tag
};

h1_tag = html_tag('h1')

console.log(h1_tag('This is a Headline!'))


function html_tag(tag){
  function wrap_text(msg){
    console.log('<' + tag +'>' + msg + '</' + tag + '>')
  }
  return wrap_text
}

print_h1 = html_tag('h1')

print_h1('Test Headline!')
print_h1('Another Headline!')


print_p = html_tag('p')
print_p('Test Paragraph!')


# Closures

import logging
logging.basicConfig(filename='example.log', level=logging.INFO)


def logger(func):
    def log_func(*args):
        logging.info(
            'Running "{}" with arguments {}'.format(func.__name__, args))
        print(func(*args))
    return log_func


def add(x, y):
    return x+y


def sub(x, y):
    return x-y

add_logger = logger(add)
sub_logger = logger(sub)

add_logger(3, 3)
add_logger(4, 5)

sub_logger(10, 5)
sub_logger(20, 10)

一开始写Python时感觉还有些别扭,因为Python对格式要求是比较高的。
每次接出一门新的语言时,都会从简单的demo开始。

先来一个简单的小游戏

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
39
40
41
42
43
44
45
46
47
from random import randint

board = []

for x in range(5):
board.append(["O"] * 5)

def print_board(board):
for row in board:
print " ".join(row)

print "Let's play Battleship!"
print_board(board)

def random_row(board):
return randint(0, len(board) - 1)

def random_col(board):
return randint(0, len(board[0]) - 1)

ship_row = random_row(board)
ship_col = random_col(board)
print ship_row
print ship_col

# Everything from here on should go in your for loop!
# Be sure to indent four spaces!
for turn in range(4):
print "Turn", turn + 1
guess_row = int(raw_input("Guess Row:"))
guess_col = int(raw_input("Guess Col:"))
if guess_row == ship_row and guess_col == ship_col:
print "Congratulations! You sunk my battleship!"
break

else:
if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):
print "Oops, that's not even in the ocean."
elif(board[guess_row][guess_col] == "X"):
print "You guessed that one already."
else:
print "You missed my battleship!"
board[guess_row][guess_col] = "X"
if turn == 3:
print "Game Over"
# Print (turn + 1) here!
print_board(board)

一上来看这段代码会有些模糊,但里面有着最基础的Python代码知识。有不明白的地方记得Google,逻辑非常简单。

既然标题都是说基础嘛,所以还是来些干货

首先是字符串的使用

1
2
3
4
5
6
7
8
9
10
11
12
```
``` bash
from datetime import datetime
now = datetime.now()

print '%s-%s-%s' % (now.year, now.month, now.day)

print '%s/%s/%s' % (now.month, now.day, now.year)

print '%s:%s:%s' % (now.hour, now.minute, now.second)

print '%s/%s/%s %s:%s:%s' % (now.month, now.day, now.year, now.hour, now.minute, now.second)

然后是布尔值的定义,其实跟javascript的或且非是一样的

1
2
3
4
5
6
7
8
9
10
11
12
13
     Boolean Operators
------------------------ True and True is True
True and False is False
False and True is False
False and False is False

True or True is True
True or False is True
False or True is True
False or False is False

Not True is False
Not False is True

对字符串进行一些简单的操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
pyg = 'ay'

original = raw_input('Enter a word:')

word = original.lower()

first = word[0]

new_word = word + first + pyg

if len(original) > 0 and original.isalpha():
print original
else:
print 'empty'

接下来是对functions的小探

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
def tax(bill):
"""Adds 8% tax to a restaurant bill."""
bill *= 1.08
print "With tax: %f" % bill
return bill

def tip(bill):
"""Adds 15% tip to a restaurant bill."""
bill *= 1.15
print "With tip: %f" % bill
return bill

meal_cost = 100
meal_with_tax = tax(meal_cost)
meal_with_tip = tip(meal_with_tax)


def square(n):
"""Returns the square of a number."""
squared = n**2
print "%d squared is %d." % (n, squared)
return squared

square(10)

def power(base, exponent):
result = base**exponent
print "%d to the power of %d is %d." % (base, exponent, result)

power(37,4)

对于字典,列表的操作

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
lloyd = {
"name": "Lloyd",
"homework": [90.0, 97.0, 75.0, 92.0],
"quizzes": [88.0, 40.0, 94.0],
"tests": [75.0, 90.0]
}
alice = {
"name": "Alice",
"homework": [100.0, 92.0, 98.0, 100.0],
"quizzes": [82.0, 83.0, 91.0],
"tests": [89.0, 97.0]
}
tyler = {
"name": "Tyler",
"homework": [0.0, 87.0, 75.0, 22.0],
"quizzes": [0.0, 75.0, 78.0],
"tests": [100.0, 100.0]
}

students = [lloyd, alice, tyler]

for student in students:
print student["name"]
print student["homework"]
print student["quizzes"]
print student["tests"]

lloyd = {
"name": "Lloyd",
"homework": [90.0, 97.0, 75.0, 92.0],
"quizzes": [88.0, 40.0, 94.0],
"tests": [75.0, 90.0]
}
alice = {
"name": "Alice",
"homework": [100.0, 92.0, 98.0, 100.0],
"quizzes": [82.0, 83.0, 91.0],
"tests": [89.0, 97.0]
}
tyler = {
"name": "Tyler",
"homework": [0.0, 87.0, 75.0, 22.0],
"quizzes": [0.0, 75.0, 78.0],
"tests": [100.0, 100.0]
}

# Add your function below!
def average(numbers):
total = sum(numbers)
return float(total) / len(numbers)


def get_average(student):
homework = average(student["homework"])
quizzes = average(student["quizzes"])
tests = average(student["tests"])
return 0.1 * homework + \
0.3 * quizzes + \
0.6 * tests

def get_letter_grade(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"

def get_class_average(students):
result = []
for student in students:
result.append(get_average(student))
return average(result)

students = [lloyd, alice, tyler]

print get_class_average(students)
hello = get_class_average(students)
print get_letter_grade(hello)

最后结束也是再来一个游戏

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from random import randint

guesses_left = 3

while guesses_left > 0:
random_number = randint(1, 10)
guess = int(raw_input("Your guess: "))
if guess == random_number:
print "You win!"
break
if guess != random_number:
print 'You guessed incorrectly!'
guesses_left -= 1
else:
print "You lose."

print "Game Over"