Python从入门到实践 代码总结

# 11.2.3 test_code 2017-7-2 Shenzhen ''
import unittest
from survey import AnonymousSurvey

class TestAnonmyousSurvey(unittest.TestCase)
    def test_store_single_response(self)
        question = "what language did you first learn to speak?"
        my_survey = AnonymousSurvey(question)
        my_survey.store_response('English')

        self.assertIn('English', my_survey.responses)

    def test_store_three_responses(self)
        question = "what language did you first learn to speak?"
        my_survey = AnonymousSurvey(question)
        responses = ['English', 'Spanish', 'Mandarin']
        for response in responses
            my_survey.store_response(response)

        for response in responses
            self.assertIn(response, my_survey.responses)

unittest.main()

..
----------------------------------------------------------------------
Ran 2 tests in 0.001s

OK
[Finished in 0.4s]





# 11.2.2 test_code 2017-7-2 Shenzhen ''
# 11.2.2 test_code 2017-7-2 Shenzhen ''
from survey import AnonymousSurvey

question = "What language did you learn first?"
my_survey = AnonymousSurvey(question)

my_survey.show_question()
print("enter 'q' at anytime to quit")
while True
    response = input('language ')
    if response == 'q'
        break
    my_survey.store_response(response)

print("\n Thank you to everyone who participated in the new survey!")
my_survey.show_results()


What language did you learn first?
enter 'q' at anytime to quit
language chinese
language english
language q

 Thank you to everyone who participated in the new survey!
Survey results 
- chinese
- english

***Repl Closed***
















# 11.2.2 test_code 2017-7-2 Shenzhen ''
class AnonymousSurvey()
    def __init__(self,question)
        self.question=question
        self.responses=[]

    def show_question(self)
        print(self.question)

    def store_response(self, new_response)
        self.responses.append(new_response)

    def show_results(self)
        print("Survey results ")
        for response in self.responses
            print('- ' + response)





question = "What language did you learn first?"
my_survey = AnonymousSurvey(question)
my_survey.show_question()
my_survey.store_response('chinese')
my_survey.store_response('english')
my_survey.show_results()


What language did you learn first?
Survey results 
- chinese
- english
[Finished in 0.2s]
# 11-2 test_code 2017-7-2 Shenzhen ''





# 11.1.5 test_code 2017-7-2 Shenzhen ''
#添加新测试,用于测试包含中间名的姓名。

import unittest
from name_function import get_formatted_name

class NamesTestCase(unittest.TestCase)
    """test name_function.py"""

    def test_first_last_neme(self)
        formatted_name = get_formatted_name('janis', 'joplin')
        self.assertEqual(formatted_name, 'Janis Joplin')

    def test_first_last_middle_name(self)
        formatted_name = get_formatted_name('wolfgang','mozart','amadeus')
        self.assertEqual(formatted_name, 'Wolfgang Amadeus Mozart')

unittest.main()


..              #.. 表示两个测试通过
----------------------------------------------------------------------
Ran 2 tests in 0.001s

OK                  #OK表示全部测试都通过了
[Finished in 0.4s]

# 11.1.4 test_code 2017-7-22 Shenzhen ''
#解决测试用例没有通过的情况
#修改函数如下,测试就通过了。

def get_formatted_name(first, last, middle= '')
    if middle

        full_name = first + ' '+ middle +' '+ last
    else
        full_name = first + ' ' + last
    return full_name.title()

# 11.1.3 test_code 2017-7-22 Shenzhen ''
给函数添加一个中间名,测试函数是否还能通过
#只包含一个方法的测试用例,检查函数在给定名和姓时候能否正确工作
import unittest     #标准库中的模块unittest提供了代码测试工具。
from name_function import get_formatted_name        #导入要测试的函数

class NamesTestCase(unittest.TestCase)     #这个类名字必须要包含Test,名字最好和要测试的函数有些关系
    """test name_function.py"""

    def test_first_last_neme(self)         #所有以test打头的方法都自动运行。
        formatted_name = get_formatted_name('janis', 'joplin')
        self.assertEqual(formatted_name, 'Janis Joplin')
        #assertEqual()断言方法核实得到的结果是否与期望的结果一致

unittest.main()                 #让python运行文件中的测试,

#下面是被修改过的get_formatted_name()函数

def get_formatted_name(first, last, middle)

    full_name = first + ' '+ middle + ' ' + last

    return full_name.title()

E               #E指出测试用例中有个单元测试导致了错误,
======================================================================
ERROR test_first_last_neme (__main__.NamesTestCase)                #这个函数导致错误
----------------------------------------------------------------------
Traceback (most recent call last)
  File "D\Sublime text_work\Python_work\test.py", line 8, in test_first_last_neme
    formatted_name = get_formatted_name('janis', 'joplin')
TypeError get_formatted_name() missing 1 required positional argument 'middle'
#告诉出问题的具体原因是缺少一个需要的位置实参 'middle'

----------------------------------------------------------------------
Ran 1 test in 0.001s                #运行了一个单元测试用了0.001s

FAILED (errors=1)                   #指出整个测试用例没有通过,因为运行该测试用例时候发生了一个错误
[Finished in 0.4s with exit code 1]


'''
单元测试用于合适函数的某个方面没有问题,测试用例是一组单元测试,这些单元测试一起核实函数在各种情形下的
行为都符合要求。良好的测试用例考虑到了函数可能收到的各种输入。
'''
# 11.1.2 test_code 2017-7-2 Shenzhen ''
#只包含一个方法的测试用例,检查函数在给定名和姓时候能否正确工作
import unittest     #标准库中的模块unittest提供了代码测试工具。
from name_function import get_formatted_name        #导入要测试的函数

class NamesTestCase(unittest.TestCase)     #这个类名字必须要包含Test,名字最好和要测试的函数有些关系
    """test name_function.py"""

    def test_first_last_neme(self)         #所有以test打头的方法都自动运行。
        formatted_name = get_formatted_name('janis', 'joplin')
        self.assertEqual(formatted_name, 'Janis Joplin')
        #assertEqual()断言方法核实得到的结果是否与期望的结果一致

unittest.main()                 #让python运行文件中的测试,



.               #  . 表示有一个测试通过了
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK                                  #OK表示所有测试都通过了
[Finished in 0.6s]


#当稍微改动程序为        formatted_name = get_formatted_name('jans', 'joplin')
F               #表示测试有错误
======================================================================
FAIL test_first_last_neme (__main__.NamesTestCase)     #指出这行有错误
----------------------------------------------------------------------
Traceback (most recent call last)
  File "D\Sublime text_work\Python_work\test.py", line 9, in test_first_last_neme
    self.assertEqual(formatted_name, 'Janis Joplin')
AssertionError 'Jans Joplin' != 'Janis Joplin'             #断言错误,formatted_name和'Janis Joplin'不相等
- Jans Joplin
+ Janis Joplin
?    +


----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (failures=1)                      #最终测试结果:失败一个                               
[Finished in 0.5s with exit code 1]









# 10-13 file 2017-7-2 Shenzhen ''
import json
def get_stored_username()
    filename = 'username.json'
    try
        with open(filename) as f_obj
            username = json.load(f_obj)
    except FileNotFoundError
        return None 
       
    else
        return username

def get_new_username()
    username = input("what is your name?")
    filename = 'username.json'
    with open(filename,'w') as f_obj
        json.dump(username,f_obj)

def greet_user()
    username = get_stored_username()
    if username == get_stored_username()
        print("welcome back, " + username)
    else
        username = get_new_username()
        print("we will remeber you when you come back, " + username)

greet_user()



# 10-12 file 2017-7-2 Shenzhen ''
import json
filename = 'favorate_num.json'
try 
    with open(filename) as f_obj
        favorate_num = json.load(f_obj)
        print("i know your favorate number! It is " + favorate_num)

except FileNotFoundError
    favorate_num =input("enter your favorate number ")
    with open(filename,'w') as f_obj
        json.dump(favorate_num, f_obj)
        print("your favorate number is " + favorate_num)






# 10-11 file 2017-7-2 Shenzhen ''
import json
favorate_num =input("enter your favorate number ")
filename = 'favorate_num.json'
with open(filename,'w') as f_obj
    json.dump(favorate_num, f_obj)
    print("your favorate number is " + favorate_num)

# 10-11 file 2017-7-2 Shenzhen ''
import json
filename = 'favorate_num.json'
with open(filename) as f_obj
    favorate_num = json.load(f_obj)
    print("i know your favorate number! It is " + favorate_num)


# 10.4.3 file 2017-7-2 Shenzhen ''
import json
def get_stored_username()
    filename = 'username.json'
    try
        with open(filename) as f_obj
            username = json.load(f_obj)
    except FileNotFoundError
        return None 
       
    else
        return username

def get_new_username()
    username = input("what is your name?")
    filename = 'username.json'
    with open(filename,'w') as f_obj       #文件不存在就创建
        json.dump(username,f_obj)       #给文件写入username

def greet_user()
    username = get_stored_username()
    if username
        print("welcome back, " + username)
    else
        username = get_new_username()
        print("we will remeber you when you come back, " + username)

greet_user()















# 10.4.2 file 2017-7-2 Shenzhen ''
import json
#如果以前存储了用户名,直接调用,如果没有存储,新建用户名
filename = 'username.json'
try
    with open(filename) as f_obj
        username = json.load(f_obj)
except FileNotFoundError
    username = input("what is your name?")
    with open(filename, 'w') as f_obj #'w'标记,表示,如果文件不存在,就创建该文件
        json.dump(username, f_obj)          #文件创建好了后,写入内容username
        print("we will remeber you when you come back, " + username)
else 


    print("welcome back, " + username)




# 10.4.2 file 2017-7-2 Shenzhen ''
import json
username = input("what is your name?")
filename = 'username.json'
with open(filename, 'w') as f_obj
    json.dump(username, f_obj)
    print("we will remeber you when you come back, " + username) 

# 10.4.2 file 2017-7-2 Shenzhen ''
import json

filename = 'username.json'
with open(filename) as f_obj
    username = json.load(f_obj)
    print("welcome back, " + username)


# 10.4.1 file 2017-7-2 Shenzhen ''
import json

filename= 'numbers.json'
with open(filename) as f_obj
    numbers = json.load(f_obj)          
    #函数json.load()从参数代表的文件中下载数据
print(numbers)


# 10.4.1 file 2017-7-2 Shenzhen ''
import json
numbers = [2,3,4,5,6,7,89]
filename= 'numbers.json'
with open(filename,'w') as f_obj
    json.dump(numbers, f_obj)       #函数json.dump()接受两个实参,
    #要存储的数据:numbers,和可用于存储数据的文件对象
    #该函数作用就是把数据写入文件中和write()函数功能一样





# 10-10 file 2017-7-2 Shenzhen ''

file_name = 'CarbonSpineTableTop_UC.stl'
try
    with open(file_name) as file_object
        contents=file_object.read()
except FileNotFoundError
    message = "Sorry, the file " + file_name + " does not exist."
    print(message)
else
    
    words = contents.count('vertex')
    
    print(words)




36
[Finished in 0.2s]




# 10-9 file 2017-7-2 Shenzhen ''
try
    filename1 = 'cats.txt'
    filename2 = 'dogs.txt'
    with open(filename1) as file_object
        contents1 = file_object.read()
        print(contents1)

    with open(filename2) as file_object
        contents2 = file_object.read()
        print(contents2)
except FileNotFoundError
    pass










# 10-8 file 2017-7-2 Shenzhen ''
try
    filename1 = 'cats.txt'
    filename2 = 'dogs.txt'
    with open(filename1) as file_object
        contents1 = file_object.read()
        print(contents1)

    with open(filename2) as file_object
        contents2 = file_object.read()
        print(contents2)
except FileNotFoundError
    print("i can not find the file 'dog.txt', please creat it. ")



mimi huahua taoqi
i can not find the file 'dog.txt', please creat it. 
[Finished in 0.2s]







# 10-7 file 2017-7-2 Shenzhen ''
print("input two numbers and caculate the add of them. " +
    "press 'q' to exit the input ")
while True
    while True
        first_number = input("input the first number ")
        if first_number == 'q'
            break
        second_number = input("input the second number ")
        if first_number == 'q'
            break

        try
            answer = int(first_number) + int(second_number)
        except ValueError
            print("you have to input number.")
        else
            print(answer)
    if first_number == 'q' or second_number == 'q'
            break



# 10-6 file 2017-7-2 Shenzhen ''
print("input two numbers and caculate the add of them. " +
    "press 'q' to exit the input ")

while True
    first_number = input("input the first number ")
    if first_number == 'q'
        break
    second_number = input("input the second number ")
    if first_number == 'q'
        break

    try
        answer = int(first_number) + int(second_number)
    except ValueError
        print("you have to input number.")
    else
        print(answer)




# 10.3.8 file 2017-7-2 Shenzhen ''
def count_words(file_name)
#计算文件中含有多少个字符
    try
        with open(file_name) as file_object
            contents=file_object.read()
    except FileNotFoundError
        pass            #直接忽略掉不存在的文件,也不会报错,
    else
        words = contents.split()
        num_words = len(words)
        print("the file " + file_name +"has about " + str(num_words) + " words.")

file_names =[ 'alice.txt', 'siddhartha.txt','moby_dick.txt','little_women.txt']
for file_name in file_names
    count_words(file_name)






# 10.3.7 file 2017-7-2 Shenzhen ''
def count_words(file_name)
#计算文件中含有多少个字符
    try        
        with open(file_name) as file_object
            contents=file_object.read()
    except FileNotFoundError
        message = "Sorry, the file " + file_name + " does not exist."
        print(message)
    else
        words = contents.split()
        num_words = len(words)
        print("the file " + file_name +"has about " + str(num_words) + " words.")

file_names =[ 'alice.txt', 'siddhartha.txt','moby_dick.txt','little_women.txt']
for file_name in file_names
    count_words(file_name)








# 10.3.6 file 2017-7-2 Shenzhen ''

file_name = 'alice.txt'
try
    with open(file_name) as file_object
        contents=file_object.read()
except FileNotFoundError
    message = "Sorry, the file " + file_name + " does not exist."
    print(message)
else
    words = contents.split()       #计算words中字符串个数,也就是单词个数
    #words = contents  #计算words中字符个数
    num_words = len(words) 
    print("the file " + file_name +"has about " + str(num_words) + " words.")






# 10.3.6 file 2017-7-2 Shenzhen ''

title= "alice in wonderland"
print(title)
print(title.split())            #split()可以把有三个单词的字符串分割为有许多元素(三个单词)的列表

alice in wonderland     这是字符串的形式
['alice', 'in', 'wonderland']       #列表形式
[Finished in 0.3s]

# 10.3.5 file 2017-7-2 Shenzhen ''

file_name = 'alice.txt'
try            #使用try except 代码块避免程序碰到异常崩溃。
    with open(file_name) as file_object
        contents=file_object.read()
except FileNotFoundError
    message = "Sorry, the file " + file_name + " does not exist."
    print(message)

Sorry, the file alice.txt does not exist.
[Finished in 0.2s]


# 10.3.3 file 2017-7-2 Shenzhen ''
print("give me two numbers and i will divide them")
print("enter 'q' to exit")

