第一章 起步

计算机执行源程序的两种方式:

  • 编译:一次性执行源代码,生成目标代码
  • 解释:随时需要执行源代码

源代码:采用某种编程语言编写的计算机程序

目标代码:计算机可执行,101010

编程语言分为两类:

  • 静态语言:使用编译执行的编程语言,C,C++
  • 脚本语言:使用解释执行的语言,Python

编写和运行Python程序主要有两种方式: 

1. 交互式: 我们写的每一行Python代码都可以敲回车键来运行

2. 文件式: 先编写好Python代码,然后通过Python指令运行

编写Python代码时,可使用任意一种文本编译器,也可使用IDE工具

IDE不仅可以编写代码还可以调试和运行,文本编译器只可编写,不可运行和调试

保存文件时,文件命名推荐全部采用小写英文字母,后缀名必须为py. 另外,文件编码应该采用UTF-8


第二章 变量和简单数据类型

2.1 编写运行一个hello world程序

print('hello world')

2.2 变量

添加一个名为message的变量

message = "Hello Python world!"

print(message)

变量的命名

  • 变量名只能包含字母、数字下划线和汉字等,变量名不能以数字开头,eg: 可将变量命名为message_1
  • 变量名不能包含空格
  • 区分大小写:Myname与myname是两个不同的
  • 关键字和函数名不能作为变量名
  • 不要使用Python的内置函数作为自己的变量

关键词

False

def

if

raise

None

del

import

return

True

elif

in

try

and

else

is

while

as

except

lambda

with

assert

finally

nonlocal

yield

break

for

not

class

from

or

continue

global

pass

2.3 字符串

 用引号括起来的都是字符串,单引号,双引号都可以

"This is a string."
'This is also a string.'

 使用方法修改字符串的大小

name = "Ada Lovelace" 
print(name.upper()) //在name.title()中,name后面的句点(.)让Python对变量name执行方法title()指定的操作,upper()全部转化为大写
print(name.lower())//lower()全部转化为小写
# ADA LOVELACE ,ada lovelace
//title()以首字母大写的方式显示每个单词

 合并字符串,把姓名合而为一

first_name = "ada"
last_name = "lovelace"
full_name = first_name + " " + last_name
message = "Hello, " + full_name.title() + "!"
print(message)
# Hello,ada lovelace!

使用制表符或换行符来添加空白

要在字符串中添加制表符,可使用字符组合\t

print('\tPython')

要在字符串中添加换行符,可使用字符组合\n

print('Languages:\nPython\nc')

XGBoostpython代码 代码编程python_ci

转义符:\n换行,\r回车\b回退(光标移动到本行首)

删除空白,Python能够找出字符串开头和末尾多余的空白

favorite_language = ' python '
favorite_language.rstrip()//删除末端的空格 ' python' 
 favorite_language.lstrip()//删除首段的空格 'python ' 
favorite_language.strip() //删除两端的空格 'python' 
favorite_language//'python '

 对变量favorite_language调用方法rstrip()后,这个多余的空格被删除了,这种删除时暂时的

 永久删除字符的空白,必须将删除操作的结果存回变量中

favorite_language = 'python '
favorite_language = favorite_language.rstrip()
favorite_language//'python'

总结

XGBoostpython代码 代码编程python_XGBoostpython代码_02

 

XGBoostpython代码 代码编程python_python_03

2.4 数字

整数类型

可正可负,无取值范围的限制,pow(x,y)函数:计算x的y次方,4种进制表示,十进制,二进制,八进制

浮点数类型

小数点可出现在数字的任何位置,存在不确定的尾数,用round()四舍五入

0.1+0.1
0.2+0.2
round(0.2+0.1,1)//0.3 round(x,y),x四舍五入,保留y位小数

 数值运算

2+3//加
3-2//减
2*3//乘
3/2//除
3//2//取整
2**3//次方
3%2//取余
123 +4.0= 127.0 //(整数+浮点数=浮点数),类型间可进行混合运算,生成结果为“最宽"类型
三种类型存在一种逐渐"扩展"或"变宽”的关系:
整数 > 浮点数 > 复数
数值运算函数,abx(x)绝对值,divmod(x,y)商余,int(x)整数,float(x)浮点数
print(5+3)
print(2*4)
print(8/1)
print(10-2)
number="1","2","3","4"
print(number[2])

 将数值转化为字符串,可调用函数str(),它让Python将非字符串值表示为字符串

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

2.5 注释

在使用#(井号)时,#位于注释行的开头,#后面有一个空格(单行注释)

