环境配置
安装python 2.7.13
下载链接如下
https://www.python.org/ftp/python/2.7.14/python-2.7.14.msi
Install for all users
C:\Python27\
首先,确保选择了名称为 pip 的功能
确保已经选中 Add python.exe to Path
然后一路next 到安装完成
验证安装完成,在cmd中,打入python命令会出现
Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
这就说明安装成功了.
然后在下载个IDE 有官方主推的idle ,有Sublime还有jetbrain推出的pycharm
我这边选择使用社区版的pycharm
下载地址
https://download.jetbrains.8686c.com/python/pycharm-community-2017.3.exe
然后我们使用命令行
推荐使用Git Bash 应用
下载地址
https://git-scm.com/download/win windows版
然后要学会一些常用的shell 命令 , 例如 pwd
:查看目录路径 ls
: list 的意思,查看当前文件下面的所有文件 open
: 打开一个文件夹(在window下的git bash 里是 start
) cd
:进入到某个目录下, cd ~就是进入到用户目录下 mkdir
: 新建目录 touch
:新建某个文件 touch 1.txt
建立多个文件
touch animals/marsupials/kangaroo.txt animals/cloven_hoofed_animals/giraffe.txt
rm
删除某个文件 rmdir
用来删除某个空文件夹 rm -r
这里的r 代表recursive(递归) rm -ri cats
这里的i 代表interactive(互动) 它将会询问你要不要删除
python test.py 运行一个python 命令
( 对于运行 Git Bash 的 Windows 用户,应该执行命令 winpty python test.py 来运行你的 Python 文件。)
编程导论
python是一个解释性语言
为什么不用自然语言作为计算机语言呢
一,具有歧义性 Ambiguous
二,太繁琐 verbose
syntaxError 语法错误
sentence =subject + verb + object .
backus-naur form 巴克斯构造
巴克斯范式
<non-terminal>->replacement. 非终止符 代替符
比如 sentence ,subject,verb,object,non,都是非终止符
而i, like, pythone ,cookies ,都是终止,
我们都是由 derivation 推导出来的.
Expression->Expression operator Expression
Expression-> number
Expression-> (Expression)
Operator->+,-,*,/
Number->1,2,3,4,5
编译式(立刻完成所有工作然后运行新的程序)和解释式(两个同时实行)
变量与字符串
变量(the variable)
- 变量是什么?
- 对变量进行赋值(assign a value)是什么意思?
- 等于号 =,在数学和编程方面的含义有什么区别?2 + 3 = 5 和 my_variable = 5 中的等号有什么区别?
#注释符号
使用一个变量之前,我们要定义这个变量.
变量名尽量使用小写的,例如 days_of_year
字符串中的+号, 连接符号
无法对字符串做加法, 但是能做乘法
Indexing Strings
<string>[<expression>] --> name[0],name[1+1+1],(name+name)[1+1]
<string>[<expression>:<expression>] -->name[0:4]#0到第三个字符
<string>.split(seperator)
从零开始索引
如果输入负数那么会从字符串的右边开始索引
name[0:4] 第0个字符到第4个字符之间的值
s = "1234567";
print s[0:4];
#输出1234
#还可以输出s[0:]不指定最后即是到最后 反正也是 两边都不设定的话就是全部
string 的find 方法
<string>.find(<string>)
<string>.find(<string>,<number>)
第一次出现的位置,如果找到即输出下标,没有则出-1
number 代表从这个位置开始往后找.
<string>.replace(<old>,<new>,<number>)
字符串替换
输入–函数(functions)–输出
过程(procedures)
什么是函数
如何创建函数
如何使用函数
什么时候应该写函数
为什么函数如此重要
<procedures>(<input>,<input>....)
函数定义方式与函数使用方式之间的差别
python 使用none 来说明是返回空值
在执行过程中所有可见的函数和变量,在函数返回的时候都变的不可见了
函数组合
sum(2,sum(2,5))
用于比较的运算符
< > ==
<number><operation><number>
#if语句
if<TestExpression>:
<Block>
else:
<Block>
boolean 类型的值要大写
while<Expression>:
<block>
break
str(n) 强转成 string类型
#注释 ``` 三个引号表示块状注释
from random import randint
structured data 结构化数据
List 可以包含重复元素 可以包含小list(nested lists)
<list>->[<Expression>,<Expression>,<Expression>]
p=['a','b','c','d','e']
p[o]=='a'
p[1:3]=['b','c','d']
print "EXAMPLE 1: Lists can contain strings"
string_list = ['HTML', 'CSS', 'Python']
print string_list
print "EXAMPLE 2: Lists can contain numbers"
number_list = [3.14159, 2.71828, 1.61803]
print number_list
print "EXAMPLE 3: Lists can be 'accessed' and 'sliced' like how we accessed and sliced strings in the previous lessons"
pi = number_list[0]
not_pi = number_list[1:]
print pi
print not_pi
print "EXAMPLE 4: Lists can contain strings AND numbers"
mixed_list = ['Hello!', 42, "Goodbye!"]
print mixed_list
print "Example 5: Lists can even contain other lists"
list_with_lists = [3, 'colors:', ['red', 'green', 'blue'], 'your favorite?']
print list_with_lists
print list_with_lists[2][1]
#==>red
变更(mutation)和别名(aliasing)
string 是直接指向新的一个string
而数组是改变那个数组的位置,并没有创建一个新的数组
可变和不可变要考虑的是另外一个变量同时指向同一个东西
list 的其他方法
<list>.append(<element>)
#在列表末尾添加元素 没有创建新列表,只是改变了列表的值
我们发现使用 += 和向变量添加值(append)一样。
mylist += [6,7]
<list>+<list>
#类似于str的+ 创建新列表,不改变原来列表的值
len(<list>)
#计算这个list的长度 不算嵌套元素的个数, 只算最大的那个括号里的值
<list>.index(<value>)
#找到值出现的第一个位置 如果没有则会报错(并不会报-1)
<value> in <list>
#查看value 是不是在list里面 在的话就显示True 不在就显示False
<value> not in <list>
#与in 相反
如何遍历循环一个list
for<name> in <list>:
<block>
#例子
for e in list:
print e
解决问题
0.勇敢
1.什么是输入(检验输入)
2.输出什么?
3.手动写一些例子
4.想出一些机械的方法代码
5.写一些小测验
可以return 多个值
return year,month,day
然后用于接受的也可以是三个值
year,month,day =function(year,month,day)
如果不够满足函数假设的话,我们就提出一个断言(assertion)
assert<Expression>-->False-->Exception
assert dateIsBefore(year1, month1, day1, year2, month2, day2)
# Credit goes to Websten from forums
#
# Use Dave's suggestions to finish your daysBetweenDates
# procedure. It will need to take into account leap years
# in addition to the correct number of days in each month.
# 这是一个判断日期之间有多少天的程序
def isleapyear(year):
if year % 400 == 0:
return True
else:
if year % 4 == 0:
if year % 100 == 0:
return False
else:
return True
return False
def daysinmonth(year, month):
if month == 2:
if isleapyear(year):
return 29
else:
return 28
else:
if month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12:
return 31
else:
return 30
def nextDay(year, month, day):
"""Simple version: assume every month has 30 days"""
if day < daysinmonth(year, month):
return year, month, day + 1
else:
if month == 12:
return year + 1, 1, 1
else:
return year, month + 1, 1
def dateIsBefore(year1, month1, day1, year2, month2, day2):
"""Returns True if year1-month1-day1 is before year2-month2-day2. Otherwise, returns False."""
if year1 < year2:
return True
if year1 == year2:
if month1 < month2:
return True
if month1 == month2:
return day1 < day2
return False
def daysBetweenDates(year1, month1, day1, year2, month2, day2):
"""Returns the number of days between year1/month1/day1
and year2/month2/day2. Assumes inputs are valid dates
in Gregorian calendar."""
# program defensively! Add an assertion if the input is not valid!
assert not dateIsBefore(year2, month2, day2, year1, month1, day1)
days = 0
while dateIsBefore(year1, month1, day1, year2, month2, day2):
year1, month1, day1 = nextDay(year1, month1, day1)
days += 1
return days
def test():
test_cases = [((2012, 1, 1, 2012, 2, 28), 58),
((2012, 1, 1, 2012, 3, 1), 60),
((2011, 6, 30, 2012, 6, 30), 366),
((2011, 1, 1, 2012, 8, 8), 585),
((1900, 1, 1, 1999, 12, 31), 36523)]
for (args, answer) in test_cases:
result = daysBetweenDates(*args)
if result != answer:
print "Test with data:", args, "failed"
else:
print "Test case passed!"
def test2():
assert nextDay(2000,1,1)==(2000,1,2)
assert nextDay(2000,2,28)==(2000,3,1)
assert nextDay(2000,1,1)==(2000,1,2)
print "test finish"
# test()
print test()
Stub (存根或桩) 是指该函数的虚拟实现,是对将要开发的代码的一种临时替代。它可以在你编写整个函数之前用于测试。
探索列表属性:你将探索用 + 运算符连接两个列表和用 .append() 附加列表的区别。你还将学习一个新的运算符 +=。
列表乘:你将编写将列表中所有数字相乘的代码。
最大值:你将编写返回列表中最大值的代码。
str(random.randint(0,10)) #str()转成字符串
python 2.7版本中文备注需要在文件第一行添加
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
import random
# 获取随机数组
def getDataList():
random_list = []
list_length = 20
while len(random_list) < list_length:
random_list.append(random.randint(1, 10))
print random_list
return random_list
# 输出一个列表的下标和数
def answer(count_list):
print count_list
print "index | number"
index = 0
num_len = len("index")
while index < len(count_list):
num_spaces = num_len - len(str(index))
print " " * num_spaces + str(index) + " | " + str(count_list[index])
index = index + 1
# 输出一个列表的频数分布
def get_pop_distribution(count_list):
print "number | occurrence"
set=[0]*len(count_list)
index=0
num_len = len("number")
while index<len(count_list):
if count_list[index] not in set:
num_spaces = num_len - len(str(count_list[index]))
print " " * num_spaces + str(count_list[index]) + " | " + str(count_times(count_list,count_list[index]))
set.append(count_list[index])
index = index + 1
def count_times(list,number):
count=0
for e in list:
if number==e:
count+=1
return count
print get_pop_distribution(getDataList())
# print count_times(getDataList(),2)
string.split()
" ".join(string)
# Write code for the function play_game, which takes in as inputs parts_of_speech
# (a list of acceptable replacement words) and ml_string (a string that
# can contain replacement words that are found in parts_of_speech). Your play_game
# function should return the joined list replaced, which will have the same structure
# as ml_string, only that replacement words are swapped out with "corgi", since this
# program cannot replace those words with user input.
parts_of_speech = ["PLACE", "PERSON", "PLURALNOUN", "NOUN"]
test_string = """This is PLACE, no NOUN named PERSON, We have so many PLURALNOUN around here."""
def word_in_pos(word, parts_of_speech):
for pos in parts_of_speech:
if pos in word:
return pos
return None
def play_game(ml_string, parts_of_speech):
replaced = []
# your code here
strArray = ml_string.split()
for e in strArray:
result = word_in_pos(e, parts_of_speech)
if result == None:
replaced.append(e)
else:
e = e.replace(result, "corgi")
replaced.append(e)
return " ".join(replaced)
print play_game(test_string, parts_of_speech)
#要求用户输入一个单词
user_in_type=raw_input("please input a word")
#-*- coding: utf-8 -*-
import webbrowser
import time
#打印当前计算机时间
print time.ctime()
#程序停止10秒种
time.sleep(10)
#打开一个浏览器转跳到谷歌
webbrowser.open("http://www.google.com")
import os
#r代表raw package 代表接受它本身,不要用其他的东西去解读它
file_list=os.listdir(r"C:\Users\hulion\Downloads\prank\prank")
#获取当前目录文件夹路径
pwd=os.getcwd()
#更换工作目录
os.chdir(r"C:\Users\hulion\Downloads\prank\prank")
for file_name in file_list:
new_name=file_name.translate(None,"0123456789")
os.rename(file_name,new_name)
os.chdir(pwd)
print file_list
#-*- coding: utf-8 -*-
#这是一个通过正方形画园的代码
#在电脑上花东西的玩意
import turtle
def draw_square():
#我们要一个幕布
window=turtle.Screen();
#这个幕布有一个绿色的背景色
window.bgcolor("green")
brad=turtle.Turtle()
#设置这个的形状
brad.shape("turtle")
#设置这个的速度
brad.speed(2)
#设置这个的颜色
brad.color("red")
n=20
count=0
while count<360:
zheng_fang_xing(brad)
brad.right(n)
count+=n
#window在按下一个键的时候关闭
window.exitonclick()
def zheng_fang_xing(brad):
count=0
while count<4:
# 向前走100个单位
brad.forward(100)
# 向右边旋转90度
brad.right(90)
count+=1
def yuan_xing():
yuan = turtle.Turtle()
# 形状是个箭头
yuan.shape("arrow")
# 画个园,半径为100
yuan.circle(100)
draw_square()
结果就是这样
这个连接可以查看你的词语是不是冒犯词
http://www.wdylike.appspot.com/?q=shot
#-*- coding: utf-8 -*-
#这个程序是检查你的语句中是否有冒犯词
import urllib
def read_text():
#打开这个文件
quotes=open("C:\Users\movie_quotes.txt")
#读取这个文件里的东西到contents_of_file里面
contents_of_file=quotes.read()
print contents_of_file
#取完了要记得关闭
quotes.close()
check_profanity(contents_of_file)
def check_profanity(text_to_check):
#urllib 帮助我们从网上获取信息
connection=urllib.urlopen("http://www.wdylike.appspot.com/?q="+text_to_check)
connection_text=connection.read()
print connection_text
connection.close()
read_text()
类名称首字母大写(不是强制,习惯)
class(类)
可以同时拥有变量和方法
init(初始化)
instance(实例)
constructor(构造函数)
self
instance variable(实例变量)
instance methods (实例方法)
#这个是classs.py文件
# -*- coding:utf-8 -*-
import webbrowser
# 这个是类名
class Movie:
# 类变量 评分 因为不常修改所以全部大写定义
VALID_RATINGS = ['A', 'B', 'C', 'D', 'E']
# 构造函数
def __init__(self, title, story_line, poster_image_url, trailer_youtube_url):
print "Class movie init success"
# 实例变量
self.title = title
self.story_line = story_line
self.poster_image_url = poster_image_url
self.trailer_youtube_url = trailer_youtube_url
# 实例方法
def print_msg(self):
print self.title
print self.story_line
print self.poster_image_url
print self.trailer_youtube_url
def show_url(self):
webbrowser.open(self.trailer_youtube_url)
注意,这里的self 不是保留关键字, 不信你可以把所有的self改成shot试试
#这个是tets.py
# -*- coding:utf-8 -*-
import classs
import fresh_tomatoes
dazaibian = classs.Movie("大灾变1", "这是故事线", "这是图片路径", "http://www.baidu.com")
dazaibian2 = classs.Movie("大灾变2", "这是故事线2", "这是图片路径2", "http://www.google.com")
movies = [dazaibian, dazaibian2]
#fresh_tomatoes.open_movies_page(movies)
print classs.Movie.valid_ratings
#这个是fresh_tomatoes
import webbrowser
import os
import re
# Styles and scripting for the page
main_page_head = '''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Fresh Tomatoes!</title>
<!-- Bootstrap 3 -->
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap-theme.min.css">
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.1.0/js/bootstrap.min.js"></script>
<style type="text/css" media="screen">
body {
padding-top: 80px;
}
#trailer .modal-dialog {
margin-top: 200px;
width: 640px;
height: 480px;
}
.hanging-close {
position: absolute;
top: -12px;
right: -12px;
z-index: 9001;
}
#trailer-video {
width: 100%;
height: 100%;
}
.movie-tile {
margin-bottom: 20px;
padding-top: 20px;
}
.movie-tile:hover {
background-color: #EEE;
cursor: pointer;
}
.scale-media {
padding-bottom: 56.25%;
position: relative;
}
.scale-media iframe {
border: none;
height: 100%;
position: absolute;
width: 100%;
left: 0;
top: 0;
background-color: white;
}
</style>
<script type="text/javascript" charset="utf-8">
// Pause the video when the modal is closed
$(document).on('click', '.hanging-close, .modal-backdrop, .modal', function (event) {
// Remove the src so the player itself gets removed, as this is the only
// reliable way to ensure the video stops playing in IE
$("#trailer-video-container").empty();
});
// Start playing the video whenever the trailer modal is opened
$(document).on('click', '.movie-tile', function (event) {
var trailerYouTubeId = $(this).attr('data-trailer-youtube-id')
var sourceUrl = 'http://www.youtube.com/embed/' + trailerYouTubeId + '?autoplay=1&html5=1';
$("#trailer-video-container").empty().append($("<iframe></iframe>", {
'id': 'trailer-video',
'type': 'text-html',
'src': sourceUrl,
'frameborder': 0
}));
});
// Animate in the movies when the page loads
$(document).ready(function () {
$('.movie-tile').hide().first().show("fast", function showNext() {
$(this).next("div").show("fast", showNext);
});
});
</script>
</head>
'''
# The main page layout and title bar
main_page_content = '''
<body>
<!-- Trailer Video Modal -->
<div class="modal" id="trailer">
<div class="modal-dialog">
<div class="modal-content">
<a href="#" class="hanging-close" data-dismiss="modal" aria-hidden="true">
<img src="https://lh5.ggpht.com/v4-628SilF0HtHuHdu5EzxD7WRqOrrTIDi_MhEG6_qkNtUK5Wg7KPkofp_VJoF7RS2LhxwEFCO1ICHZlc-o_=s0#w=24&h=24"/>
</a>
<div class="scale-media" id="trailer-video-container">
</div>
</div>
</div>
</div>
<!-- Main Page Content -->
<div class="container">
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="#">Fresh Tomatoes Movie Trailers</a>
</div>
</div>
</div>
</div>
<div class="container">
{movie_tiles}
</div>
</body>
</html>
'''
# A single movie entry html template
movie_tile_content = '''
<div class="col-md-6 col-lg-4 movie-tile text-center" data-trailer-youtube-id="{trailer_youtube_id}" data-toggle="modal" data-target="#trailer">
<img src="{poster_image_url}" width="220" height="342">
<h2>{movie_title}</h2>
</div>
'''
def create_movie_tiles_content(movies):
# The HTML content for this section of the page
content = ''
for movie in movies:
# Extract the youtube ID from the url
youtube_id_match = re.search(
r'(?<=v=)[^&#]+', movie.trailer_youtube_url)
youtube_id_match = youtube_id_match or re.search(
r'(?<=be/)[^&#]+', movie.trailer_youtube_url)
trailer_youtube_id = (youtube_id_match.group(0) if youtube_id_match
else None)
# Append the tile for the movie with its content filled in
content += movie_tile_content.format(
movie_title=movie.title,
poster_image_url=movie.poster_image_url,
trailer_youtube_id=trailer_youtube_id
)
return content
def open_movies_page(movies):
# Create or overwrite the output file
output_file = open('fresh_tomatoes.html', 'w')
# Replace the movie tiles placeholder generated content
rendered_content = main_page_content.format(
movie_tiles=create_movie_tiles_content(movies))
# Output the file
output_file.write(main_page_head + rendered_content)
output_file.close()
# open the output file in the browser (in a new tab, if possible)
url = os.path.abspath(output_file.name)
webbrowser.open('file://' + url, new=2)
#预装变量
#用三个引号标记
''' 这是doc '''
__doc__
#还有很多
__name__
__module__
inheritance 继承
# -*- coding:utf-8 -*-
class parent():
def __init__(self, eye_color, tall):
print "父类被创建"
self.eye_color = eye_color
self.tall = tall
def show_info(self):
print "这是父类的眼睛颜色-->" + self.eye_color
print "这是父类的身高-->" + str(self.tall)
class child(parent):
def __init__(self, eye_color, tall, number_of_toy):
print "子类被创建"
parent.__init__(self, eye_color, tall)
self.number_of_toy = number_of_toy
# 方法覆盖 method overriding
def show_info(self):
print "这是子类的眼睛颜色-->" + self.eye_color
print "这是子类的身高-->" + str(self.tall)
print "这是子类的玩具数量-->" + str(self.number_of_toy)
gu_yi = parent("bule", 172)
# gu_yi.show_info()
gu_er = child("bule", 173, 3)
# print gu_er.tall, gu_er.eye_color, gu_er.number_of_toy
gu_er.show_info()