while True
    first_number = input("first number ")
    if first_number == 'q'
        break
    second_number = input("second number")
    if second_number =='q'
        break
    answer = int(first_number)/int(second_number)
    print(answer)



# 10.3.2 file 2017-7-2 Shenzhen ''
try            # 
    print(5/0)
except ZeroDivisionError
    print("you can nont divide by zero!")




# 10-3 file 2017-7-2 Shenzhen ''

#filename = 'learning_python.txt'
print("please input your name")
with open('programming.txt','a') as file_object
    file_object.write("\nI also love finding meaning in large datasets.")
    file_object.write("\nI like creating apps that runs in a browser.")
    file_object.write("\ngung yang")


# 10.1.8 file 2017-7-2 Shenzhen ''

#filename = 'learning_python.txt'

with open('programming.txt','a') as file_object
    file_object.write("\nI also love finding meaning in large datasets.")
    file_object.write("\nI like creating apps that runs in a browser.")




# 10.1.7 file 2017-7-2 Shenzhen ''

#filename = 'learning_python.txt'

with open('programming.txt','w') as file_object
    file_object.write("I love programming.")
    file_object.write("\nI like creating new games.")
    
# 10.1.7 file 2017-7-2 Shenzhen ''

#filename = 'learning_python.txt'

with open('programming.txt','a') as file_object
    file_object.write("\nI also love finding meaning in large datasets.")
    file_object.write("\nI like creating apps that runs in a browser.")


#或者如下
open('programming.txt','w').write("I love programming."
    + "\nI also love finding meaning in large datasets."
    + "\nI like creating apps that runs in a browser.")



# 10.2.1 file 2017-7-2 Shenzhen ''

#filename = 'learning_python.txt'
#打开这个文件,如果文件不存在,就创建一个这样的文件。打开文件,格式化文件内容,输入write里的内容
with open('programming.txt','w') as file_object
    file_object.write("I love programming.")

#或者写成
open('programming.txt','w').write("I love programming.")
    


# 10-2 file 2017-7-2 Shenzhen ''
#problem程序无法使用replace函数。该问题已经解决,
filename = 'learning_python.txt'

with open(filename) as file_object
    lines = file_object.readlines()

for line in lines
    #print(line.rstrip())
   
    message = line.replace('Python', 'C')               #replace()就是用新字符替换旧字符串。
    #新字符串放在右侧
    
    print(message)

#或者写成如下程序
print(open('learning_python.txt').read().replace('Python', 'C'))

In C I can deal with all kinds of number and characters
In C I can use loop like do .. while; while(); if else; if elif elif else;
In C I can deal with file
In C I can make a game called space war
[Finished in 0.3s]

#原来错误程序如下,错误原因再于没有把处理的结果正确打印出来
# 10-2 file 2017-7-2 Shenzhen ''
#problem程序无法使用replace函数
filename = 'learning_python.txt'

with open(filename) as file_object
    lines = file_object.readlines()

for line in lines
    #print(line.rstrip())
   
    message = line
    message.replace('Python', 'C')
    
    print(message.strip())

In Python I can deal with all kinds of number and characters
In Python I can use loop like do .. while; while(); if else; if elif elif else;
In Python I can deal with file
In Python I can make a game called space war
[Finished in 0.3s]


# 10-1 file 2017-7-2 Shenzhen ''

filename = 'learning_python.txt'

with open(filename) as file_object
    contents = file_object.read()
    
print(contents)

with open(filename) as file_object
    #contents = file_object.read()
    lines = file_object.readlines()
for line in lines
    print(line.rstrip())

learning_string = ''
for line in lines
    learning_string +=line.strip()
print(learning_string)







# 10.1.7 file 2017-7-2 Shenzhen ''

filename = 'pi_million_digits.txt'

with open(filename) as file_object
    lines = file_object.readlines()

pi_string = ''
for line in lines
    pi_string += line.strip()

birthday = input("enter your birthday, in the form mmddyy")
if birthday in pi_string
    print("your birthday appears in the first million digits of pi!")
else
    print("your birthday doesn't appear in the first million digits of pi!")




# 10.1.5 file 2017-7-2 Shenzhen ''

filename = 'pi_million_digits.txt'

with open(filename) as file_object
    lines = file_object.readlines()
print(lines)
pi_string = ''
for line in lines
    pi_string += line.strip()           #把数组中的每个元素(每行为一个元素),添加到字符串中,
    #相当于把数组转化为了一个大大的字符串,并且砍去了左右两侧的空格和回车,但是不能删除元素内部的空格

print(pi_string[52] + "...")
print(len(pi_string))
print(pi_string)

['solid CarbonSpineTableTop_UC.xml\n', '  facet normal 0.0127001469276938 -0.976683740874678 0.214307201416703\n', '    outer loop\n', '      vertex 46.776 -922.29 129.226\n', '      vertex 43.791 -913.621 168.911\n', '      vertex -46.622 -923.499 129.251\n', '    endloop\n', '  endfacet\n', '  facet normal -0.000279634081810437 0.000924132031115562 -0.999999533892276\n', '    outer loop\n', '      vertex -46.622 -923.499 129.251\n', '      vertex -41.116 915.566 130.949\n', '      vertex 46.776 -922.29 129.226\n', '    endloop\n', '  endfacet\n', '  facet normal -8.32043915054624E-05 0.000933525936137284 -0.999999560803081\n', '    outer loop\n', '      vertex 46.776 -922.29 129.226\n', '      vertex -41.116 915.566 130.949\n', '      vertex 40.947 921.809 130.948\n', '    endloop\n', '  endfacet\n', '  facet normal -0.999995330588652 0.00299333044944216 0.000615445946858977\n', '    outer loop\n', '      vertex -41.118 908.294 163.068\n', '      vertex -41.116 915.566 130.949\n', '      vertex -46.622 -923.499 129.251\n', '    endloop\n', '  endfacet\n', '  facet normal -0.0739917576942274 0.972642290740622 0.220209432259733\n', '    outer loop\n', '      vertex 40.947 921.809 130.948\n', '      vertex -41.116 915.566 130.949\n', '      vertex -41.118 908.294 163.068\n', '    endloop\n', '  endfacet\n', '  facet normal -0.00173458985321827 -0.969419158869921 0.245404738369038\n', '    outer loop\n', '      vertex 43.791 -913.621 168.911\n', '      vertex -43.535 -913.465 168.91\n', '      vertex -46.622 -923.499 129.251\n', '    endloop\n', '  endfacet\n', '  facet normal -0.997013707777174 0.00157037017712669 0.0772088106495587\n', '    outer loop\n', '      vertex -41.118 908.294 163.068\n', '      vertex -46.622 -923.499 129.251\n', '      vertex -43.535 -913.465 168.91\n', '    endloop\n', '  endfacet\n', '  facet normal 0.00150640610275766 0.92034717740265 0.391099480679313\n', '    outer loop\n', '      vertex -41.118 908.294 163.068\n', '      vertex 41.361 908.159 163.068\n', '      vertex 40.947 921.809 130.948\n', '    endloop\n', '  endfacet\n', '  facet normal 0.999928377094609 0.00317144318875765 -0.0115404778515142\n', '    outer loop\n', '      vertex 40.947 921.809 130.948\n', '      vertex 41.361 908.159 163.068\n', '      vertex 46.776 -922.29 129.226\n', '    endloop\n', '  endfacet\n', '  facet normal 0.997207481463438 0.00156960685246571 0.0746644175472933\n', '    outer loop\n', '      vertex 46.776 -922.29 129.226\n', '      vertex 41.361 908.159 163.068\n', '      vertex 43.791 -913.621 168.911\n', '    endloop\n', '  endfacet\n', '  facet normal -5.72177120225145E-06 0.00320727861954548 0.999994856652332\n', '    outer loop\n', '      vertex 43.791 -913.621 168.911\n', '      vertex 41.361 908.159 163.068\n', '      vertex -43.535 -913.465 168.91\n', '    endloop\n', '  endfacet\n', '  facet normal 5.24877352886244E-06 0.00320676734731182 0.999994858294597\n', '    outer loop\n', '      vertex -43.535 -913.465 168.91\n', '      vertex 41.361 908.159 163.068\n', '      vertex -41.118 908.294 163.068\n', '    endloop\n', '  endfacet\n', 'endsolid CarbonSpineTableTop_UC.xml\n']
solid CarbonSpineTableTop_UC.xmlfacet normal 0.01270...
2283
solid CarbonSpineTableTop_UC.xmlfacet normal 0.0127001469276938 -0.976683740874678 0.214307201416703outer loopvertex 46.776 -922.29 129.226vertex 43.791 -913.621 168.911vertex -46.622 -923.499 129.251endloopendfacetfacet normal -0.000279634081810437 0.000924132031115562 -0.999999533892276outer loopvertex -46.622 -923.499 129.251vertex -41.116 915.566 130.949vertex 46.776 -922.29 129.226endloopendfacetfacet normal -8.32043915054624E-05 0.000933525936137284 -0.999999560803081outer loopvertex 46.776 -922.29 129.226vertex -41.116 915.566 130.949vertex 40.947 921.809 130.948endloopendfacetfacet normal -0.999995330588652 0.00299333044944216 0.000615445946858977outer loopvertex -41.118 908.294 163.068vertex -41.116 915.566 130.949vertex -46.622 -923.499 129.251endloopendfacetfacet normal -0.0739917576942274 0.972642290740622 0.220209432259733outer loopvertex 40.947 921.809 130.948vertex -41.116 915.566 130.949vertex -41.118 908.294 163.068endloopendfacetfacet normal -0.00173458985321827 -0.969419158869921 0.245404738369038outer loopvertex 43.791 -913.621 168.911vertex -43.535 -913.465 168.91vertex -46.622 -923.499 129.251endloopendfacetfacet normal -0.997013707777174 0.00157037017712669 0.0772088106495587outer loopvertex -41.118 908.294 163.068vertex -46.622 -923.499 129.251vertex -43.535 -913.465 168.91endloopendfacetfacet normal 0.00150640610275766 0.92034717740265 0.391099480679313outer loopvertex -41.118 908.294 163.068vertex 41.361 908.159 163.068vertex 40.947 921.809 130.948endloopendfacetfacet normal 0.999928377094609 0.00317144318875765 -0.0115404778515142outer loopvertex 40.947 921.809 130.948vertex 41.361 908.159 163.068vertex 46.776 -922.29 129.226endloopendfacetfacet normal 0.997207481463438 0.00156960685246571 0.0746644175472933outer loopvertex 46.776 -922.29 129.226vertex 41.361 908.159 163.068vertex 43.791 -913.621 168.911endloopendfacetfacet normal -5.72177120225145E-06 0.00320727861954548 0.999994856652332outer loopvertex 43.791 -913.621 168.911vertex 41.361 908.159 163.068vertex -43.535 -913.465 168.91endloopendfacetfacet normal 5.24877352886244E-06 0.00320676734731182 0.999994858294597outer loopvertex -43.535 -913.465 168.91vertex 41.361 908.159 163.068vertex -41.118 908.294 163.068endloopendfacetendsolid CarbonSpineTableTop_UC.xml
[Finished in 0.3s]

# 10.1.4 file 2017-7-2 Shenzhen ''

filename = 'CarbonSpineTableTop_UC.stl'

with open(filename) as file_object
    lines = file_object.readlines()     #lines包含了文件里面的所有行,每个元素就是一行

for line in lines
    print(line.rstrip())

#more easy
lines = open(filename).readlines()
for line in lines
    print(line.rstrip())

#more easy
for line in open(filename).readlines()
    print(line.rstrip())

#more easy
for line in open(filename)
    print(line.rstrip())

#但是不能写成,因为会把所有字母排成一个竖列输出,完全看不出内容是什么东西。
for line in open(filename).read()
    print(line.rstrip())

'''
注意read()一般是读取文本中的全部内容,并以字符串的形式返回 ,
所以,在for循环中才会发现所有字符都会占一行,无法统计规律


readline()读取文本第一行,并以字符串的形式返回
所以,在for循环中才会发现所有字符都会占一行,无法统计规律


readlines()读取文本所有内容,并以数列的形式返回,


filename = 'CarbonSpineTableTop_UC.stl'
a ={}
a = open(filename).readlines()
print(a)

通过以上程序的输出可以看出a = open(filename).readlines()里面是以每行为一个列表元素的集合,
并且自动在每行的后面加上回车符号,列表每个元素用逗号分开,每个元素最后面都有回车符号。
所以,在for循环中才会按照原格式正常输出(原格式中的一行为一个元素)

'''

# 10.1.3 file 2017-7-2 Shenzhen ''

filename = 'CarbonSpineTableTop_UC.stl'

with open(filename) as file_object
    for line in file_object
        print(line)

#more easy and beautiful
for line in open(filename)
    print(line.rstrip())

# 10.1.2 file 2017-7-2 Shenzhen ''
with open('edit_files\CarbonSpineTableTop_UC.stl') as file_object
    contents = file_object.read()
    print(contents.rstrip()) #rstr5ip() delete the space at the end of output


#更简单的方法
print(open('edit_files\CarbonSpineTableTop_UC.stl').read().rstrip())

# 10.1.1 file 2017-7-2 Shenzhen ''
with open('CarbonSpineTableTop_UC.stl') as file_object
    contents = file_object.read()
    print(contents)

# 10.1.1 file 2017-7-2 Shenzhen ''
with open('pi_digits.txt') as file_object
    contents = file_object.read()
    print(contents)

#更简单的方法
print(open('pi_digits.txt').read())



# 9-14   class 2017-6-30 Shenzhen ''
# library block using
from random import randint

class Die()
    def __init__(self,sides)
        self.sides=sides

    def roll_die(self)
        x = randint(1,self.sides)           #输出1到self.sides()之间的随机数
        print(x)
shanzi = Die(10)
shanzi.roll_die()

输出1到10的数字



# 9-14   class 2017-6-30 Shenzhen ''
# library block using
# a problem function, the reason is that i forgot the self in 
from random import randint

class Die()
    def __init__(self,sides)
        self.sides=6

    def roll_die()
        x = randint(1,self.sides)
        print(x)
shanzi = Die(6) #创建shanzi的实例,
shanzi.roll_die()           #调用类里面的roll_die()方法,该方法自动输出1到6之间的随机数

一下是错误原因,改正后的程序在上面   
Traceback (most recent call last)
  File "D\Sublime text_work\Python_work\test.py", line 14, in <module>
    shanzi.roll_die()
TypeError roll_die() takes 0 positional arguments but 1 was given
[Finished in 0.4s with exit code 1]

# 9-13   class 2017-6-30 Shenzhen ''
# library block using
from collections import OrderedDict

faverate_numbers=OrderedDict()

faverate_numbers['jack']='1'
faverate_numbers['mike']='2'
faverate_numbers['tom']='3'
faverate_numbers['lili']='4'
faverate_numbers['lucy']='5'
for name,number in faverate_numbers.items()
    print(name+'   like number '+number)
print('\n')
faverate_numbers['martin']='6'
faverate_numbers['johanes']='8'
faverate_numbers['alix']='7'

faverate_numbers['andre']='9'
faverate_numbers['dirk']='10'
for name,number in faverate_numbers.items()
    print(name+'   like number '+number)


jack   like number 1
mike   like number 2
tom   like number 3
lili   like number 4
lucy   like number 5


