Skip to content

Latest commit

 

History

History
447 lines (320 loc) · 6.97 KB

20170627.md

File metadata and controls

447 lines (320 loc) · 6.97 KB

內建函數 range()

>>> print(range(10))

range(0, 10)

```pythonprint(type(range(10)))

<class 'range'>

print(list(range(10)))

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print(list(range(0, 10)))

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print(list(range(0, 10, 2)))

[0, 2, 4, 6, 8]

print(list(range(9, -1, -1)))

[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Make the loop print the numbers from 0 to 19 instead of 0 to 9.

print "Counting..."
for i in range(0,20):
    print i

Using strings in lists in functions

n = ["Michael", "Lieberman"]
def join_strings(words):
    result = ""
    for i in words:
        result = result + i
    return result
print join_strings(n)

Using two lists as two arguments in a function

m = [1, 2, 3]
n = [4, 5, 6]
# Add your code here!
def join_lists(a, b):
    return a + b
print join_lists(m, n)
# You want this to print [1, 2, 3, 4, 5, 6]

[1, 2, 3, 4, 5, 6]

Using a list of lists in a function

n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
for lst in n:
    print lst
    for item in lst:
        print item

內建函數 append()

把input輸入的內容新增到list

hobbies = []
for x in range(0,3):
    newhobbies = raw_input("your new hobbies")
    hobbies.append(str(newhobbies))

print hobbies
n = [[1, 2], [4, 5, 6, 7]]
def flatten(lists):
    results = [ ]
    for x in lists:
        for j in x:
            results.append(j)
    return results

print flatten(n)
board = []
for x in range(0,5):
    board.append('0')
for i in range(0,5):
    print board

or

board = []
for n in range(5):
    board.append('O' )
def print_board(board):
    for row in board:
        print board
print_board(board)

[0, 0, 0, 0, 0]

[0, 0, 0, 0, 0]

[0, 0, 0, 0, 0]

[0, 0, 0, 0, 0]

[0, 0, 0, 0, 0]

board = []
for n in range(5):
    board.append(['O'] * 5)
print board

[[0, 0, 0, 0, 0] , [0, 0, 0, 0, 0] , [0, 0, 0, 0, 0] , [0, 0, 0, 0, 0] , [0, 0, 0, 0, 0]]

letters = ['a', 'b', 'c', 'd']
print " ".join(letters)
print "---".join(letters)

a b c d

a---b---c---d---

board = []
for x in range(0,5):
   board.append(["O"] * 5)
def print_board(board):
  for row in board:
    print " ".join(row)

print_board(board)

While/else

import random
print "Lucky Numbers! 3 numbers will be generated."
print "If one of them is a '5', you lose!"
count = 0
while count < 3:
    num = random.randint(1, 6)
    print num
    if num == 5:
        print "Sorry, you lose!"
        break
    count += 1
else:
    print "You win!"

猜數字遊戲

from random import randint
random_number = randint(1, 10)
guesses_left = 3
# Start your game!
while guesses_left > 0:
    guess = int(raw_input("Your guess: "))
    if guess == random_number:
        print "You win!"
        break
    guesses_left -= 1
else:
    print random_number
    print "You lose."

取代

phrase = "A bird in the hand..."
s = ""
for x in phrase:
    if x == 'A' or x == 'a':
        s = s + 'X'
    else:
        s = s + x
print s

X bird in the hand...

The,character after our

printstatement means that our nextprint

statement keeps printing on the same line.

phrase = "A bird in the hand..."
# Add your for loop
for char in phrase:
    if char == 'A' or char == 'a':
        print 'X',
    else:
        print char,
print

X bird in the hand...


For/else

Just like withwhile,forloops may have anelseassociated with them.

fruits = ['banana', 'apple', 'orange', 'tomato', 'pear', 'grape']
print 'You have...'
for f in fruits:
    if f == 'tomato':
        print 'A tomato is not a fruit!' 
        break #到tomato就會停止
    print 'A', f
else:
    print 'A fine selection of fruits!'

You have...

A banana

A apple

A orange

A tomato is not a fruit!

#沒有break的版本
fruits = ['banana', 'apple', 'orange', 'tomato', 'pear', 'grape']
print 'You have...'
for f in fruits:
    if f == 'tomato':
        print 'A tomato is not a fruit!' 
    print 'A', f
else:
    print 'A fine selection of fruits!'

You have...

A banana

A apple

A orange

A tomato is not a fruit!

A tomato

A pear

A grape

A fine selection of fruits!


Looping over a dictionary

d = {'a': 'apple', 'b': 'berry', 'c': 'cherry'}
for key in d:
    # Your code here!
    #if d[key] == 'berry':
    print key, d[key]

a apple

b berry

c cherry


內建函數enumerate()

enumerateworks by supplying a corresponding index to each element in the list that you pass it. Each time you go through the loop,

indexwill be one greater, anditemwill be the next item in the sequence. It's very similar to using a normalforloop with a list, except this gives us an easy way to count how many items we've seen so far

choices = ['pizza', 'pasta', 'salad', 'nachos']
print 'Your choices are:'
for index, item in enumerate(choices):
    print index+1, item
    # index從0開始所以+1

Your choices are:

1 pizza

2 pasta

3 salad

4 nachos


內建函數zip()

zipwill create pairs of elements when passed two lists, and will stop at the end of the shorter list.zipcan handle three or more lists as well!

#zip()用來混合list_a & list_b
list_a = [3, 9, 17, 15, 19]
list_b = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90]
for a, b in zip(list_a, list_b):
    # Add your code here!
    #print a,b 列出ab 
    if a > b: #a,b比大小
        print a
    else:
        print b

3

9

17

15

30


內建函數sum() , float()

grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]
def grades_sum(scores):
    total = sum(scores) 
    #sum 自動總和
    return total

def grades_average(scores):
    return grades_sum(scores)/float(len(scores))
    #float轉換成浮點數
    #len()長度(list數量)
print grades_average(grades)

Standard Deviation:

The standard deviation is the square root of the variance.

grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]

# all the grades
def print_grades(grades):
    for grade in grades:
        print grade
# sum of grades        
def grades_sum(grades): 
    total = 0
    for grade in grades: 
        total += grade
    return total
# average of grades
def grades_average(grades):
    sum_of_grades = grades_sum(grades)
    average = sum_of_grades / float(len(grades))
    return average
# variance of grades
def  grades_variance(scores):
    average = grades_average(scores)
    variance = 0
    for score in scores:
        variance += (average - score) ** 2
        result = variance/float(len(scores))
    return result 
# deviation of grades
def grades_std_deviation(variance):
    return variance ** 0.5 #開根號

variance = grades_std_deviation(grades_variance(grades))
#取得variance的值再計算deviation
print (variance)