# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 2
#     language: python
#     name: python2
# ---

# 1.文件下的所有代码都是使用的Python 2  
# 2.文件内容主要来自于《父与子的编程之旅》

# +
import sys


sys.version_info
# -

numBlocks = int(raw_input('How many blocks of stars do you want? '))
for block in range(1, numBlocks + 1):
    for line in range(1, block * 2):
        for star in range(1, (block + line) * 2):
            print '*',
        print
    print

numBlocks = int(raw_input('How many blocks of stars do you want? '))
for block in range(1, numBlocks + 1):
    print 'block =', block
    for line in range(1, block * 2):
        for star in range(1, (block + line) * 2):
            print '*',
        print 'line =', line, 'star =', star
    print

numBlocks = int(raw_input('How many blocks of stars do you want? '))
for block in range(1, numBlocks + 1):
    print 'block =', block
    for line in range(1, block * 2):
        for star in range(1, (block + line) * 2):
            print '*',
        print 'line =', line, 'star =', star
    print

print '\tDog\tBun\tKetchup\tMustard\tOnions'
count = 1
for dog in [0, 1]:
    for bun in [0, 1]:
        for ketchup in [0, 1]:
            for mustard in [0, 1]:
                for onion in [0, 1]:
                    print '#', count, '\t', dog, '\t', bun, '\t',
                    print ketchup, '\t', mustard, '\t', onion
                    count += 1

dog_cal = 140
bun_cal = 120
mus_cal = 20
ket_cal = 80
onion_cal = 40
print '\tDog\tBun\tKetchup\tMustard\tOnions\tCalories'
count = 1
for dog in [0, 1]:
    for bun in [0, 1]:
        for ketchup in [0, 1]:
            for mustard in [0, 1]:
                for onion in [0, 1]:
                    tot_cal = dog * dog_cal + bun * bun_cal + \
                              mustard * mus_cal + ketchup * ket_cal + \
                              onion * onion_cal
                    print '#', count, '\t', dog, '\t', bun, '\t',
                    print ketchup, '\t', mustard, '\t', onion, '\t',
                    print tot_cal
                    count += 1

dog_cal = 140
bun_cal = 120
mus_cal = 20
ket_cal = 80
onion_cal = 40
print '\tDog\tBun\tKetchup\tMustard\tOnions\tCalories'
count = 1
for dog in [0, 1]:
    for bun in [0, 1]:
        for ketchup in [0, 1]:
            for mustard in [0, 1]:
                for onion in [0, 1]:
                    tot_cal = (dog * dog_cal + bun * bun_cal + 
                              mustard * mus_cal + ketchup * ket_cal + 
                              onion * onion_cal)
                    print '#', count, '\t', dog, '\t', bun, '\t',
                    print ketchup, '\t', mustard, '\t', onion, '\t',
                    print tot_cal
                    count += 1

# +
import time


starter = int(raw_input("How many seconds? "))
for i in range(starter, 0, -1):
    print i,
    for j in range(i):
        print '*',
    print
    time.sleep(1)
print "BLAST OFF!"
# -

letters = ['d', 'a', 'e', 'c', 'b']
print letters
letters.sort()
print letters

letters = ['d', 'a', 'e', 'c', 'b']
print letters.sort()

letters = ['d', 'a', 'e', 'c', 'b']
letters.sort()
print letters

classMarks = [[55, 63, 77, 81], [65, 61, 67, 72], [97, 95, 92, 88]]
print classMarks

for studentMarks in classMarks:
    print studentMarks

print classMarks[0]

print classMarks[0][2]

phoneNumbers = {}
phoneNumbers['John'] = '555-1234'
print phoneNumbers

print phoneNumbers['John']

print phoneNumbers.keys()

print phoneNumbers.values()

dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}
print dishes.keys()

dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}
keys = dishes.keys()
values = dishes.values()
sorted_key_list = sorted(keys)
for value in sorted(values):
    for key in sorted_key_list:
        if dishes[key] == value:
            print key, dishes[key]
            sorted_key_list.remove(key)
            break


print "Enter 5 names:"
name1 = raw_input()
name2 = raw_input()
name3 = raw_input()
name4 = raw_input()
name5 = raw_input()
name_list = [name1, name2, name3, name4, name5]
print "The names are",
for name in name_list:
    print name,