jack   like number 1
mike   like number 2
tom   like number 3
lili   like number 4
lucy   like number 5
martin   like number 6
johanes   like number 8
alix   like number 7
andre   like number 9
dirk   like number 10
[Finished in 0.2s]

# 9.5   class 2017-6-30 Shenzhen ''
# library block using
from collections import OrderedDict


favorite_languages= OrderedDict()
favorite_languages['jen'] =['python','ruby']
favorite_languages['sarah']=['C','C++']
favorite_languages['edward']=['ruby','go']
favorite_languages['phil']=['python','haskell']

for name,languages in favorite_languages.items()
    print(name+"'s favorite languages are ")
    for language in languages
        print(language.title())

jen's favorite languages are 
Python
Ruby
sarah's favorite languages are 
C
C++
edward's favorite languages are 
Ruby
Go
phil's favorite languages are 
Python
Haskell
[Finished in 0.4s]

# 9.4.6   class 2017-6-30 Shenzhen ''
#car 意思是car。py文件,里面有关于car的模块。,从里面引用Car类
from car import Car 
from electric_car import ElectricCar 

my_tesla = ElectricCar('tesla','model s', 2016)

print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()

my_beetle = Car('volkswagen','beetle',2016)
print(my_beetle.get_descriptive_name())

2016 Tesla Model S
this car has a 70-kwh battery
this car can go approximately 240 miles on a full charge
2016 Volkswagen Beetle
[Finished in 0.2s]

# 9.4.4   class 2017-6-30 Shenzhen ''
#car 意思是car。py文件,里面有关于car的模块。,从里面引用Car类
import car

my_tesla = car.ElectricCar('tesla','model s', 2016)

print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()

my_beetle = car.Car('volkswagen','beetle',2016)
print(my_beetle.get_descriptive_name())


2016 Tesla Model S
this car has a 70-kwh battery
this car can go approximately 240 miles on a full charge
2016 Volkswagen Beetle
[Finished in 0.2s]


# 9.4.3   class 2017-6-30 Shenzhen ''
#car 意思是car。py文件,里面有关于car的模块。,从里面引用Car类
from car import ElectricCar,Car

my_tesla = ElectricCar('tesla','model s', 2016)

print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()

my_beetle = Car('volkswagen','beetle',2016)
print(my_beetle.get_descriptive_name())


2016 Tesla Model S
this car has a 70-kwh battery
this car can go approximately 240 miles on a full charge
2016 Volkswagen Beetle
[Finished in 0.2s]


# 9.4.2   class 2017-6-30 Shenzhen ''
#car 意思是car。py文件,里面有关于car的模块。,从里面引用ElectricCar类
from car import ElectricCar     

my_tesla = ElectricCar('tesla','model s', 2016)

print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()

2016 Tesla Model S
this car has a 70-kwh battery
this car can go approximately 240 miles on a full charge

[Finished in 0.2s]


# 9.4.1class 2017-6-30 Shenzhen ''
#car 意思是car。py文件,里面有关于car的模块。,从里面引用Car类
from car import Car

my_new_car = Car('Audi','a4',2016)
print(my_new_car.get_descriptive_name())
my_new_car.odometer_reading = 23
my_new_car.read_odometer()




# 9-7 class 2017-7-1 Shenzhen ''

class User()
    def __init__(self, first_name, last_name, age)
        self.first_name = first_name
        self.last_name = last_name
        self.age = age

    def describe_user(self)
        print("the fisrt name of the user is " + self.first_name)
        print("the last name of the user is " + self.last_name)
        print("the age of the user is " + self.age)

    def greet_user(self)
        print("hello " + self.first_name + self.last_name)


class Admin(User)
    def __init__(self, first_name, last_name, age)
        super().__init__(first_name, last_name, age)
        #self.privileges = 

    def show_privileges()
        privileges = ["can add post", "can delete post", "can ban user"]
        for privilege in privileges
            print("the users' privileges are "+ privilege)

admin=Admin('guang', 'yang', '28')
admin.show_privileges()







# 9-6 class 2017-7-1 Shenzhen ''

class Restaurant()

    def __init__(self, restaurant_name, cuisine_type)
        self.restaurant_name = restaurant_name
        self.cuisine_type = cuisine_type

    def describe_restaurant(self)
        print("the restaurant name is " + self.restaurant_name)
        print("the cuisine is " + self.cuisine_type)

    def open_restaurant(self)
        print("the restaurant is running!")


class IceCreamStand(Restaurant)
    def __init__(self,restaurant_name, cuisine_type)
        super().__init__(restaurant_name, cuisine_type)
        #self.flavors=['banana','strawbery','apple']

    def ice_types(self)
        flavors = ['apple','strawbery','banana']
        for flavor in flavors
            print("the flavors of the icecream are " + flavor)


icecream = IceCreamStand('shanghai restaurant', 'chinese')
#icecream.flavors = ['banana','strawbery','apple']
icecream.ice_types()


the flavors of the icecream are apple
the flavors of the icecream are strawbery
the flavors of the icecream are banana
[Finished in 0.2s]







# 9-6 class 2017-7-1 Shenzhen ''
# the programm has a problem
class Restaurant()

    def __init__(self, restaurant_name, cuisine_type)
        self.restaurant_name = restaurant_name
        self.cuisine_type = cuisine_type

    def describe_restaurant(self)
        print("the restaurant name is " + self.restaurant_name)
        print("the cuisine is " + self.cuisine_type)

    def open_restaurant(self)
        print("the restaurant is running!")


class IceCreamStand(Restaurant)
    def __init__(self,restaurant_name, cuisine_type)
        super().__init__(restaurant_name, cuisine_type,flavors)
        #self.flavors=['banana','strawbery','apple']

    def ice_types(self)
        for flavor in flavors
            print("the flavors of the icecream are " + flavor)

restaurant = Restaurant('shanghai restaurant', 'chinese')

icecream = IceCreamStand('shanghai restaurant', 'chinese',"['banana','strawbery','apple']")
#icecream.flavors = ['banana','strawbery','apple']
icecream.ice_types()
restaurant.describe_restaurant()
restaurant.open_restaurant()











# 9.3.5 class 2017-7-1 Shenzhen ''
class Car()
    def __init__(self, make, model, year)
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0

    def get_descriptive_name(self)
        long_name = str(self.year) +' ' + self.make + ' ' + self.model
        return long_name.title()

    def update_odometer(self,mileage)
        if mileage >= self.odometer_reading

            self.odometer_reading = mileage
        else
            print("you have to give a larger number")

    def increment_odometer(self, miles)
        if miles >= 0
            self.odometer_reading +=miles
        else
            print("please give a number which is larger than 0")

    def read_odometer(self)
        print("this car has " + str(self.odometer_reading) + " miles on it.")

class Battery()            #电池类,但是没有继承父类Car()的方法,因为汽车的方法都不实用电池
    def __init__(self, battery_size=70)            #因为电池不属于汽车的子类,所以看不到super().__init__
        self.battery_size = battery_size

    def describe_battery(self)
        print("this car has a " + str(self.battery_size) + "-kwh battery")

    def get_range(self)
        if self.battery_size == 70
            range = 240
        elif self.battery_size == 85
            range = 270

        message="this car can go approximately " + str(range)
        message += " miles on a full charge"
        print(message)

class ElectricCar(Car)
    def __init__(self, make, model, year)
        super().__init__(make, model, year)
        self.battery = Battery()        #self.battery is not in init shuxing

my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()

2016 Tesla Model S
this car has a 70-kwh battery
this car can go approximately 240 miles on a full charge
[Finished in 0.2s]



# 9.3.5 class 2017-7-1 Shenzhen ''
class Car()
    def __init__(self, make, model, year)
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0

    def get_descriptive_name(self)
        long_name = str(self.year) +' ' + self.make + ' ' + self.model
        return long_name.title()

    def update_odometer(self,mileage)
        if mileage >= self.odometer_reading

            self.odometer_reading = mileage
        else
            print("you have to give a larger number")

    def increment_odometer(self, miles)
        if miles >= 0
            self.odometer_reading +=miles
        else
            print("please give a number which is larger than 0")

    def read_odometer(self)
        print("this car has " + str(self.odometer_reading) + " miles on it.")

class Battery()
    def __init__(self, battery_size=70)
        self.battery_size = battery_size

    def describe_battery(self)
        print("this car has a " + str(self.battery_size) + "-kwh battery")

    def get_range(self)
    	if self.battery_size == 70
    		range = 240
    	elif self.battery_size == 85
    		range = 270
    	message="this car can go approximately " + str(range)
    	message += "miles on a full charge"
    	print(message)

class ElectricCar(Car)
    def __init__(self, make, model, year)
        super().__init__(make, model, year)
        self.battery = Battery()        #self.battery is not in init shuxing

my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())      #从父类Car()中调取get_descriptive_name()
my_tesla.battery.describe_battery()         #从类Battery()中调取describe_battery()

2016 Tesla Model S
this car has a 70-kwh battery
[Finished in 0.3s]

# 9.3.4 class 2017-7-1 Shenzhen ''
class Car()
    def __init__(self, make, model, year)
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0

    def get_descriptive_name(self)
        long_name = str(self.year) +' ' + self.make + ' ' + self.model
        return long_name.title()

    def update_odometer(self,mileage)
        if mileage >= self.odometer_reading

            self.odometer_reading = mileage
        else
            print("you have to give a larger number")

    def increment_odometer(self, miles)
        if miles >= 0
            self.odometer_reading +=miles
        else
            print("please give a number which is larger than 0")

    def read_odometer(self)
        print("this car has " + str(self.odometer_reading) + " miles on it.")

    def fill_gas_tank(self)
        print("the gas tank is 50 L")

class ElectricCar(Car)
    def __init__(self, make, model, year)
        super().__init__(make, model, year)
        self.battery_size = 70

    def describe_battery(self)
        print("this car has a " + str(self.battery_size) + "-kwh battery")

    def fill_gas_tank(self)
        print("the electric car has no gas tank")

my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()
my_tesla.fill_gas_tank()

2016 Tesla Model S
this car has a 70-kwh battery
the electric car has no gas tank
[Finished in 0.3s]


# 9.3.3 class 2017-7-1 Shenzhen ''
class Car()
    def __init__(self, make, model, year)
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0

    def get_descriptive_name(self)
        long_name = str(self.year) +' ' + self.make + ' ' + self.model
        return long_name.title()

    def update_odometer(self,mileage)
        if mileage >= self.odometer_reading

            self.odometer_reading = mileage
        else
            print("you have to give a larger number")

    def increment_odometer(self, miles)
        if miles >= 0
            self.odometer_reading +=miles
        else
            print("please give a number which is larger than 0")

    def read_odometer(self)
        print("this car has " + str(self.odometer_reading) + " miles on it.")

class ElectricCar(Car)
    def __init__(self, make, model, year)
        super().__init__(make, model, year)
        self.battery_size = 70

    def describe_battery(self)
        print("this car has a " + str(self.battery_size) + "-kwh battery")

my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())                  #子类通过实例可以调用父类的方法
my_tesla.describe_battery()                             #子类通过实例也可以调用子类的方法

2016 Tesla Model S
this car has a 70-kwh battery
[Finished in 0.5s]




# 9.3.1 class 2017-7-1 Shenzhen ''
class Car()
    def __init__(self, make, model, year)
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0

    def get_descriptive_name(self)
        long_name = str(self.year) +' ' + self.make + ' ' + self.model
        return long_name.title()

    def update_odometer(self,mileage)
        if mileage >= self.odometer_reading

            self.odometer_reading = mileage
        else
            print("you have to give a larger number")

    def increment_odometer(self, miles)
        if miles >= 0
            self.odometer_reading +=miles
        else
            print("please give a number which is larger than 0")

    def read_odometer(self)
        print("this car has " + str(self.odometer_reading) + " miles on it.")

class ElectricCar(Car) #子类ElectricCar()继承父类Car()的所有属性,方法,
    def __init__(self, make, model, year)      #子类初始化
        super().__init__(make, model, year)     #父类初始化(superclass())代表继承父类的意思

my_tesla = ElectricCar('tesla', 'model s', 2016)        #创建my_tesla()的实例,
print(my_tesla.get_descriptive_name())      #


2016 Tesla Model S
[Finished in 0.2s]