也可使用'''开头和结尾'''a,b,c,d,e...'''(多行注释)

# 大家好
print('hello people')

 Python之禅,只需在解释器重中执行import this

import this
The Zen of Python, by Tim Peters 
Beautiful is better than ugly.

第三章 列表简介

列表

列表按特定顺序排列的元素组成,用[]表示,其中元素由逗号分开 ['1','2','3','4'....]

在Python中,第一个列表元素的索引为0,而不是1,字符串的序号[0到-1]

  • 创建列表,访问列表,使用列表中的各个值
bicycles=['trek','redline','specialized']
print(bicycles)
//['trek','redline','specialized'] 创建列表

bicycles=['trek','redline','specialized']
print(bicycles[0])
//trek 访问列表

bicycles=['trek','redline','specialized']
massage="My bicycle was a"+bicycles[0]+"!"
print(massage)
//My bicycle was a trek! 使用列表中的各个值
  •  修改,添加元素
bicycles=['trek','redline','specialized']
print(bicycles)
//['trek','redline','specialized']

# 修改列表元素
bicycles[0]='abc'
print(bicycle)
//['abc','redline','specialized']

# 添加元素,append()将元素添加列表末尾
bicycles.append=('hahaha')
print(bicycles)
//['trek','redline','specialized','hahaha'] 

# 插入元素,insert()可在列表任意位置插入新元素
bicycles.insert=(0,'hahaha')
print(bicycles)
//['trek','hahaha','redline','specialized']
  • 删除元素
bicycles=['trek','redline','specialized']
print(bicycles)
//['trek','redline','specialized']

# del删除列表元素
del bicycles[0]
print(bicycles)
//['redline','specialized']

# pop()删除列表末端元素
popped_bicycle = bicycles.pop() 
print(bicycles) 
print(popped_bicycle)
//['trek','redline']

# 用pop()来删除列表中任何位置的元素
first_owned = bicycles.pop(0) 
print(first_owned.title())
//['redline','specialized']

# 只知道要删除的元素的值,可使用方法remove()删除元素
bicycles.remove('specialized') 
print(bicycles)
//['trek','redline']

# 删除值'redline',并打印一条消息
bicycles.remove(too_expensive) 
print(bicycles) 
print(too_expensive.title())
//['trek','specialized']
//['redline']

组织列表

使用方法 sort()对列表进行永久性排序

对列表中,按字母排列

cars = ['bmw', 'audi', 'toyota', 'subaru'] 
cars.sort()
print(cars)
//['audi', 'bmw', 'subaru', 'toyota']

倒着打印列表,使用reverse( )函数

cars = ['bmw', 'audi', 'toyota', 'subaru']
print(cars)
cars.reverse()
print(cars)
//['bmw', 'audi', 'toyota', 'subaru']原列表
//['subaru', 'toyota', 'audi', 'bmw'] 
确定列表长度
cars = ['bmw', 'audi', 'toyota', 'subaru']
len(cars)
//4

第四章 操作列表

遍历整个列表

magicians = ['alice', 'david', 'carolina']
for magician in magicians:
       print(magician)
//alice david  carolina
foods=['酥肉焖面','砂锅刀削面','西红柿炒鸡蛋','酸菜鱼']
message='我的最爱:'
for food in foods:
    print(food)
for food in foods:
    print(message+food)
/*酥肉焖面
砂锅刀削面
西红柿炒鸡蛋
酸菜鱼
我的最爱:酥肉焖面
我的最爱:砂锅刀削面
我的最爱:西红柿炒鸡蛋
我的最爱:酸菜鱼*/

 创建数值列表,使用range( )函数

for value in range(1,5):
        print(value) 
//123
for number in range(1,21):
    print(number)
//1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

 使用 range()创建数字列表

numbers = list(range(1,6))
print(numbers)//[1, 2, 3, 4, 5]

使用函数range()时,还可指定步长

even_numbers = list(range(2,11,2))

print(even_numbers) //[2, 4, 6, 8, 10]

遍历切片

players = ['charles', 'martina', 'michael', 'florence', 'eli'] 
  print(players[0:3]) //第0位取三个
//['charles', 'martina', 'michael'] 

players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[2:])//第2位,取到最后一个
//['michael', 'florence', 'eli']从第3个元素到列表末尾的所有元素,[:2]从头开始,取2个['michael', 'florence'] 没有指定第一个索引,Python将自动从列表开头开始,没有指定最后一个索引,将取值到最后一位

players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[-3:])//从倒数第三个,取到尾
//['michael', 'florence', 'eli']
1
foods=['酥肉焖面','砂锅刀削面','西红柿炒鸡蛋','酸菜鱼']
print(foods[0:3])
print(foods[2:])
print(foods[-3:])

//['酥肉焖面', '砂锅刀削面', '西红柿炒鸡蛋']
['西红柿炒鸡蛋', '酸菜鱼']
['砂锅刀削面', '西红柿炒鸡蛋', '酸菜鱼']

2
foods=['酥肉焖面','砂锅刀削面','西红柿炒鸡蛋','酸菜鱼']
friend=foods[:]
print(friend)
print(foods)
for i in foods:
    print(i,end='')
//['酥肉焖面', '砂锅刀削面', '西红柿炒鸡蛋', '酸菜鱼']
['酥肉焖面', '砂锅刀削面', '西红柿炒鸡蛋', '酸菜鱼']
酥肉焖面砂锅刀削面西红柿炒鸡蛋酸菜鱼

元组

 是一种不可变序列类型

dimensions=(200,50)
print(dimensions[0])
print(dimensions[1])//200 50

第五章 if语句

简单的if语句

单分支结构(顺序)

guess=eval(input())//eval()去掉函数最外侧引号并执行余下语句的函数
if guess==99:
print("猜对了")

二分支结构(分支)

guess=eval(input())
if guess==99:
print("猜对了")
else:("猜错了")
# 紧凑形式
guess=eval(input())
print("".format("对"if guess==99 else"错"))

多个elif语句

多分支结构

score=eval(input())
if score>=60:
   grade="D"
elif score>=70:
   grade="C"
elif score>=80:
   grade="B"
elif score>=90:
   grade="A"
print("{}".format(grade))
age=int(input("请输入年龄:"))
if age<2:
    print("他是婴儿!")
elif age<4:
    print("他正在蹒跚学步!")
elif age<13:
    print("他是儿童!")
elif age<20:
    print("他是青少年!")
elif age<65:
    print("他是成年人!")
elif age>=65:
    print("他是老年人!")
请输入年龄:21
他是成年人!

  if-else语句

条件判断及组合(循环)

guess=eval(input())
if guess>99 or guess<99:
    print("猜错了")
else:
    print("猜对了")

条件判断

操作符

描述

<

小于

<=

小于等于

>=

大于等于

>

大于

==

等于

!=

不等于

操作符及使用

操作符及使用

描述

x and y


x or y


not x


异常处理

try:
    num =eval(input("请输入一个整数:"))
    print(num**2)
except:
    print("输入不是整数”)

第六章 字典

字典( dict)是可迭代的、通过键( key)来访问元素的可变的容器类型的数据

alien_0 = {'color': 'green', 'points': 5} 
print(alien_0['color']) 
print(alien_0['points']) 
//green 5
1
friend ={"first_name":"zhao", "last_name":"yan","city":"xi an"}
print(friend);
print(friend["first_name"])
print(friend["last_name"])
print(friend["city"])
{'first_name': 'zhao', 'last_name': 'yan', 'city': 'xi an'}
//zhao
yan
xi an

2
glossary={
    "NameError":"命名错误",
    "SyntaxError":"语法错误",
    "TypeError":"类型错误",
    "IndexError":"索引错误",
    "NameError":"命名错误",
    "Indentation":"缩进错误",
    "KeyError":"字典关键字错误",
}
for i,j in glossary.items():
    print(i+":\t"+j)
NameError:	命名错误
SyntaxError:	语法错误
TypeError:	类型错误
IndexError:	索引错误
Indentation:	缩进错误
KeyError:	字典关键字错误

第七章 while循环

遍历循环

计数遍历循环

for i in range(1,6):
    print(i)//12345
for i in range(1,6,2):
    print(i)//135

字符串遍历循环

for c in "Python":
print(c,end=",")
//P,y,t,h,o,n,

列表遍历循环 

for item in [123, "PY",456] :
print(item, end=",")
//123,PY,456,

文件遍历循环 

for line in fi:
    print(line)

无限循环

a=3
while a>0:
    a=a-1
    print(a)//210
a=3
while a>0:
    a=a+1
    print(a)//45...CTRL+C退出运行

循环控制保留字

break跳出并结束当前整个循环,执行循环后的语句,continue结束当次循环,继续执行后续次数循环 

for c in "PYTHON":
    if c =="T":
     continue
    print(c, end="")
//PYHON

for c in "PYTHON":
    if c =="T":
      break
    print(c, end="")
//PY

S ="PYTHON”
while s!="":
    for c in s:
        print(c, end="")   
    s = s[:-1]
//PYTHONPYTHOPYTHPYTPYP,break仅跳出当前最内层循环

S ="PYTHON
while s!="" :
    for c in s:
       if c =="T":
         break
       print(c,end="")
   s=s[:-1]
//PYPYPYPYPYP

循环与else 

for c in "PYTHON":
    if c =="T":
      continue
    print(c, end="")
else:
    print("正常退出")//PYHON正常退出

for c in "PYTHON":
    if c =="T":
      break
    print(c, end="")
else:
    print("正常退出")//PY

XGBoostpython代码 代码编程python_XGBoostpython代码_04


第八章 函数

定义函数

def dispiay_message():
    print("本章主题:函数")
dispiay_message()//本章主题:函数

向函数传递信息

def favorite_book(title):
    print("One of my favorite book is"+title.title())
favorite_book("Alice in Wonderland")
//One of my favorite book is Alice in Wonderland

传递实参

def make_shirt(size,style):
    print("size:"+size,end=" ")
    print("style:"+style)
make_shirt("M","COOL")
make_shirt(size="M",style="COOL")
//size:M style:COOL
size:M style:COOL

返回值

def city_country(city,country):
    return'"'+city+","+country+'"'
location=city_country("santiage","chile")
print(location)
//"santiage,chile"