print "Enter 5 names:"
name1 = raw_input()
name2 = raw_input()
name3 = raw_input()
name4 = raw_input()
name5 = raw_input()
name_list = [name1, name2, name3, name4, name5]
print "The names are",
for name in name_list:
    print name,
print
print "The sorted names are",
for name in sorted(name_list):
    print name,

print "Enter 5 names:"
name1 = raw_input()
name2 = raw_input()
name3 = raw_input()
name4 = raw_input()
name5 = raw_input()
name_list = [name1, name2, name3, name4, name5]
print "The third name you entered is:", name3

print "Enter 5 names:"
name1 = raw_input()
name2 = raw_input()
name3 = raw_input()
name4 = raw_input()
name5 = raw_input()
name_list = [name1, name2, name3, name4, name5]
print "The names are",
for name in name_list:
    print name,
print
sub_index = int(raw_input("Replace one name. Which one? (1-5): "))
name_list[sub_index - 1] = raw_input("New name: ")
print "The names are",
for name in name_list:
    print name,

# +
import sys


dicts = {}
operation = raw_input("Add or look up a word (a/l)? ")
running = True
while running:
    if operation == 'a':
        key = raw_input("Type the word: ")
        value = raw_input("Type the definition: ")
        dicts[key] = value
        print "Word added!"
        operation = raw_input("Add or look up a word (a/l)? ")
    elif operation == 'l':
        query_key = raw_input("Type the word: ")
        if query_key in dicts:
            print dicts[query_key]
            operation = raw_input("Add or look up a word (a/l)? ")
        else:
            print "That word isn't in the dictionary yet."
            operation = raw_input("Add or look up a word (a/l)? ")
    elif operation == 'quit':
        sys.exit()


# +
def printMyAddress():
    print "<NAME>"
    print "123 Main Street"
    print "Ottawa, Ontario, Canada"
    print "K2M 2E9"
    print
    
    
printMyAddress()


# +
def calculateTax(price, tax_rate):
    taxTotal = price + (price * tax_rate)
    return taxTotal


my_price = float(raw_input("Enter a price: "))
totalPrice = calculateTax(my_price, 0.06)
print "price =", my_price, "Total price =", totalPrice


# +
def calculateTax(price, tax_rate):
    taxTotal = price + (price * tax_rate)
    my_price = 1000
    print "my_price (inside function) =", my_price
    return taxTotal


my_price = float(raw_input("Enter a price: "))

totalPrice = calculateTax(my_price, 0.06)
print "price =", my_price, "Total price =", totalPrice
print "my_price (outside function) =", my_price


# -

def calculateTax(price, tax_rate):
    global my_price  # 告诉Python你想使用全局版本的my_price


# +
def calculateTax(price, tax_rate):
    taxTotal = price + (price * tax_rate)
    global my_price
    my_price = 1000
    print "my_price (inside function) =", my_price
    return taxTotal


my_price = float(raw_input("Enter a price: "))

totalPrice = calculateTax(my_price, 0.06)
print "price =", my_price, "Total price =", totalPrice
print "my_price (outside function) =", my_price


# +
class Ball:
    
    def bounce(self):
        if self.direction == "down":
            self.direction = "up"
            
            
myBall = Ball()
myBall.direction = "down"
myBall.color = "green"
myBall.size = "small"

print "I just created a ball."
print "My ball is", myBall.size
print "My ball is", myBall.color
print "My ball's direction is", myBall.direction
print "Now I'm going to bounce the ball"
print
myBall.bounce()
print "Now the ball's direction is", myBall.direction


# +
class Ball:
    def __init__(self, color, size, direction):
        self.color = color
        self.size = size
        self.direction = direction
        
    def bounce(self):
        if self.direction == "down":
            self.direction = "up"
            
            
myBall = Ball("red", "small", "down")
print "I just create a ball."

print "My ball is", myBall.size
print "My ball is", myBall.color
print "My ball's direction is", myBall.direction
print "Now I'm going to bounce the ball"
print
myBall.bounce()
print "Now the ball's direction is", myBall.direction
print myBall


# +
class Ball:
    def __init__(self, color, size, direction):
        self.color = color
        self.size = size
        self.direction = direction
        
    def __str__(self):
        msg = "Hi, I'm a " + self.size + " " + self.color + " ball!"
        return msg
    
    
myBall = Ball("red", "small", "down")
print myBall
# -