# #9-5 class 2017-6-30 Shenzhen ''
class User()
    def __init__(self, first_name, last_name, age,login_attempts)
        self.first_name = first_name
        self.last_name = last_name
        self.age = age
        self.login_attempts = login_attempts

    def increment_login_attempts(self, increment)
        if increment == 1
            self.login_attempts+= increment 
        else
            print("the increment can only be 1")

    def reset_login_attempts(self, reset)
        self.login_attempts =reset 

    #def describe_user(self)
        print("the fisrt name of the user is " + self.first_name)
        print("the last name of the user is " + self.last_name)
        print("the age of the user is " + str(self.age)
        print("the login times are " + str(self.login_attempts))

    def greet_user(self)
        print("hello " + self.first_name + self.last_name)

user_1 = User('guang', 'yang', 28, 30)


user_1.describe_user()
user_1.greet_user()

print('\n')
user_1.increment_login_attempts(1)
user_1.describe_user()
user_1.greet_user()
print('\n')
user_1.reset_login_attempts(1)
user_1.describe_user()
user_1.greet_user()








# 9-4 class 2017-6-30 Shenzhen ''
class Restaurant()

    def __init__(self, restaurant_name, cuisine_type)
        self.restaurant_name = restaurant_name
        self.cuisine_type = cuisine_type
        self.number_served = 0

    def set_number_served(self, number)
        self.number_served = number 

    def increment_number_served(self,increment)
        self.number_served += increment

    def describe_restaurant(self)
        print("the restaurant name is " + self.restaurant_name)
        print("the cuisine is " + self.cuisine_type)
        print("the served number is " + str(self.number_served))

    def open_restaurant(self)
        print("the restaurant is running!")

restaurant = Restaurant('shanghai restaurant', 'chinese')

restaurant.number_served = 30
restaurant.describe_restaurant()
restaurant.open_restaurant()
print('\n')
restaurant.set_number_served(300)
restaurant.describe_restaurant()
restaurant.open_restaurant()
print('\n')
restaurant.increment_number_served(300)
restaurant.describe_restaurant()
restaurant.open_restaurant()


the restaurant name is shanghai restaurant
the cuisine is chinese
the served number is 30
the restaurant is running!


the restaurant name is shanghai restaurant
the cuisine is chinese
the served number is 300
the restaurant is running!


the restaurant name is shanghai restaurant
the cuisine is chinese
the served number is 600
the restaurant is running!
[Finished in 0.3s]

# 9.2.3 class 2017-6-30 Shenzhen ''
class Car()
    def __init__(self, make, model, year)
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0           #可以添加新属性并赋值

    def get_descriptive_name(self)
        long_name = str(self.year) +' ' + self.make + ' ' + self.model
        return long_name.title()

    def update_odometer(self,mileage)
        if mileage >= self.odometer_reading

            self.odometer_reading = mileage
        else
            print("you have to give a larger number")

    def increment_odometer(self, miles)
        if miles >= 0
            self.odometer_reading +=miles
        else
            print("please give a number which is larger than 0")

    def read_odometer(self)
        print("this car has " + str(self.odometer_reading) + " miles on it.")

my_new_car = Car('audi', 'a4', 2016)
print(my_new_car.get_descriptive_name())
my_new_car.odometer_reading = 22        #给新属性从新赋值
my_new_car.read_odometer()                      #调用方法读出新的数据

my_new_car.update_odometer(26)              #更新里程表数据,并且保证更新后的值大于更新前的值
my_new_car.read_odometer()

my_new_car.increment_odometer(6)            #增加里程表数据6
my_new_car.read_odometer()



2016 Audi A4
this car has 22 miles on it.
this car has 26 miles on it.
this car has 32 miles on it.
[Finished in 0.2s]




# 9.2.1 class 2017-6-30 Shenzhen ''
class Car()
    def __init__(self, make, model, year)
        self.make = make
        self.model = model
        self.year = year

    def get_descriptive_name(self)
        long_name = str(self.year) +' ' + self.make + ' ' + self.model
        return long_name.title()

my_new_car = Car('audi', 'a4', 2016)
print(my_new_car.get_descriptive_name())


2016 Audi A4
[Finished in 0.2s]





# #9-3 class 2017-6-30 Shenzhen ''
class User()
    def __init__(self, first_name, last_name, age)
        self.first_name = first_name
        self.last_name = last_name
        self.age = age

    def describe_user(self)
        print("the fisrt name of the user is " + self.first_name)
        print("the last name of the user is " + self.last_name)
        print("the age of the user is " + self.age)

    def greet_user(self)
        print("hello " + self.first_name + self.last_name)

user_1 = User('guang', 'yang', '28')
user_2 = User('siyuan', 'wang', '26')
user_3 = User('hao', 'wang', '32')

user_1.describe_user()
user_1.greet_user()
user_2.describe_user()
user_2.greet_user()
user_3.describe_user()
user_3.greet_user()

the fisrt name of the user is guang
the last name of the user is yang
the age of the user is 28
hello guangyang
the fisrt name of the user is siyuan
the last name of the user is wang
the age of the user is 26
hello siyuanwang
the fisrt name of the user is hao
the last name of the user is wang
the age of the user is 32
hello haowang
[Finished in 0.2s]

# 9-2 class 2017-6-30 Shenzhen ''
class Restaurant()

    def __init__(self, restaurant_name, cuisine_type)
        self.restaurant_name = restaurant_name
        self.cuisine_type = cuisine_type

    def describe_restaurant(self)
        print("the restaurant name is " + self.restaurant_name)
        print("the cuisine is " + self.cuisine_type)

    def open_restaurant(self)
        print("the restaurant is running!")

restaurant_1 = Restaurant('shanghai restaurant', 'chinese')
restaurant_2 = Restaurant('fensi', 'vetnem')
restaurant_3 = Restaurant('doner', 'german')



print("the restaurant's name is " + restaurant_1.restaurant_name)
print("the cuisine is " + restaurant_1.cuisine_type)

restaurant_1.describe_restaurant()
restaurant_2.describe_restaurant()
restaurant_3.describe_restaurant()


restaurant_1.open_restaurant()


the restaurant's name is shanghai restaurant
the cuisine is chinese
the restaurant name is shanghai restaurant
the cuisine is chinese
the restaurant name is fensi
the cuisine is vetnem
the restaurant name is doner
the cuisine is german
the restaurant is running!
[Finished in 0.2s]




# 9-1 class 2017-6-30 Shenzhen ''
class Restaurant()

    def __init__(self, restaurant_name, cuisine_type)
        self.restaurant_name = restaurant_name
        self.cuisine_type = cuisine_type

    def describe_restaurant(self)
        print("the restaurant name is " + self.restaurant_name)
        print("the cuisine is " + self.cuisine_type)

    def open_restaurant(self)
        print("the restaurant is running!")

restaurant = Restaurant('shanghai restaurant', 'chinese')
print("the restaurant's name is " + restaurant.restaurant_name)
print("the cuisine is " + restaurant.cuisine_type)

restaurant.describe_restaurant()
restaurant.open_restaurant()


the restaurant's name is shanghai restaurant

the cuisine is chinese
the restaurant name is shanghai restaurant
the cuisine is chinese
the restaurant is running!
[Finished in 0.2s]




# 9.1.2 class 2017-6-30 Shenzhen ''
class Dog()
    """
    模拟小狗的尝试
    """
    def __init__(self,name, age)
        """初始化属性name and age"""
        self.name = name
        self.age = age

    def sit(self)
        """
        模拟小狗被命令时候蹲下
        """
        print(self.name.title() + "is now sitting")

    def roll_over(self)
        print(self.name.title() + "rolled over!")

my_dog = Dog('willie', 6)
your_dog = Dog('lucy', 3)

print("My dog's name is ", my_dog.name.title())
print("My dog is " + str(my_dog.age) + " years old.") 
my_dog.sit()

print("Your dog's name is ", my_dog.name.title())
print("Your dog is " + str(my_dog.age) + " years old.") 
your_dog.roll_over()


My dog's name is  Willie
My dog is 6 years old.
Willieis now sitting
Your dog's name is  Willie
Your dog is 6 years old.
Lucyrolled over!
[Finished in 0.3s]


# 9.1.2 class 2017-6-30 Shenzhen ''
class Dog()
    """
    模拟小狗的尝试
    """
    def __init__(self,name, age)
        """初始化属性name and age"""
        self.name = name
        self.age = age

    def sit(self)
        """
        模拟小狗被命令时候蹲下
        """
        print(self.name.title() + "is now sitting")

    def roll_over(self)
        print(self.name.title() + "rolled over!")

my_dog = Dog('willie', 6)
my_dog.sit()
my_dog.roll_over()

Willieis now sitting
Willierolled over!
[Finished in 0.3s]


# 9.1.2 class 2017-6-30 Shenzhen ''
class Dog()
    """
    模拟小狗的尝试
    """
    def __init__(self,name, age)
        """初始化属性name and age"""
        self.name = name
        self.age = age

    def sit(self)
        """
        模拟小狗被命令时候蹲下
        """
        print(self.name.title() + "is now sitting")

    def roll_over(self)
        print(self.name.title() + "rolled over!")

my_dog = Dog('willie', 6)   #'willie', 6相当于给name,age赋值了;my_dog是一个Dog实例
print("My dog's name is ", my_dog.name.title())       #类属性的调用;my_dog就是相当于引用了Dog()类,然后调用下面的name,
print("My dog is " + str(my_dog.age) + " years old.") 

My dog's name is  Willie
My dog is 6 years old.
[Finished in 0.3s]

# 9.1.1 class 类 2017-6-30 Shenzhen ''
class Dog()        Dog()类,并且类名字要大写,一个类可以有无数个函数
    """
    模拟小狗的尝试
    """
    def __init__(self,name, age)                             #括号里面的三个东西叫做属性,
        """初始化属性name and age"""
        self.name = name
        self.age = age

    def sit(self)   #sit()方法,类里面的函数叫做方法
        """
        模拟小狗被命令时候蹲下
        """
        print(self.name.title() + "is now sitting")

    def roll_over(self)
        print(self.name.title() + "rolled over!")







# 8-15 function 函数2017-6-30 Shenzhen ''
from fun import*
unprinted_designs = ['iphone case', 'robot pendant','dodecahedron']
completed_models = []
print_models(unprinted_designs,completed_models)
show_completed_models(completed_models)





# 8.6.5 function 2017-6-30 Shenzhen ''
from fun import*                                    #从fun.py文件引入所有函数,要保证引入的文件和这个文件在一个目录里面
make_pizza(36,'dao')

making a 36 CM pizza with the following toppings 
-dao
[Finished in 0.3s]


# 8.6.4 function 2017-6-30 Shenzhen ''
import fun as f             #引入fun.py文件,并且简写为f

f.make_pizza(36,'dao')






# 8.6.3 function 2017-6-30 Shenzhen ''
from fun import make_pizza as mp            #从fun.py文件引入make_pizza()函数,并且简写为mp

mp(12,'dag')
mp(23,'mushrooms','green peppers','extra cheese')

making a 12 CM pizza with the following toppings 
-dag
making a 23 CM pizza with the following toppings 
-mushrooms
-green peppers
-extra cheese
[Finished in 0.2s]




# 8.6.2 function 2017-6-30 Shenzhen ''
from fun import make_pizza          #从fun.py文件引入make_pizza()函数

make_pizza(12,'dag')        #直接使用make_pizza函数
make_pizza(23,'mushrooms','green peppers','extra cheese')


making a 12 CM pizza with the following toppings 
-dag
making a 23 CM pizza with the following toppings 
-mushrooms
-green peppers
-extra cheese
[Finished in 0.3s]

# 8.6.1 function 2017-6-30 Shenzhen ''
import temp                 #引入temp.py文件

temp.make_pizza(12,'dag')           #调取temp.py文件里面的函数make_pizza(),并且赋值12,'dag'
temp.make_pizza(23,'mushrooms','green peppers','extra cheese')

making a 12 CM pizza with the following toppings 
-dag
making a 23 CM pizza with the following toppings 
-mushrooms
-green peppers
-extra cheese
[Finished in 0.2s]


# 8-14 function 2017-6-30 Shenzhen ''
def build_profile(maker,type, **car_info)
    profile = {}
    profile['maker'] = maker
    profile['type'] = type
    for key,value in car_info.items()
        profile[key] = value
    return profile

user_profile = build_profile('bmw', 'x5', 
    color = 'schwarz',  two_packages = 'true')

print(user_profile)

{'maker' 'bmw', 'type' 'x5', 'color' 'schwarz', 'two_packages' 'true'}
[Finished in 0.3s]








# 8-13 function 2017-6-30 Shenzhen ''
def build_profile(first,last, **user_info)
    profile = {}
    profile['first_name'] = first
    profile['last_name'] = last
    for key,value in user_info.items()
        profile[key] = value
    return profile

user_profile = build_profile('guang', 'yang', 
    location = 'shenzhen', field= 'infomation')

print(user_profile)


{'first_name' 'guang', 'last_name' 'yang', 'location' 'shenzhen', 'field' 'infomation'}
[Finished in 0.2s]


# 8-12 function 2017-6-30 Shenzhen ''
def pizza(*liao)
    print("the pizza has the liao ")
    for lia in liao
        print(lia)
pizza("dao")
pizza('cat', 'dog')
pizza('monkey', 'cat', 'snake')

the pizza has the liao 
dao
the pizza has the liao 
cat
dog
the pizza has the liao 
monkey
cat
snake
[Finished in 0.2s]


# 8.5.2 function 2017-6-30 Shenzhen ''
def build_profile(first,last, **user_info)
    profile = {}
    profile['first_name'] = first
    profile['last_name'] = last
    for key,value in user_info.items()
        profile[key] = value
    return profile

user_profile = build_profile('albert', 'einstein', 
    location = 'princeton', field= 'physics')

print(user_profile)

{'first_name' 'albert', 'last_name' 'einstein', 'location' 'princeton', 'field' 'physics'}
[Finished in 0.2s]



# 8.5.1 function 2017-6-30 Shenzhen ''
def make_pizza(size, *toppings)
    print("making a " + str(size) + " CM pizza with the following toppings ")
    for topping in toppings

        print('-' +topping)

make_pizza(12,'pepperoni')
make_pizza(23,'mushrooms','green peppers','extra cheese')

making a 12 CM pizza with the following toppings 
-pepperoni
making a 23 CM pizza with the following toppings 
-mushrooms
-green peppers
-extra cheese
[Finished in 0.2s]


# 8.5 function 2017-6-30 Shenzhen ''
def make_pizza(*toppings)
    print("making a pizza with the following toppings ")
    for topping in toppings

        print(str("-") +topping)

make_pizza('pepperoni')
make_pizza('mushrooms','green peppers','extra cheese')


making a pizza with the following toppings 
-pepperoni
making a pizza with the following toppings 
-mushrooms
-green peppers
-extra cheese
[Finished in 0.2s]



# 8.5 function 2017-6-30 Shenzhen ''
def make_pizza(*toppings)          #  ‘*’代表参数数目无限制;toppings是参数,也是被输出的东西
    print(toppings)

make_pizza('pepperoni')
make_pizza('mushrooms','green peppers','extra cheese')


('pepperoni',)
('mushrooms', 'green peppers', 'extra cheese')
[Finished in 0.3s]


# 8-10 function 2017-6-30 Shenzhen ''

#this program has a problem
def make_great(magician_names)
    """
    for name in magician_names
        greeting_name = "the great " + name 
        print(greeting_name)
        greeting_names.append(greeting_name)
    """
    while magician_names
        
        name=magician_names.pop()
        greeting_name="the great " + name
        print(greeting_name)
        greeting_names.append(greeting_name)


def show_magicians(magician_names)
    make_great(magician_names)



names=['jack','like','lucy']
greeting_names=[]
show_magicians(names)
print('\n')
print("the greeting_names " + str(greeting_names) + "\n")
print("names " + str(names))

the great lucy
the great like
the great jack


the greeting_names ['the great lucy', 'the great like', 'the great jack']

names []
[Finished in 0.2s]






# 8-10 function 2017-6-30 Shenzhen ''
def make_great(magician_names)
    for name in magician_names
        greeting = "the great " + name 
        print(greeting)

def show_magicians(magician_names)
    make_great(magician_names)

the great jack
the great like
the great lucy
[Finished in 0.2s]

names=['jack','like','lucy']
#make_great(names)
show_magicians(names)


# 8-9 function 2017-6-30 Shenzhen ''
def show_magicians(magician_names)
    for name in names

        print(name)
names=['jack','like','lucy']
show_magicians(names)


# 8.4.2 function 2017-6-30 Shenzhen ''

def print_models(unprinted_designs,completed_models)
    """
    模拟打印每个设计,直到没有未打印的为止
    打印每个设计后,都将其移动到列表completed——models中
    """
    while unprinted_designs
        current_design = unprinted_designs.pop()          #把没打印的东西从尾部,一个个弹出来,

        print("printing model " + current_design)
        completed_models.append(current_design)             #把弹出来的东西一个个添加到完成的列表中

def show_completed_models(completed_models)

    print("\nthe following models have been printed ")
    for completed_model in completed_models
        print(completed_model)

unprinted_designs = ['iphone case', 'robot pendant','dodecahedron']
completed_models = []
print_models(unprinted_designs,completed_models)             #[]代表所有的内容
show_completed_models(completed_models)
print('\n')
print(unprinted_designs)

删除[],输出如下,没有打印的东西显示无,说明都打印完了
printing model dodecahedron
printing model robot pendant
printing model iphone case

the following models have been printed 
dodecahedron
robot pendant
iphone case


[]
[Finished in 0.3s]

# 8.4.2 function 2017-6-30 Shenzhen ''

def print_models(unprinted_designs,completed_models)
    """
    模拟打印每个设计,直到没有未打印的为止
    打印每个设计后,都将其移动到列表completed——models中
    """
    while unprinted_designs
        current_design = unprinted_designs.pop()          #把没打印的东西从尾部,一个个弹出来,

        print("printing model " + current_design)
        completed_models.append(current_design)             #把弹出来的东西一个个添加到完成的列表中

def show_completed_models(completed_models)

    print("\nthe following models have been printed ")
    for completed_model in completed_models
        print(completed_model)

unprinted_designs = ['iphone case', 'robot pendant','dodecahedron']
completed_models = []
print_models(unprinted_designs[],completed_models)             #[]代表所有的内容
show_completed_models(completed_models)
print('\n')
print(unprinted_designs)



printing model dodecahedron
printing model robot pendant
printing model iphone case

the following models have been printed 
dodecahedron
robot pendant
iphone case


['iphone case', 'robot pendant', 'dodecahedron']
[Finished in 0.2s]



# 8.4.1 function 2017-6-30 Shenzhen ''

def print_models(unprinted_designs,completed_models)
    """
    模拟打印每个设计,直到没有未打印的为止
    打印每个设计后,都将其移动到列表completed——models中
    """
    while unprinted_designs
        current_design = unprinted_designs.pop()

        print("printing model " + current_design)
        completed_models.append(current_design)

def show_completed_models(completed_models)

    print("\nthe following models have been printed ")
    for completed_model in completed_models
        print(completed_model)

unprinted_designs = ['iphone case', 'robot pendant','dodecahedron']
completed_models = []
print_models(unprinted_designs,completed_models)
show_completed_models(completed_models)

printing model dodecahedron
printing model robot pendant
printing model iphone case

the following models have been printed 
dodecahedron
robot pendant
iphone case
[Finished in 0.2s]


# 8.4.1 function 2017-6-30 Shenzhen ''
unprinted_designs = ['iphone case', 'robot pendant','dodecahedron']
completed_models = []

while unprinted_designs
    current_design = unprinted_designs.pop()         #pop()是弹出列表中最后一个内容

    print("printing model " + current_design)          #pop(0)是弹出第一个元素,而且只能有一个参数
    completed_models.append(current_design)

print("\nthe following models have been printed ")
for completed_model in completed_models
    print(completed_model)

printing model dodecahedron
printing model robot pendant
printing model iphone case

the following models have been printed 
dodecahedron
robot pendant
iphone case


[]
[Finished in 0.2s]

# 8.4 function 2017-6-29 Shenzhen ''
def greet_users(names)
    for name in names
        print('hello '+name)
usernames=['jack','lili','lucy']
greet_users(usernames)

hello jack
hello lili
hello lucy
[Finished in 0.2s]





# 8-8 function 2017-6-29 Shenzhen ''
#this programm has a problem
def make_album(singer_name,singer_album)
    """return singer"""
    name_album=singer_name+ ' ' + singer_album
    
    #if album_number
        #name_album['album_number'] = album_number
    while True
        print('please input the name and the album of singer')
        print('press characterq to quit the program')

        s_name = input(name )
        if s_name == 'q'
            break

        s_album = input(album )
        if s_album == 'q'
            break

    return name_album
album_1 = make_album(s_name, s_album) #this line has a problem
print(album_1)


# 8-7 function 2017-6-29 Shenzhen ''
def make_album(singer_name,singer_album, album_number = '')
    name_album={'name'singer_name,'album'singer_album}
    
    if album_number
        name_album['album_number'] = album_number
    return name_album
album_1 = make_album('sun','nicht')
print(album_1)
album_2 = make_album('zhou','ich')
print(album_2)
album_3 = make_album('liu','wangqingshui','3')
print(album_3)
{'name' 'sun', 'album' 'nicht'}
{'name' 'zhou', 'album' 'ich'}
{'name' 'liu', 'album' 'wangqingshui', 'album_number' '3'}
[Finished in 0.2s]

# 8-7 function 2017-6-29 Shenzhen ''
def make_album(singer_name,singer_album)
    name_album={'name'singer_name,'album'singer_album}
    return name_album
album_1 = make_album('sun','nicht')
print(album_1)
album_2 = make_album('zhou','ich')
print(album_2)
album_3 = make_album('liu','wangqingshui')
print(album_3)

{'name' 'sun', 'album' 'nicht'}
{'name' 'zhou', 'album' 'ich'}
{'name' 'liu', 'album' 'wangqingshui'}
[Finished in 0.2s]



# 8-6 function 2017-6-29 Shenzhen ''
def city_country(city_name,city_country)
    city= city_name + ', ' + city_country
    return city 
city_1= city_country('santiage', 'chile')
print(city_1)
city_2= city_country('beijing', 'china')
print(city_2)
city_3= city_country('berlin', 'germany')
print(city_3)

santiage, chile
beijing, china
berlin, germany
[Finished in 0.2s]



# 8.3.4 function 2017-6-29 Shenzhen ''
#程序设计不合理
def get_formatted_name(first_name,last_name)
    """return tidi name"""
    full_name = last_name +' ' + first_name
    return full_name.upper()

while True
    print('please give me your name')
    print("press 'q' to exit")

    f_name = input("first name\n")
    if f_name == 'q'
        break

    l_name = input("last name\n")
    if l_name == 'q'
        break
        
formatted_name = get_formatted_name(f_name, l_name)
print(formatted_name)


please give me your name
press 'q' to exit
first name
guang
last name
yang
please give me your name
press 'q' to exit
first name
q
YANG Q

***Repl Closed***





# 8.3.3 function 2017-6-29 Shenzhen ''
# use return to give a value to function
def build_person(first_name,last_name)                 
    """return a dictinery, which contain the info of a person"""
    person={'first'first_name,'last'last_name}
    return person                #输出字典
get_returned_value=build_person('guang', 'yang')
print(get_returned_value)

{'first' 'guang', 'last' 'yang'}
[Finished in 0.2s]

# 8.3.2 function 2017-6-29 Shenzhen ''
# use return to give a value to function
def get_formatted_name(first_name,last_name,middle_name='')
    """return tidi name"""
    full_name = last_name +' ' +middle_name+ ' ' + first_name
    return full_name.upper()
person_1 = get_formatted_name('guang','yang')       #程序会自动识别前两位,不用考虑第三个参数
print(person_1)

person_2 = get_formatted_name('guang','yang','wen')
print(person_2)

YANG  GUANG
YANG WEN GUANG
[Finished in 0.3s]

# 8.3.1 function 2017-6-29 Shenzhen ''
# use return to give a value to function
def get_formatted_name(first_name,last_name)
    """return tidi name"""
    full_name = first_name +' ' + last_name
    return full_name.upper()
person = get_formatted_name('guang','yang')
print(person)

GUANG YANG
[Finished in 0.2s]

# 8-5 function 2017-6-29 Shenzhen ''
def describe_city(name,land="china")
    """name of city and city of land"""
    print(name + " is in " + land)
describe_city('beijing')
describe_city(name="shanghai")
describe_city("berlin",land="germany") 

beijing is in china
shanghai is in china
berlin is in germany
[Finished in 0.3s]

# 8-4 function 2017-6-29 Shenzhen ''
def make_shirt(number, words="i love python")
    print("the number of the t-shirt is" + number+ ("\nthe words on the t-shirt are " +words))
make_shirt('35')
make_shirt(number= '45')

make_shirt(number= '65', words='i love you')

the number of the t-shirt is35
the words on the t-shirt are i love python
the number of the t-shirt is45
the words on the t-shirt are i love python
the number of the t-shirt is65
the words on the t-shirt are i love you
[Finished in 0.2s]


# 8-3 function 2017-6-29 Shenzhen ''
def make_shirt(number, words)
    print("the number of the t-shirt is" + number+ ("\nthe words on the t-shirt are " +words))
make_shirt('35','i love you')
make_shirt(number= '35', words='i love you')

# 8.2.3 function 2017-6-29 Shenzhen ''
#defoult value for xing can
def describe_pet(pet_name, animal_type='dog')
    """show the pet info"""
    print("i have a " + animal_type)
    print("my " + animal_type + "'s name is " + pet_name)
describe_pet(pet_name='harry')
describe_pet(pet_name='willie')

i have a dog
my dog's name is willie
i have a dog
my dog's name is willie
i have a hamster
my hamster's name is harry
i have a hamster
my hamster's name is harry
i have a hamster
my hamster's name is harry
[Finished in 0.2s]

# 8.2.2 function 2017-6-29 Shenzhen ''
#key word in function is better
def describe_pet(animal_type,pet_name)
    """show the pet info"""
    print("i have a " + animal_type)
    print("my " + animal_type + "'s name is " + pet_name)
describe_pet(animal_type ='hamster', pet_name='harry')      #参数可以变换位置,如果指定了参数名称
describe_pet(pet_name='willie', animal_type='dog')


i have a hamster
my hamster's name is harry
i have a dog
my dog's name is willie
[Finished in 0.3s]



# 8.2.1 function 2017-6-29 Shenzhen ''
#location sequence is very important
def describe_pet(animal_type,pet_name)
    """show the pet info"""
    print("i have a " + animal_type)
    print("my " + animal_type + "'s name is " + pet_name)
describe_pet('hamster','harry')

i have a hamster
my hamster's name is harry
[Finished in 0.2s]

# 8--1 function 2017-6-29 Shenzhen ''
def display_message()
    print('what i lernt in this chapter is how to use function in programm')
display_message()

what i lernt in this chapter is how to use function in programm
[Finished in 0.2s]


# 8.1.1 function 2017-6-29 Shenzhen ''
#def是函数定义的标志。函数定义由函数名,括号,冒号组成
def greet_user(username)
    #文档字符串的注释,描述函数干嘛用的
    """show simple greeting words"""
    print('hello world '+ username.upper())
#调用函数如下,不用冒号了
greet_user('jack')


# 8.1 function 2017-6-29 Shenzhen ''
#def是函数定义的标志。函数定义由函数名,括号,冒号组成
def greet_user()
    #文档字符串的注释,描述函数干嘛用的
    """show simple greeting words"""
    print('hello world')
#调用函数如下,不用冒号了
greet_user()


response = []
response.append('I')
response.append('like')
response.append('you')
print(response)

['I', 'like', 'you']
[Finished in 0.3s]

# 7-10  2017-6-29 Shenzhen ''
response = []
number = True
while number
    place = input("would you like to visit one place in the world, where would you go?")
    response.append(place)
    repeat = input('if you would like say more places? yes/no')
    if number == 'no'
        number = False
print(response)


# 7-9  2017-6-29 Shenzhen ''
sandwich_orders=['dog' , 'pastrami', 'hot', 'pastrami', 'cat', 'pastrami', 'snack']
print(sandwich_orders)

print("the pastrami is finished in our shop, sorry")
while 'pastrami' in sandwich_orders
    sandwich_orders.remove('pastrami')
    print(sandwich_orders)
#for sandwich_order in sandwich_orders
    #print(sandwich_order)
['dog', 'pastrami', 'hot', 'pastrami', 'cat', 'pastrami', 'snack']
the pastrami is finished in our shop, sorry
['dog', 'hot', 'pastrami', 'cat', 'pastrami', 'snack']
['dog', 'hot', 'cat', 'pastrami', 'snack']
['dog', 'hot', 'cat', 'snack']
[Finished in 0.2s]


# 7-8  2017-6-29 Shenzhen ''
sandwich_orders=['dog' , 'hot', 'cat']
finished_sandwiches = []
while sandwich_orders
    current_order = sandwich_orders.pop()
    print("i made your " + current_order.upper() + " sandwich")
    #finished_sandwiches = sandwich_order
    finished_sandwiches.append(current_order)
print("the sandwiches are in the following ")
for finished_sandwich in finished_sandwiches
    print(finished_sandwich)

i made your CAT sandwich
i made your HOT sandwich
i made your DOG sandwich
the sandwiches are in the following 
cat
hot
dog
[Finished in 0.2s]





# 7-8  2017-6-29 Shenzhen ''
sandwich_orders=['dog' , 'hot', 'cat']
finished_sandwiches = []
for sandwich_order in sandwich_orders
    print("i made your " + sandwich_order + " sandwich")
    #finished_sandwiches = sandwich_order
    finished_sandwiches.append(sandwich_order)          #append()函数是添加的意思
print("the sandwiches are in the following ")
for finished_sandwich in finished_sandwiches
    print(finished_sandwich)

    i made your dog sandwich
i made your hot sandwich
i made your cat sandwich
the sandwiches are in the following 
dog
hot
cat
[Finished in 0.2s]

#!/usr/bin/env python
# -*- codingutf-8 -*-
'''
 * @Author      Guang_Yang 
 * @DateTime    2017-07-30 113757
 * @Place       Shenzhen, China
 * @Description 7-3 判断不同年龄观众的电影票价格
'''
age = 1
while age != 0
    age = int(input("how old are you?   "))
    if age>0 and age<3
        print("the ticket price is free")
        
    elif age>=3 and age<=12
        print("the ticket price is 10 $")
        
    elif age>12
        print("the ticket price is 15 $")


how old are you?6
the ticket price is 10 $
how old are you?3
the ticket price is 10 $
how old are you?1
the ticket price is free
how old are you?0
the ticket price is free

***Repl Closed*** 


#7.3.3 while 2017.6.29
responses = {}
#设置一个标志,指出调查是否继续
polling_active = True
while polling_active
    #提示输入被调查者的名字和回答
    name = input("\nwhat is your name?")
    response = input("\nwhich mountain would you like to climb someday?")
    #把答卷存储在字典中
    responses[name] = response
    #看看是否还有人要接受调查
    repeat = input("would you like to let another people respond?让其他人也做反馈?yes or no\n")
    if repeat == 'yes'
        polling_active = True
    else
        polling_active = False
#调查结束,显示结果
print("\n--- Poll Result ---")
for name,response in responses.items()
    print(name + " would like to climb " + response + '.')


what is your name?guang

which mountain would you like to climb someday?华山
would you like to let another people respond?让其他人也做反馈?yes or no
不了

--- Poll Result ---
guang would like to climb 华山.

***Repl Closed***



#7.3.2 while 2017.6.28 
pets=['cat','dog','monkey','cat','dog']
print(pets)
while 'cat' in pets 
    current_pets = pets.remove('cat')       #remove()里面只能放字符串,pop()里面只能放数字
print(pets)
print(current_pets)


['cat', 'dog', 'monkey', 'cat', 'dog']
['dog', 'monkey', 'dog']
None
[Finished in 0.3s]


#7.3.1 while 2017.6.28 
#首先创建一个待验证的用户列表
#再创建一个已经验证过的空列表
unconfirmed_users=['alice','brian','candace']
confirmed_users = []
#验证每个用户,直到没有未验证用户为止
#将每个经过验证的列表都移动到已经验证过的列表中
while unconfirmed_users
    current_users = unconfirmed_users.pop()
    print("verifying users " + current_users)
    confirmed_users.append(current_users)

#显示所有已经验证的用户名单
print("the following users have been confirmed ")
for confirmed_user in confirmed_users
    print(confirmed_user)

verifying users candace
verifying users brian
verifying users alice
the following users have been confirmed 
candace
brian
alice
[Finished in 0.2s]

#7.2.5 while 2017.6.28 
current_number = 0
while current_number < 10
    current_number += 1
    if current_number % 2 ==0
        continue
    else
        print(current_number)

1
3
5
7
9
[Finished in 0.2s]
#7.2.3 while 2017.6.28 
prompt = "enter the name of cities you have visited"
prompt += "(enter 'quit' when you are finished.)\n"
#prompt太长了,分了2行输入
while True
    city = input(prompt)

    if city == 'quit'
        break
    else
        print("i would love to go to " + city.title())

   


#7.2.3 while 2017.6.28 
prompt = "\n enter 'quit' to end the program."
active = True
while active
    message = input(prompt)

    if message == 'quit'
        active = Fals
    else
        print(message)

#7.2.2 while 2017.6.28 
prompt = "\n enter 'quit' to end the program.\n"
message = ''
while message != 'quit'
    message = input(prompt)
    print(message)


#7.2.1 while 2017.6.28 
current_number = 1
while current_number <= 5
    print(current_number)
    current_number += 1

1
2
3
4
5
[Finished in 0.3s]

# 7-3 
num = input("please input a number")
num = int(num)
if num % 10 == 0
    print("the number can be divided by 10")
else
    print("the number can not be divided by 10")

#7-2 2017.6.28
num = input("how many people for dinner?")
num = int(num)
if num > 8
    print("there is no available table")
else
    print("there is table")


#7-1 2017.6.28 
car = input("what kind of car do you want to rent? ")
#input let me see if  i can find you a subaru


#7.1.3 rollercoaster.py 2017.6.28
number = input("tell me a number and i will tell you if it is even or odd ")
number = int(number)
if number % 2 == 0
    print("the number " + str(number) + " is a even")
else
    print("the number " + str(number) + " is a odd")


#7.1.2 rollercoaster.py 2017.6.28
height = input("how tall are you, in inch? ")
height = int(height)
if height > 36
    print(" you are tall engough to ride! ")
else
    print("\nyou will be able to ride when you are a little older")

#7.1.1  2017.6.28
prompt = "if you tell us who you are, we can personalize the messages you see."
prompt += "\n what is your first name?"
name = input(prompt)
print("\n hello, " + name)


#7.1.1 
name = input("please input your name ")
print("hello, " + name)


# 7.1 2016.6.28 input
message=input("tell me something and i will repeat it")
print(message)



#6-11  2017.6.28 am Mittwoch
cities={
    'beijing'{
    'country''china',
    'population''2000 0000',
    'fact''main city'
    },
    'berlin'{
    'country''Germany',
    'population''300 0000',
    'fact''main city'
    },
    'shenzhen'{
    'country''china',
    'population''1500 0000',
    'fact''new city'
    }
}
for city, info in cities.items()
    print(city + "'s info ")
    for key,value in info.items()
        print(key + " " + value)
    print('\n')


beijing's info 
country china
population 2000 0000
fact main city


berlin's info 
country Germany
population 300 0000
fact main city


shenzhen's info 
country china
population 1500 0000
fact new city


[Finished in 0.3s]


#6-10
faverate_numbers={
    'jack'['1','3','6'],'mike'['2','6','8'],'tom'['3','8','9'],'lili'['8','6','4'],'lucy'['5','4','6']}
for names,numbers in faverate_numbers.items()
    print(names + "'s favorite number is ")
    for number in numbers
        print(number)

jack's favorite number is 
1
3
6
mike's favorite number is 
2
6
8
tom's favorite number is 
3
8
9
lili's favorite number is 
8
6
4
lucy's favorite number is 
5
4
6
[Finished in 0.3s]


#6-9
favorite_places={
    'yang'['hangzhou','beijing','shenzhen'],
    'guang'['guizhou','cottbus','berlin'],
    'hi'['shanxi','frankfurt','munich']
}
for name, places in favorite_places.items()
    print(name+"'s favorite places are ")
    for place in places
        print(place)

yang's favorite places are 
hangzhou
beijing
shenzhen
guang's favorite places are 
guizhou
cottbus
berlin
hi's favorite places are 
shanxi
frankfurt
munich
[Finished in 0.5s]



#6-8
dog={'type''doubi','master''yang'}
cat={'type''taidi','master''guang'}
tiger = {'type''big','master''zoo'}
pets = [dog, cat, tiger]
for pet in pets
    print(pet)

{'type' 'doubi', 'master' 'yang'}
{'type' 'taidi', 'master' 'guang'}
{'type' 'big', 'master' 'zoo'}
[Finished in 0.2s]


#6-7 
peoples_1={'first_name''guang','last_name''yang','age''29','city''Shenzhen'}
peoples_2 = {'first_name''hao','last_name''wang','age''20','city''beijing'}
peoples_3 = {'first_name''ming','last_name''yao','age''35','city''shagnhai'}
peoples = [peoples_1, peoples_2, peoples_3]
for people in peoples
    print(people)

{'first_name' 'guang', 'last_name' 'yang', 'age' '29', 'city' 'Shenzhen'}
{'first_name' 'hao', 'last_name' 'wang', 'age' '20', 'city' 'beijing'}
{'first_name' 'ming', 'last_name' 'yao', 'age' '35', 'city' 'shagnhai'}
[Finished in 0.2s]

#6.4.3  many_users.py  2017.6.27
users={
    'aeinstein'{
    'first''albert',
    'last''einstein',
    'location''princeton'
    },

    'mcurie'{
    'first''marie',
    'last''curie',
    'location''paris'
    }
}               #users字典里面值可以是个字典。只有2个对,但是值里有好多对
for user,user_info in users.items()
    print("username "+user)
    full_name=user_info['first']+' '+user_info['last']
    location=user_info['location']              #userinfo就代表了user值的信息,通过调用location就可以获取location对应的值
    print("Full name "+full_name)
    print("location "+location)

username aeinstein
Full name albert einstein
location princeton
username mcurie
Full name marie curie
location paris
[Finished in 0.2s]


#6.4.2  favorite_languages.py  2017.6.27
favorite_languages={
    'jen'['python','ruby'],
    'sarah'['C'],
    'edward'['ruby','go'],
    'phil'['python','haskell']
}
for name,languages in favorite_languages.items()
    if len(languages) > 1

        print(name+"'s favorite languages are ")
        for language in languages
            print(language.title())
    else
        print(name+"'s favorite language is ")
        for language in languages
            print(language.title())


jen's favorite languages are 
Python
Ruby
sarah's favorite language is 
C
edward's favorite languages are 
Ruby
Go
phil's favorite languages are 
Python
Haskell
[Finished in 0.2s]





#6.4.2  favorite_languages.py  2017.6.27
favorite_languages={
    'jen'['python','ruby'],
    'sarah'['C','C++'],
    'edward'['ruby','go'],
    'phil'['python','haskell']
}
for name,languages in favorite_languages.items()
    print(name+"'s favorite languages are ")
    for language in languages
        print(language.title())

jen's favorite languages are 
Python
Ruby
sarah's favorite languages are 
C
C++
edward's favorite languages are 
Ruby
Go
phil's favorite languages are 
Python
Haskell
[Finished in 0.3s]

#6.4.2    2017.6.27
pizza={
    'crust''thick',
    'toppings'['mushrooms','extra cheese'],

}           #字典里面的值可以是列表
print("you ordered a "+pizza['crust']+'-crust pizza '+
    "with the following toppings ")
for topping in pizza['toppings']
    print(topping)                                       

you ordered a thick-crust pizza with the following toppings 
mushrooms
extra cheese
[Finished in 0.2s]



#6.4.1
aliens = [] #创建一个存储太空人的列表
#创建30个绿色外星人
for alien_number in range(30)
    #print(alien_number)
    new_alien={'color''green','points''5','speed''slow'}
    aliens.append(new_alien)  #

#显示 前面5个外星人
for alien in aliens[05]
    print(alien)
print('...')
#显示创建了多少个外星人
print("total number of aliens "+str(len(aliens)))

{'color' 'green', 'points' '5', 'speed' 'slow'}
{'color' 'green', 'points' '5', 'speed' 'slow'}
{'color' 'green', 'points' '5', 'speed' 'slow'}
{'color' 'green', 'points' '5', 'speed' 'slow'}
{'color' 'green', 'points' '5', 'speed' 'slow'}
...
total number of aliens 30
[Finished in 0.2s]



#6.4.1
alien_0={'color''green','points''5'}
alien_1={'color''yellow','points''10'}
alien_2={'color''red','points''15'}
aliens = [alien_0,alien_1, alien_2]             #aliens是一个字典列表,也就是,每个元素都是字典
for alien in aliens
    print(alien)

{'color' 'green', 'points' '5'}
{'color' 'yellow', 'points' '10'}
{'color' 'red', 'points' '15'}
[Finished in 0.3s]


#6-6
peoples={'first_name''guang','last_name''yang','age''29','city''Shenzhen'}
for key,value in peoples.items()
    print(key+' '+value)
infors=['first_name','age','dog','cat']
for infor in infors
    if infor in peoples.keys()
        print('thank you')
    else
        print('please come here')

first_name guang
last_name yang
age 29
city Shenzhen
thank you
thank you
please come here
please come here
[Finished in 0.3s]

#6-5
rivers={'nile''egypt','jazi''china','duonao''german'}
for river, land in rivers.items()
    print(river+ " run through "+land)
for river in rivers.keys()
    print(river)
for land in rivers.values()
    print(land)
        
nile run through egypt
jazi run through china
duonao run through german
nile
jazi
duonao
egypt
china
german
[Finished in 0.3s]


#6-4
faverate_numbers={'jack''1','mike''2','tom''3','lili''4','lucy''5'}
for name,number in faverate_numbers.items()        #keys,values只能取一个内容,items()可以取2个内容
    print(name+'   like number '+number)
print('\n')
faverate_numbers['martin']='6'
faverate_numbers['alix']='7'
faverate_numbers['johanes']='8'
faverate_numbers['andre']='9'
faverate_numbers['dirk']='10'
for name,number in faverate_numbers.items()
    print(name+'   like number '+number)


jack   like number 1
mike   like number 2
tom   like number 3
lili   like number 4
lucy   like number 5


jack   like number 1
mike   like number 2
tom   like number 3
lili   like number 4
lucy   like number 5
martin   like number 6
johanes   like number 8
alix   like number 7
andre   like number 9
dirk   like number 10
[Finished in 0.2s]


#6.3.4 output with sequence
peoples={'first_name''guang','last_name''yang','age''29','city''Shenzhen'}
for data in set(peoples.values())          #set主要是消除重复元素
    print(data.title())


Shenzhen
Yang
29
Guang
[Finished in 0.3s]


#6.3.3 output with sequence
peoples={'first_name''guang','last_name''yang','age''29','city''Shenzhen'}
for data in sorted(peoples.keys())         #sorted()把要输出的内容按照顺序输出
    print(data.title())

Age
City
First_Name
Last_Name
[Finished in 0.3s]

#6.3.2
peoples={'first_name''guang','last_name''yang','age''29','city''Shenzhen'}
datas=['age','city']
for people in peoples.keys()
    print(people)
    if people in datas
        print(people+" information is "+peoples[people])
    elif 'dog' not in peoples
        print('dog please take out our poll')


first_name
dog please take out our poll
last_name
dog please take out our poll
age
age information is 29
city
city information is Shenzhen
[Finished in 0.3s]

#6.3.2
peoples={'first_name''guang','last_name''yang','age''29','city''Shenzhen'}
datas=['age','city']
for people in peoples.keys()
    print(people)
    if people in datas
        print(people+" information is "+peoples[people])

first_name
last_name
age
age information is 29
city
city information is Shenzhen
[Finished in 0.3s]
#6.3.2
peoples={'first_name''guang','last_name''yang','age''29','city''Shenzhen'}
for people in peoples.values()       #这种只有一个参数的情况并且指明输出values()的值,只会输出value的数据
    print(people)

guang
yang
29
Shenzhen
[Finished in 0.3s]


#6.3.2
peoples={'first_name''guang','last_name''yang','age''29','city''Shenzhen'}
for people in peoples.keys()       #这种只有一个参数的情况并且指明输出keys的值,只会输出键key的数据
    print(people)

first_name
last_name
age
city
[Finished in 0.3s]


#6.3.2
peoples={'first_name''guang','last_name''yang','age''29','city''Shenzhen'}
for people in peoples              #这种只有一个参数的情况,默认输出键key的数据
    print(people)

first_name
last_name
age
city
[Finished in 0.3s]


#6.3.1 
peoples={'first_name''guang','last_name''yang','age''29','city''Shenzhen'}
print('first_name '+peoples['first_name'])
print('last_name '+peoples['last_name'])
print('age '+str(peoples['age']))
print('city '+peoples['city'])
print('\n')
for key,value in peoples.items()
    print('\n'+key+' '+value)

first_name guang
last_name yang
age 29
city Shenzhen



first_name guang

last_name yang

age 29

city Shenzhen
[Finished in 0.3s]

#6-2
faverate_numbers={'jack''1','mike''2','tom''3','lili''4','lucy''5'}
print('jack like number '+faverate_numbers['jack'])
print('mike like number '+faverate_numbers['mike'])
print('tom like number '+faverate_numbers['tom'])
print('lili like number '+faverate_numbers['lili'])
print('lucy like number '+faverate_numbers['lucy'])


jack like number 1
mike like number 2
tom like number 3
lili like number 4
lucy like number 5
[Finished in 0.3s]

#6-1#字典包含键和值组成的对(keyvalue)
peoples={'first_name''guang','last_name''yang','age''29','city''Shenzhen'}
print('first_name '+peoples['first_name'])         #取值,可以通过字典名调用相应的键
print('last_name '+peoples['last_name'])
print('age '+str(peoples['age']))
print('city '+peoples['city'])


first_name guang
last_name yang
age 29
city Shenzhen
[Finished in 0.3s]


#5-11
datas=[1,2,3,4,5,6,7,8,9]
for data in datas
    if data==1
        print('1st')
    elif data==2
        print('2nd')
    elif data==3
        print('3rd')
    else
        print(str(data)+"th")

1st
2nd
3rd
4th
5th
6th
7th
8th
9th
[Finished in 0.3s]

#5-10
current_users=['lili','admin','lucy','lilei','Mike']
new_users=['Lucy','martin','lukas','MIKE','andre']
for new_user in new_users
    #for current_user in current_users
    if new_user.lower() or new_user.title() or new_user.upper() in current_users
        print(new_user+' you need another name for the account')
    else
        print(new_user +' congratulations! you name can be used')

Lucy you need another name for the account
martin you need another name for the account
lukas you need another name for the account
MIKE you need another name for the account
andre you need another name for the account
[Finished in 0.3s]

#5-10
current_users=['lili','admin','lucy','lilei','mike']
new_users=['lucy','martin','lukas','mike','andre']
for new_user in new_users
    if new_user in current_users
        print(new_user+' you need another name for the account')
    else
        print(new_user +' congratulations! you name can be used')

lucy you need another name for the account
martin congratulations! you name can be used
lukas congratulations! you name can be used
mike you need another name for the account
andre congratulations! you name can be used
[Finished in 0.3s]

#5-9
peoples=['lili','admin','lucy','lilei','mike']
if peoples
    for people in peoples
        if people=='admin'
            print('hello '+people+', would you like to see a status report?')
        else
            print('hello! '+people+', thank you for logging in again')
else
    print('we need to find some users!')
for people in peoples
    del people
print('we need to find some users!')


hello! lili, thank you for logging in again
hello admin, would you like to see a status report?
hello! lucy, thank you for logging in again
hello! lilei, thank you for logging in again
hello! mike, thank you for logging in again
we need to find some users!
[Finished in 0.3s]


#5-8 
peoples=['lili','admin','lucy','lilei','mike'] #peoples是列表
for people in peoples
    if people=='admin'
        print('hello '+people+', would you like to see a status report?')
    else
        print('hello! '+people+', thank you for logging in again')

hello! lili, thank you for logging in again
hello admin, would you like to see a status report?
hello! lucy, thank you for logging in again
hello! lilei, thank you for logging in again
hello! mike, thank you for logging in again
[Finished in 0.3s]

#5.4.3
animals_zoo=['dog','people','monkey','cat','snack','elephent']
animals_home=['dog','cat','tiger']
for animal_home in animals_home
    if animal_home in animals_zoo
        print(animal_home+" belongs to zoo")
    else
        print("the zoo has not "+ animal_home)
print("the zoo is at the end")


dog belongs to zoo
cat belongs to zoo
the zoo has not tiger
the zoo is at the end
[Finished in 0.3s]


#5.4.2
animals=['dog','people','monkey']
if animals

    for animal in animals
        print(animal)
        if animal=='people'

            print(animal+" doesn't not belong to animals")
        else
            print(animal +" belongs to animals")
else

    print('there is no animals')

dog
dog belongs to animals
people
people doesn't not belong to animals
monkey
monkey belongs to animals
[Finished in 0.3s]

#5-6
age=30
if age<2
    print('you are a baby')
elif age>=2 and age<4
    print('you are learning walking')
elif age>=4 and age<13
    print('you are a child')
elif (age>=13 and age<20)
    print('you are a teenage')
elif age>=20 and age<65
    print('you are an adult')
else
    print('you are and old man')

False
False
True
False
a<b and b<c
a>b or b<c
a>=b or b>c or c>=d
[Finished in 0.3s]

#5-2
a=19
b=29
c=39
d=29
print(a==b)
print(a==d)
print(a<b)
print(a>b)
if a>b and b>c
    print("a>b and b>c")
else
    print("a<b and b<c")
if a>b or b<c
    print("a>b or b<c")
else
    print("a<b or b>c")
if a>=b or b>c or c>=d
    print("a>=b or b>c or c>=d")
else
    print("a<b or b<c or c>d")

#5-2
a='lili'
b='Lili'
print(a==b.lower())
print(a!=b)
if a==b
    print("a==b")
else
    print("a!=b")

True
True
a!=b
[Finished in 0.3s]


#5-1 
name="lili"
print("is name =='lili'? I predict True")
print(name=='lili')
print("is name =='lucy'? I predict False.")
print(name=='lucy')
print("is name =='dog'? I predict False.")


is name =='lili'? I predict True
True
is name =='lucy'? I predict False.
False
is name =='dog'? I predict False.
[Finished in 0.3s]

#5-5
alien_color=['green','yellow','red']
if 'green' in alien_color
    print("you get 5 points in this game")
elif 'yellow' in alien_color
    print("you get 10 points in this game")

elif 'red' in alien_color
    print("you get 15 points in this game")

you get 5 points in this game
[Finished in 0.3s]

#5-4
alien_color=['green','yellow','red']
if 'black' in alien_color
    print("you get 5 points in this game")
else
    print("you get 10 points in this game")
if 'red' in alien_color
    print("you get 5 points in this game")

you get 10 points in this game
you get 5 points in this game
[Finished in 0.3s]


#5-3 
alien_color=['green','yellow','red']
if 'green' in alien_color
    print("you get 5 points in this game")
if 'black' in alien_color
    print()

you get 5 points in this game
[Finished in 0.3s]

#5.3.3  str(ticket) easy to wrong
age=30
if age<4
    ticket=0
elif age<18
    ticket=5
elif age<60
    ticket=10
else
    ticket=5
print("your admission cost is "+str(ticket))


your admission cost is 10
[Finished in 0.3s]

#5-2

animals=['dog','cat','tiger']
animal='cat'
if animal not in animals
    print(animal+" doesn't belong to animals")
else
    print(animal+" does belong to animals")
if animal in animals
    print(animal+" does belong to animals")
else
    print(animal+" doesn't belong to animals")

#5.2.6  in 
animals=['dog','cat','tiger']
animal='dog'
if animal not in animals
    print(animal+", you can post a response if you wish")
else
    print(animal in animals)

True
[Finished in 0.3s]

#5.2.6  in 
animals=['dog','cat','tiger']
a='dog' in animals
print(a)

True
[Finished in 0.3s]

#5.1 if loop
cars=['audi','bmw','subaru','toyota']
for car in cars
    if car=='bmw'
        print(car.upper())
    else
            print(car.title())

Audi
BMW
Subaru
Toyota
[Finished in 0.3s]


#4-13
foods=('dog','cat','hund','snack','monkey')
for food in foods
	print(food)
#foods(0)='pig'
foods=('dog','cat','hund','tv','apple')
for food in foods
	print(food)


dog
cat
hund
snack
monkey
dog
cat
hund
tv
apple
[Finished in 0.3s]

#4-11
players=['charles','martina','michael','florence','eli']
player=players[]
print(player)
players.append('good')
player.append('very good')
print('the members in players are ')
for play_1 in players
	print(play_1)
print('the members in player are ')
for play_2 in player
	print(play_2)


['charles', 'martina', 'michael', 'florence', 'eli']
the members in players are 
charles
martina
michael
florence
eli
good
the members in player are 
charles
martina
michael
florence
eli
very good
[Finished in 0.2s]

#4-10
players=['charles', 'martina', 'michael', 'florence', 'eli', 'good', 'very good']
print('The first three items in the list are ')
print(players[03])
print('Three items from the middle of the list are ')
print(players[2-2])
print('the last three items in the list are ')
print(players[-3])

The first three items in the list are 
['charles', 'martina', 'michael']
Three items from the middle of the list are 
['michael', 'florence', 'eli']
the last three items in the list are 
['eli', 'good', 'very good']


"#!/usr/bin/env python""\n"
"# -*- codingutf-8 -*-""\n"
players=['charles','martina','michael','florence','eli']
player=players[]
print(player)
players.append('good')
print(players)

player.append('very good')
print(player)

['charles', 'martina', 'michael', 'florence', 'eli']
['charles', 'martina', 'michael', 'florence', 'eli', 'good']
['charles', 'martina', 'michael', 'florence', 'eli', 'very good']

"#!/usr/bin/env python""\n"
"# -*- codingutf-8 -*-""\n"

players=['charles','martina','michael','florence','eli']
player=players
print(player)
players.append('good')
print(players)

player.append('very good')
print(player)

['charles', 'martina', 'michael', 'florence', 'eli']
['charles', 'martina', 'michael', 'florence', 'eli', 'good']
['charles', 'martina', 'michael', 'florence', 'eli', 'good', 'very good']

"#!/usr/bin/env python""\n"
"# -*- codingutf-8 -*-""\n"

players=['charles','martina','michael','florence','eli']
player=players[]
print(player)

['charles', 'martina', 'michael', 'florence', 'eli']
[Finished in 0.3s]

"#!/usr/bin/env python""\n"
"# -*- codingutf-8 -*-""\n"

players=['charles','martina','michael','florence','eli']
for player in players[03]
	print(player)

charles
martina
michael


"#!/usr/bin/env python""\n"
"# -*- codingutf-8 -*-""\n"

values=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
print(values[38])

[4, 5, 6, 7, 8]
[Finished in 0.3s]


#4-9
values=[value**3 for value in range(1,11)]
print(values)

[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
[Finished in 0.3s]

#4-8
values=[]
for value in range(1,11)
	values.append(value**3)
print(values)

[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
[Finished in 0.3s]

#4-7
values=list(range(3,30,3))
for value in values
	print(value)

3
6
9
12
15
18
21
24
27
[Finished in 0.5s]

"#!/usr/bin/env python""\n"
"# -*- codingutf-8 -*-""\n"

#4-6
odds=list(range(1,20,2))
print(odds)
for odd in odds
    print(odd)
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
1
3
5
7
9
11
13
15
17
19
[Finished in 0.3s]


"#!/usr/bin/env python""\n"
"# -*- codingutf-8 -*-""\n"
#4-5

numbers=list(range(1,1000001))
print(min(numbers))
print(max(numbers))
print(sum(numbers))

"#!/usr/bin/env python""\n"
"# -*- codingutf-8 -*-""\n"
#4-4
for value in range(1,101)
	print(value)

"#!/usr/bin/env python""\n"
"# -*- codingutf-8 -*-""\n"
# 4-3
values=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
for value in values
	print(value)

"#!/usr/bin/env python""\n"
"# -*- codingutf-8 -*-""\n"

squares=[values**2 for values in range(1,11)]
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

"#!/usr/bin/env python""\n"
"# -*- codingutf-8 -*-""\n"
digits=[1,2,3,4,5,6,7,8,9,0]
print(min(digits))
print(max(digits))
print(sum(digits))
0
9
45

"#!/usr/bin/env python""\n"
"# -*- codingutf-8 -*-""\n"
squares=[]
for value in range(1,11)
	square=value**2                      #**2代表平方,**3代表立方
	squares.append(square)             #append()添加元素到列表末尾

print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]




"#!/usr/bin/env python""\n"
"# -*- codingutf-8 -*-""\n"
even_numbers=list(range(2,12,2))            #打印2到12之间的数字,并且间隔为2
print(even_numbers)
[2, 4, 6, 8, 10]
[Finished in 0.5s]


"#!/usr/bin/env python""\n"
"# -*- codingutf-8 -*-""\n"

for value in range(1,5)                    #range(1,5)表示一个1到5之间的列表,包含1,不包含5
	print(value)                            #依次打印列表中的每个元素,并且自带回车

numbers=list(range(1,5))                    #list(range(1,5))表示一个1到5之间的列表
print(numbers)                              #把列表原样输出

"#!/usr/bin/env python""\n"
"# -*- codingutf-8 -*-""\n"
#4-2
animals=['dog','cat','monkey']
for animal in animals
	print("A "+animal+ " would make a great pet")
print("Any of these animals would make a great pet!")


"#!/usr/bin/env python""\n"
"# -*- codingutf-8 -*-""\n"
#4-1 
pizzas=['dog','cat','monkey']
for pizza in pizzas
	print(pizza+" I like pepperoni pizza")
print("I really love pizza")

"#!/usr/bin/env python""\n"
"# -*- codingutf-8 -*-""\n"

magicians=['alice','david','carolina']#列表内容一般大于一个,所以实例都用复数
for magician in magicians
    print(magician.title()+", that was a great trick!")			
    #print前面一定要有空格,为啥?for循环后面加了分号,回车后自动缩进4个字符
    print("I can't wait to see your next trick, "+magician.upper())
print('Thank you, everyone. That was a great magic show')
#最后的输出没有缩进4个字符,所以不受for循环的控制。python就是靠缩进来控制循环

Alice, that was a great trick!
I can't wait to see your next trick, ALICE
David, that was a great trick!
I can't wait to see your next trick, DAVID
Carolina, that was a great trick!
I can't wait to see your next trick, CAROLINA
Thank you, everyone. That was a great magic show
[Finished in 0.3s]



#4.5.3      修改元组变量
#虽然不可以修改元组元素,但是可以给元组变量赋值,达到重新定义整个元组的效果
dimensions = (200, 50)
for dimension in dimensions
    print(dimension)

dimensions = (400, 200)
for dimension in dimensions
    print(dimension)

200
50
400
200
[Finished in 0.6s]

#4.5.2 遍历元组中的所有值
dimensions = (200, 50)
for dimension in dimensions
    print(dimension)


200
50
[Finished in 0.5s]

#4.5 元组
'''
元组是一列不可以修改的元素,用小括号包起来的;列表是可以修改的,用中括号包起来的一系列元素的集合
'''
dimensions = (200, 50)
print(dimensions[0])
print(dimensions[1])

200
50
[Finished in 1.0s]

# 4.3.3 复制列表
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[]
print('my favorite foods are')
print(my_foods)
print('\nmy friend favorite foods are')
print(friend_foods)

my favorite foods are
['pizza', 'falafel', 'carrot cake']

my friend favorite foods are
['pizza', 'falafel', 'carrot cake']
[Finished in 0.3s]

#4.2.2 遍历切片
#列表的一部分叫做切片
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print("here are the first three players on my team")
for player in players[3]
    print(player)
print(players[3])

here are the first three players on my team 
charles
martina
michael
['charles', 'martina', 'michael']
[Finished in 0.3s]

#4.3.4 列表解析   把for循环和创建新元素的代码合并成一行,并自动附加新元素
squares = [value**2 for value in range(1,11)]
print(squares)

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[Finished in 0.5s]


#4.3.3对数字列表执行简单统计计算
digits = [1, 3, 2, 5, 7, 22, 0, -1, 99]
print(min(digits))
print(max(digits))
print(sum(digits))


-1
99
138
[Finished in 0.4s]


#4.3.2 函数list()把range()的结果直接转换为列表
numbers = list(range(1,6))          #range(1,6)作为list()的参数
print(numbers)
even_numbers = list(range(2,11,2))      #起始数字为2,终点数字为10,间隔为2的列表
print(even_numbers)
squares = []
for value in range(1,11)
    square = value**2
    squares.append(square)
print(squares)


[1, 2, 3, 4, 5]
[2, 4, 6, 8, 10]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[Finished in 0.6s]



#4.3.1 函数range()的使用,只会生成开始到末尾的数字,但是包含第一个数字,不包含最后一个数字
for value in range(1,5)
    print(value)
values = range(1,5)     #range本身不是列表
print(values)

1
2
3
4
range(1, 5)
[Finished in 0.8s]


#4.2.5 遗漏了冒号,for语句末尾的冒号告诉python,下一行是循环的第一行
magicians = ['alice', 'david', 'carolina']
for magician in magicians
    print(magician)

    for magician in magicians
                            ^
SyntaxError invalid syntax无效的语法,提示问题出现在哪里

#4.2.4 循环后不必要的缩进        print("Thank you everyone, that was a great magic show!")
magicians = ['alice', 'david', 'carolina']
for magician in magicians
    print(magician.title() + ", that was a great trick!")
    print("I can't wait to see your next trick, " + magician.title() + ".\n")
    print("Thank you everyone, that was a great magic show!")

Alice, that was a great trick!
I can't wait to see your next trick, Alice.

Thank you everyone, that was a great magic show!
David, that was a great trick!
I can't wait to see your next trick, David.

Thank you everyone, that was a great magic show!
Carolina, that was a great trick!
I can't wait to see your next trick, Carolina.

Thank you everyone, that was a great magic show!
[Finished in 0.4s]

# 4.2.3 不必要的缩进也会有问题
message = "hello python world"
    print(message)

    print(message)
    ^
IndentationError unexpected indent缩进错误,没有期望的缩进

#4.2.2 忘记缩进额外的代码行
magicians = ['alice', 'david', 'carolina']
for magician in magicians
    print(magician.title() + ", that was a great trick!")
print("I can't wait to see your next trick, " + magician.title() + ".\n")

Alice, that was a great trick!
David, that was a great trick!
Carolina, that was a great trick!
I can't wait to see your next trick, Carolina.

# 4.2.1 忘记缩进,造成错误
magicians = ['alice', 'david', 'carolina']
for magician in magicians
print(magician)

    print(magician)
        ^
IndentationError expected an indented block 缩进错误:期望有一个缩进模块。
[Finished in 0.4s]
#4.1.2 在for 循环中执行更多的东西
magicians = ['alice', 'david', 'carolina']
for magician in magicians
    print(magician.title() + ", that was a great trick!")

Alice, that was a great trick!
David, that was a great trick!
Carolina, that was a great trick!
[Finished in 0.3s]

#4.1 遍历整个列表
magicians = ['alice', 'david', 'carolina']
for magician in magicians
    print(magician)

alice
david
carolina
[Finished in 0.8s]

"#!/usr/bin/env python""\n"
"# -*- codingutf-8 -*-""\n"

cars=['bmw','audi','toyota','subaru']
print(cars)
cars.sort()                             #按照字母表给元素排序sort()  
print(cars)
cars.sort(reverse=True)                 #按照字母表的反顺序给元素排序sort() 
print(cars)
#cars.sort()
print("here is the original list")
print(cars)
print("here is the sorted list")
print(sorted(cars))
print("here is the original list")
print(cars)                                 #按字母排序是永久性的
cars=['bmw','audi','toyota','subaru']
print(cars)
cars.reverse()                              #把列表内容首尾调换位置
print(cars)
len(cars)                                   #计算列表长度
print(len(cars))

"#!/usr/bin/env python""\n"
"# -*- codingutf-8 -*-""\n"
"""
#3-7 缩减名单; 你发现新购买的餐桌无法及时到达,因此只能邀请两位。
#1 以3-6程序为基础,在程序末尾添加一行代码,打印你只能邀请两位参加晚宴的消息
#2 使用pop不断删除嘉宾,直到只有2个嘉宾为止。每次从名单中删除嘉宾时候,打印消息,给嘉宾道歉
# 3 给余下的两人发送消息,指出他们两人依然被邀请
# 4 使用delete删除最后两位嘉宾,让名单变成空的。打印该名单,确认名单是空的
"""
friends=['tom','jack','mike']
message='\nWould you like to have supper with me? \n'
print(message+friends[0])
print(message+friends[1])
print(message+friends[-1])
print(friends[0]+" will can't come tonight")
friends[0]='lili'
print(message+friends[0])
print(message+friends[1])
print(message+friends[-1])
print("i find a more table for us")
friends.insert(0,'lucy')
friends.insert(2,'sara')
friends.append('charli')
print(message+friends[0]+message+friends[1]+message+friends[2]+message+friends[3]+message+friends[4]+message+friends[-1])
print(friends)
print("I am sorry to imform you that the new table can't arrival in time, so only two friends can enjoy dinner with me")
poped_friend_1=friends.pop()
message_1='\ni am sorry, i have no space for more people'
print(poped_friend_1+message_1)
poped_friend_2=friends.pop()
print(poped_friend_2+message_1)
poped_friend_3=friends.pop()
print(poped_friend_3+message_1)
poped_friend_4=friends.pop()
print(poped_friend_4+message_1)
message_3='\nDear friend, you are still available for the dinner with me\n'
print(friends[0]+message_3+friends[1]+message_3)
del friends[0]
del friends[1]
print(friends)

"#!/usr/bin/env python""\n"
"# -*- codingutf-8 -*-""\n"

'''
# 3-6 你找到了更大的地方,还可以邀请另外3个嘉宾。1 以3-4和3-5的程序为基础,在程序末尾添加print语句
#说明你有了更大的餐桌;2 使用insert()将一位新嘉宾添加到名单开头;3 使用insert将另外一个嘉宾添加进来
#4 使用append将最后一位嘉宾添加到名单末尾 ;5 打印消息,向名单中每位嘉宾发出邀请
'''
friends=['tom','jack','mike']
message='\nWould you like to have supper with me? \n'
print(message+friends[0])
print(message+friends[1])
print(message+friends[-1])
print(friends[0]+" will can't come tonight")
friends[0]='lili'
print(message+friends[0])
print(message+friends[1])
print(message+friends[-1])
print("i find a more table for us")
friends.insert(0,'lucy')
friends.insert(2,'sara')
friends.append('charli')
print(message+friends[0]+message+friends[1]+message+friends[2]+message+friends[3]+message+friends[4]+message+friends[-1])
print(friends)

"#!/usr/bin/env python""\n"
"# -*- codingutf-8 -*-""\n"

#3-5 刚刚得知有人无法到来,需要另外邀请一个嘉宾。; 1 在3-4练习题的末尾加上print指出
#哪位嘉宾无法赴约。2 修改嘉宾名单,将无法赴约的嘉宾替换为新邀请的客人;
#3 再次打印消息,向名单中的每位嘉宾发出邀请
friends=['tom','jack','mike']
message='Would you like to have supper with me? '
print(message+friends[0])
print(message+friends[1])
print(message+friends[-1])
print(friends[0]+" will can't come tonight")
friends[0]='lili'
print(message+friends[0])
print(message+friends[1])
print(message+friends[-1])


"#!/usr/bin/env python""\n"
"# -*- codingutf-8 -*-""\n"

#3-4 嘉宾名单:如果你可以邀请任何人共进晚餐,你会邀请谁?创建一个列表,包含
#你想要邀请的人;然后使用这个列表打印消息,邀请这些人和你共进晚餐
friends=['tom','jack','mike']
print("Would you like to have supper with me? "+friends[0])
print("Would you like to have supper with me? "+friends[1])
print("Would you like to have supper with me? "+friends[-1])

"#!/usr/bin/env python""\n"
"# -*- codingutf-8 -*-""\n"

trival=['bicycle','car','plane','boat']
print(trival)
dangerous='car'
trival.remove('car')
print(trival)
print("\na "+dangerous+" is dangerous!")
poped_trival=trival.pop(1)
print(trival)
print("The most easy trivalling way in big city is " +poped_trival)

['bicycle', 'car', 'plane', 'boat']
['bicycle', 'plane', 'boat']

a car is dangerous!
['bicycle', 'boat']
The most easy trivalling way in big city is plane
[Finished in 0.3s]

"#!/usr/bin/env python""\n"
"# -*- codingutf-8 -*-""\n"

trival=['bicycle','car','plane','boat']
print(trival)
poped_trival=trival.pop(0)          #删除列表中的第一个元素
print(trival)
print("The most easy trivalling way in big city is " +poped_trival)

['bicycle', 'car', 'plane', 'boat']
['car', 'plane', 'boat']
The most easy trivalling way in big city is bicycle
[Finished in 0.3s]

"#!/usr/bin/env python""\n"
"# -*- codingutf-8 -*-""\n"

trival=['bicycle','car','plane','boat']
print(trival)

poped_trival=trival.pop()            #删除列表中的最后一个元素
print(trival)                           #打印被删除最后一个元素后的'trival'
print(poped_trival)                   #打印被删除的那个元素

['bicycle', 'car', 'plane', 'boat']
['bicycle', 'car', 'plane']
boat
[Finished in 0.3s]


"#!/usr/bin/env python""\n"
"# -*- codingutf-8 -*-""\n"

trival=[]                         #新建一个空列表
trival.append('car')              #添加一个元素'car'
trival.append('plane')              #'car'后面添加一个'plane'
trival.append('ship')               #'plane'后面添加一个'ship'
print(trival)                       #打印trival
trival.insert(0,'bicycle')         #在第一个元素位置插入'bicycle'
print(trival)                     #
del trival[0]                       #删除第一个元素
print(trival)
del trival[1]                       #删除第二个元素
print(trival)


"#!/usr/bin/env python""\n"
"# -*- codingutf-8 -*-""\n"

#列表包含各种通勤方式,打印一个有关通勤方式的宣言
trival=['bicycle','car','plane','boat']
message="i would like to choose "+trival[0]
print(message)
trival[0]='electric_bicycle'                    #给trival[0]赋值
print(trival)                                   #重新打印trival
trival.append('foot')                           #给trival 添加新的元素'foot'
print(trival)                                   #再次打印trival

"#!/usr/bin/env python""\n"
"# -*- codingutf-8 -*-""\n"

#列表包含各种通勤方式,打印一个有关通勤方式的宣言
trival=['bicycle','car','plane','boat']
message="i would like to choose "+trival[0]
print(message)

"#!/usr/bin/env python""\n"
"# -*- codingutf-8 -*-""\n"

#使用1中的列表,为每个朋友打印一个消息。每个消息只是名字不同
names=['wu peng', 'hou kuang','king','zhou you']
message1="i miss you "+names[0] +'\n'
message2="i miss you "+names[-3]+"\t"
message3="i miss you "+names[2]+"\n"            #names[-2] 可以表示列表中倒数第二个元素,
message4="i miss you "+names[-1]                #names[-1] 可以表示列表中最后一个元素,
print(message1,message2,message3,message4)


"#!/usr/bin/env python""\n"
"# -*- codingutf-8 -*-""\n"
#3-1 朋友姓名放在列表中,命名为name,打印所有朋友名字
names=['wu peng', 'hou kuang','king','zhou you']
print(names[0].title(),names[1].upper(),names[2].lower(),names[-1])

#3.3.4 确定列表的长度 len(cars)
cars = ['bmw', 'audi', 'toyota', 'subaru']
length = len(cars)
print(length)

4
[Finished in 0.3s]


#3.3.3 倒着打印列表,按照列表相反顺序打印列表cars.reverse()
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(cars)
cars.reverse()
print(cars)

['bmw', 'audi', 'toyota', 'subaru']
['subaru', 'toyota', 'audi', 'bmw']
[Finished in 0.4s]

# 3.3.2 使用函数sorted()对列表进行临时排序
cars = ['bmw', 'audi', 'toyota', 'subaru']
print('here is the original list')
print(cars)
print('\nhere is the sorted list')
print(sorted(cars))
print('here is the original list')
print(cars)


here is the original list
['bmw', 'audi', 'toyota', 'subaru']

here is the sorted list
['audi', 'bmw', 'subaru', 'toyota']
here is the original list
['bmw', 'audi', 'toyota', 'subaru']
[Finished in 0.4s]


#3.3.1.1 使用方法sort(reverse=True)对列表按照字母相反的顺序进行永久性排序
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort(reverse=True)
print(cars)

['toyota', 'subaru', 'bmw', 'audi']
[Finished in 0.3s]

#3.3.1.1 使用方法sort()对列表按照字母顺序进行永久性排序
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)


['audi', 'bmw', 'subaru', 'toyota']
[Finished in 0.4s]

# 3.2.3.2 使用remove()删除元素,remove()括号里只能放字符串,不可以放数字
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcycles)

motorcycles.remove('ducati')    
# removed_motorcycle = motorcycles.remove('ducati')  
# ValueError list.remove(x) x not in list
print(motorcycles)              #验证我们确实删除了一个值
#print(removed_motorcycle)        #表明我们可以使用被删除的值


['honda', 'yamaha', 'suzuki', 'ducati']
['honda', 'yamaha', 'suzuki']
[Finished in 0.3s]

# 3.2.3.2 使用pop删除元素
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)

popped_motorcycle = motorcycles.pop()       
#pop()函数默认删除末尾的元素,但是也可以删除其他位置的元素,通过变换括号里的数字括号里只能放数字,不可以放字符串
print(motorcycles)              #验证我们确实删除了一个值
print(popped_motorcycle)        #表明我们可以使用被删除的值


['honda', 'yamaha', 'suzuki']
['honda', 'yamaha']
suzuki
[Finished in 0.9s]

# 3.2.3.1  使用del语句删除元素
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)

del motorcycles[0]      #del 可以删除列表中指定的任意元素
print(motorcycles)

['honda', 'yamaha', 'suzuki']
['yamaha', 'suzuki']
[Finished in 0.4s]

#3.2.2.1 列表中添加元素
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)

motorcycles.insert(0, 'ducati')        #insert()函数在列表任意位置添加元素,
#insert函数在位置0添加元素,旧元素自动后退
print(motorcycles)