# 创建 Ball 类的两个实例
cartersBall = Ball("red", "small", "down")
warrensBall = Ball("green", "medium", "up")


# +
class HotDog:
    def __init__(self):
        self.cooked_level = 0
        self.cooked_string = "Raw"
        self.condiments = []
        
    def __str__(self):
        msg = "hot dog"
        if len(self.condiments) > 0:
            msg = msg + " with "
        for i in self.condiments:
            msg = msg + i + ", "
        msg = msg.strip(", ")
        msg = self.cooked_string + " " + msg + "."
        return msg
    
    def cook(self, time):
        self.cooked_level = self.cooked_level + time
        if self.cooked_level > 8:
            self.cooked_string = "Charcoal"
        elif self.cooked_level > 5:
            self.cooked_string = "Well-done"
        elif self.cooked_level > 3:
            self.cooked_string = "Medium"
        else:
            self.cooked_string = "Raw"
            
    def addCondiment(self, condiment):
        self.condiments.append(condiment)

            
myDog = HotDog()
print myDog
print "Cooking hot dog for 4 minutes..."
myDog.cook(4)
print myDog
print "Cooking hot dog for 3 more minutes..."
myDog.cook(3)
print myDog
print "What happens if I cook it for 10 more minutes?"
myDog.cook(10)
print myDog
print "Now, I am going to add some stuff on my hot dog"
myDog.addCondiment("ketchup")
myDog.addCondiment("mustard")
print myDog


# +
class Triangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height
        
    def getArea(self):
        area = self.width * self.height / 2.0
        return area
    
    
class Square:
    def __init__(self, size):
        self.size = size
        
    def getArea(self):
        area = self.size * self.size
        return area
    
    
myTriangle = Triangle(4, 5)
mySquare = Square(7)

print myTriangle.getArea()
print mySquare.getArea()


# +
class GameObject:
    def __init__(self, name):
        self.name = name
        
    def pickUp(self, player):
        pass
        # put code here to add the object
        # to the player's collection
        
        
class Coin(GameObject):  # Coin是GameObject的子类
    def __init__(self, value):
        GameObject.__init__(self, "coin")  # 在__init__()中，继承GameObject的初始化方法
        self.value = value                 # 并补充新内容
        
    def spend(self, buyer, seller):
        pass
        # put code here to remove the coin
        # from the buyer's money and
        # add it to the seller's money


# +
class BankAccount:
    
    def __init__(self, username, cardnumber):
        self.username = username
        self.cardnumber = cardnumber
        self.balance = 0.0
        
    def getBalance(self):
        return self.balance
    
    def deposit(self, money):
        self.balance += money
        print "Now your balance is", self.balance
        
    def quqian(self, money):
        if self.balance >= money:
            self.balance -= money
            print "Now your balance is", self.balance
        else:
            print "You tried to withdraw", money
            print "The account balance is", self.balance
        
        
class InterestAccount(BankAccount):
    
    def __init(self, username, cardnumber, rate):
        BankAccount.__init__(self, username, cardnumber)
        self.rate = rate
        
    def addInterest(self):
        interst = self.balance * self.rate
        print "adding interest to the account,", self.rate * 100, "percent"
        self.deposit(interest)


# -

# %%writefile upper.py
def upper(name):
    '''convert name to upper charactor'''
    return name.upper()


# !cat upper.py

# +
import random


random_list = []
while len(random_list) < 5:
    random_list.append(random.randint(1, 20))
print random_list

# +
import random
import time

for i in range(10):
    time.sleep(3)
    print random.random()

# +
import random


random_list = []
for i in range(5):
    random_list.append(random.randint(1, 20))
print random_list

# +
import pygame


pygame.init()
screen = pygame.display.set_mode([640, 480])

# +
# coding=utf-8
# GUI 程序的代码不适合在jupyter notebook中编写，运行的时候会引起kernel die

import sys

import pygame


pygame.init()
screen = pygame.display.set_mode([640, 480])
screen.fill([255, 255, 255])  # 用白色背景填充窗口
pygame.draw.circle(screen, [255, 0, 0], [320, 240], 30, 0)
pygame.display.flip()

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
pygame.quit()

# -

import sys
sys.executable

# !python --version

# !/usr/bin/python --version

import sys
sys.version



StarcoderdataJupyterScriptsDedupFiltered