['honda', 'yamaha', 'suzuki']
['ducati', 'honda', 'yamaha', 'suzuki']
[Finished in 0.4s]

#3.2.2 列表末尾添加元素
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)

motorcycles.append('ducati')        #append()函数默认在列表末尾添加元素
print(motorcycles)

['honda', 'yamaha', 'suzuki']
['honda', 'yamaha', 'suzuki', 'ducati']
[Finished in 0.4s]


#3.2.1 修改列表元素
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)

motorcycles[0] = 'ducati'
print(motorcycles)

['honda', 'yamaha', 'suzuki']
['ducati', 'yamaha', 'suzuki']
[Finished in 0.6s]

#3.1.3 使用列表中的各个值
bicycles=['trek', 'cannondale', 'redline', 'specialized']
message="My first bicycle was a "+bicycles[0].upper()

print(message)

"#!/usr/bin/env python""\n"
"# -*- codingutf-8 -*-""\n"

bicycles=['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[0].upper(),bicycles[2].lower(), bicycles[3].title())

TREK redline Specialized


# 3.1.1 输出列表中的特定元素,元素序号分别是0, 1, 2, 3  总共四个元素
bicycles=['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[0],bicycles[3])

trek specialized


# 3.1 列表由方括号包含许多元素组成,元素可以是数字,字母等任何内容
bicycles=['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)
['trek', 'cannondale', 'redline', 'specialized']


"#!/usr/bin/env python""\n"
"# -*- codingutf-8 -*-""\n"
#say hello to others
print("hello everybody")

"#!/usr/bin/env python""\n"
"# -*- codingutf-8 -*-""\n"

age=23
message="happy "+str(age)+"rd Birthday!"
print(message)

"#!/usr/bin/env python""\n"
"# -*- codingutf-8 -*-""\n"

a=3**2
print(a)
9

"#!/usr/bin/env python""\n"
"# -*- codingutf-8 -*-""\n"


favorite_language='  python  '
favorite_language.rstrip()                                #rstrip()函数删除字符串末尾的空白
favorite_language=favorite_language.rstrip()
print(favorite_language)

favorite_language.lstrip()                                  #rstrip()函数删除字符串左侧的空白
favorite_language=favorite_language.lstrip()
print(favorite_language.lstrip())

favorite_language.strip()                               #rstrip()函数删除字符串两侧的空白
favorite_language=favorite_language.strip()
print(favorite_language)


"#!/usr/bin/env python""\n"
"# -*- codingutf-8 -*-""\n"

print("languages\npython\nC\njava")# '\n'表示回车,换行
languages
python
C
java

print("\tpython")#'\t'是制表符,光标往后退4格

ma="Hello world"
print(ma)

"#!/usr/bin/env python""\n"
"# -*- codingutf-8 -*-""\n"

name="ada lovelace"
print(name.title())#首字母大写

Ada Lovelace

"#!/usr/bin/env python""\n"
"# -*- codingutf-8 -*-""\n"

name="Ada Lovelace"
print(name.upper())#全部换成大写

ADA LOVELACE

"#!/usr/bin/env python""\n"
"# -*- codingutf-8 -*-""\n"

name="Ada Lovelace"
print(name.lower())#字母全部换成小写
ada lovelace


"#!/usr/bin/env python""\n"
"# -*- codingutf-8 -*-""\n"

first_name="guang"
last_name="yang"
full_name=first_name+" "+last_name
print(full_name)

guang yang


猜你喜欢

转载自blog.csdn.net/btujack/article/details/80700678