1.安装python
2.安装pycharm
3.安装anaconda

# 1 基本程序要素

### Python 程序示例：猜数字

``````"""
Author: Ken Lambert
Plays a game of guess the number with the user.
"""

import random

def main():
"""Inputs the bounds of the range of numbers,
and lets the user guess the computer's number until
the guess is correct."""
smaller = int(input("Enter the smaller number: "))
larger = int(input("Enter the larger number: "))
myNumber = random.randint(smaller, larger)
count = 0
while True:
count += 1
userNumber = int(input("Enter your guess: "))
if userNumber < myNumber:
print("Too small")
elif userNumber > myNumber:
print("Too large")
else:
print("You've got it in", count, "tries!")
break

if __name__ == "__main__":
main()

``````

``````Enter the smaller number: 1
Enter the larger number: 32
Too small
Too large
You’ve got it in 3 tries!
``````

``````python numberguess.py
``````

### 程序注释

``````# This is an end-of-line comment.
``````

### 字符串字面值

``````print("Using double quotes")
print(’Using single quotes’)
print("Mentioning the word ’Python’ by quoting it")
print("Embedding a\nline break with \\n")
print("""Embedding a
line break with triple quotes""")
``````

``````Using double quotes
Using single quotes
Mentioning the word ’Python’ by quoting it
Embedding a
line break with \n
Embedding a
line break with triple quotes
``````

### 函数调用

``````min(5, 2) # Returns 2
``````

Python 包含了一些标准的函数，例如 abs 和 round。很多其他的函数，可以通过导入模块的方式而变得可用，稍后你将会看到这一点。

### input 函数（输入）

``````name = input("Enter the smaller number: ")
``````

### 类型转换函数和混合模式运算

``````radius = float(input("Radius: "))
print("The area is", 3.14 * radius ** 2)
``````

### 变量和赋值语句

PI = 3.1416

<identifier> = <expression>

``````minValue, maxValue = 1, 100
``````

``````a, b=b,a
``````

### import 语句

import 语句使得另一个模块中的标识符可以被一个程序所见到。这些标识符可能是对象名、函数名或类名。有几种方式可以表示一条 import 语句。最简单的方式是，导入一个模块名称，例如：

``````import math
``````

``````from math import sqrt
print(sqrt(2))
``````

``````from math import pi, sqrt
print(sqrt(2) * pi)
``````

# 2 控制语句

Python 包含了针对序列、条件式执行和迭代等情况的、常见的各种控制语句。语句的序列是一条接着一条编写的一组语句。一个序列中的每一条语句，都必须以相同的缩进开始。本节将会介绍条件式执行和迭代的控制语句。

# 条件语句

Python 的条件式语句的结构和其他语言中的条件式语句类似。关键词 if、elif 和else 是很重要的，冒号和缩进也同样重要。

``````if <Boolean expression>:
<sequence of statements>
``````

``````if <Boolean expression>:
<sequence of statements>
else:
<sequence of statements>
``````

``````if <Boolean expression>:
<sequence of statements>
elif <Boolean expression>:
<sequence of statements>
...
else:
<sequence of statements>
``````

``````if x > y:
print("x is greater than y")
elif x < y:
print("x is less than y")
else:
print("x is equal to y")
``````

### 使用 if name == "main"

``````if __name__ == "__main__":
main()
``````

### 循环语句

Python 的 while 循环语句的结构，类似于其他语言中的循环结构。其语法如下：

``````while <Boolean expression>:
<sequence of statements>
``````

``````product = 1
value = 1
while value <= 10:
product *= value
value += 1
print(product)
``````

``````product = product * value
``````

Python 包含了一个for 循环语句，以便更简洁地遍历值的一个序列。这条语句的语法如下：

``````for <variable> in <iterable object>:
<sequence of statements>
``````

``````product = 1
for value in range(1, 11):
product *= value
print(product)
``````

Python 程序员通常更喜欢使用一个 for 循环来遍历确定的范围的值或值的序列。当继续循环的条件是一个任意的布尔表达式的时候，程序员则使用 while 循环。

### 3字符串及其运算

#### 运算符

+运算符构建并返回一个新的字符串，它包含了两个运算数中的字符。

``````"greater"[0] # Returns "g"
``````

``````<a string>[<lower>:<upper>]
``````

``````"greater"[:] # Returns "greater"
"greater"[2:] # Returns "eater"
"greater"[:2] # Returns "gr"
"greater"[2:5] # Returns "eat"
``````

### 对象和方法调用

``````<object>.<method name>(<list of arguments>)
``````

``````"greater".isupper() # Returns False
"greater".upper() # Returns "GREATER"
"greater".startswith("great") # Returns True
``````

``````len("greater") # Is equivalent to "greater".__len__()
"great" + "er" # Is equivalent to "great".__add__("er")
"e" in "great" # Is equivalent to "great".__contains__("e")
``````

# 4内建 Python 集合及其操作

### 列表

``````[] # An empty list
["greater"] # A list of one string
["greater", "less"] # A list of two strings
["greater", "less", 10] # A list of two strings and an int
["greater", ["less", 10]] # A list with a nested list
``````

``````testList = [] # testList is []
testList.append(34) # testList is [34]
testList.append(22) # testList is [34, 22]
testList.sort() # testList is [22, 34]
testList.pop() # Returns 22; testList is [34]
testList.insert(0, 22) # testList is [22, 34]
testList.insert(1, 55) # testList is [22, 55, 34]
testList.pop(1) # Returns 55; testList is [22, 34]
testList.remove(22) # testList is [34]
testList.remove(55) # raises ValueError
``````

``````"Python is cool".split() #Returns[’Python’,’is’,’cool’]
" ".join(["Python","is","cool"]) #Returns’Python is cool’
``````

### 遍历序列

for 循环用来遍历一个序列（如字符串、列表或元组）中的项。例如，如下的代码段输出一个列表中的项：

``````testList = [67, 100, 22]
for item in testList:
print(item)
``````

``````testList = [67, 100, 22]
for index in range(len(testList)):
print(testList[index])
``````

### 字典

``````{} # An empty dictionary
{"name":"Ken"} # One entry
{"name":"Ken", "age":61} # Two entries
{"hobbies":["reading", "running"]} # One entry, value is a list

dic = {"name":"Ken", "age":61}
for key,value in dic.items():
print(key, value)
``````

# 5 函数

### 函数定义

Python 函数的定义语法是：

``````def <function name>(<list of parameters>):
<sequence of statements>
``````

``````def square(n):
"""Returns the square of n."""
result = n ** 2
return result
``````

``````first() # Raises a NameError (function undefined yet)
def first():
second() # Not an error, because not actually
print("Calling first.") # called until after second is defined
def second():
print("Calling second.")
first() # Here is where the call should go
``````

### 递归函数

``````def displayRange(lower, upper):
"""Outputs the numbers from lower to upper."""
while lower <= upper:
print(lower)
lower = lower + 1
``````

• 当 lower<=upper 的时候，循环体继续执行；
• 当函数执行的时候，lower 增加 1，但是 upper 不变。
等价的递归函数可以执行类似的基本操作，但是，用一条 if 语句替代了循环，用函数的递归调用替代了赋值语句。如下是做出这些修改后的代码：
``````def displayRange(lower, upper):
"""Outputs the numbers from lower to upper."""
if lower <= upper:
print(lower)
displayRange(lower + 1, upper)
``````

``````def ourSum(lower, upper):
"""Returns the sum of the numbers from lower thru upper."""
if lower > upper:
return 0
else:
return lower + ourSum(lower + 1, upper)
``````

### 类和对象

``````def <class name>(<parent class name>):
<class variable assignments>
<instance method definitions>
``````

``````"""
File: counter.py

Defines a Counter class for counting.
"""

class Counter(object):
"""Models a counter."""

# Class variable
instances = 0

#Constructor
def __init__(self):
"""Sets up the counter."""
Counter.instances += 1
self.reset()

# Mutator methods
def reset(self):
"""Sets the counter to 0."""
self._value = 0

def increment(self, amount = 1):
self._value += amount

def decrement(self, amount = 1):
"""Subtracts amount from the counter."""
self._value -= amount

# Accessor methods
def getValue(self):
"""Returns the counter's value."""
return self._value

def __str__(self):
"""Returns the string representation of the counter."""
return str(self._value)

def __eq__(self, other):
"""Returns True if self equals other

or False otherwise."""
if self is other: return True
if type(self) != type(other): return False
return self._value == other._value
``````

``````>>>from counter import Counter
>>>c1=Counter()
>>>print(c1)
0
>>>c1.getValue()0
>>>str(c1)
’0’
>>>c1.increment()
>>>print(c1)
1
>>>c1.increment(5)
>>>print(c1)
6
>>>c1.reset()
>>>print(c1)
0
>>>c2=Counter()
>>>Counter.instances
2
>>>c1==c1
True
>>>c1==0
False
>>>c1==c2
True
>>>c2.increment()
>>>c1==c2
False
>>>
``````

increment 和 decrement 方法使用默认的参数，这允许程序员来选择指定还是不指定这个量。Counter 类中的str方法覆盖了 object 类中的相同的方法。当把对象作为参数传递给 str 函数的时候，python 在该对象上运行str。当在一个对象上运行一个方法的时候，Python 首先在该对象自己的类中查找该方法的代码。如果没有在那里找到这个方法，Python 会在其父类中查找，依次类推。如果最终没有找到该方法的代码（在 object类中查找完了之后），Python 会抛出一个异常。

# 文件操作

### 文本文件的输出

``````34.6 22.33 66.75
77.12 21.44 99.01
``````

``````>>>f=open("myfile.txt",’w’)
``````

``````>>> f.write("First line.\nSecond line.\n")
``````

``````>>> f.close()
``````

### 将数字写入到一个文本文件

``````import random

f=open("integers.txt",'w')
for count in range(500):
number = random.randint(1, 500)
f.write(str(number) + "\n")
f.close()
``````

### 从文本文件读取文本

``````>>>f=open("myfile.txt",’r’)
``````

``````>>> text=f.read()
>>> text
’First line. \nSecond line. \n’
>>>print(text)
First line.
Second line.
>>>
``````

``````>>>f=open("myfile.txt",’r’)
>>>for line in f:
print(line)
First line.
Second line.
>>>
``````

``````>>>f=open("myfile.txt",’r’)
>>> while True:
if line == "":
break
print(line)

First line.
Second line.
>>>
``````

## python编程练习题

1.有一分数序列：2/1，3/2，5/3，8/5，13/8，21/13…求出这个数列的前20项之和。

``````from functools import reduce

def cal_sum():
fenzi = 2
fenmu = 1
lst = [2]
for i in range(1,20):
fenmu,fenzi= fenzi,fenmu+fenzi
lst.append(fenzi / fenmu)

return reduce(lambda x,y:x+y,lst)

print(cal_sum())
``````

2.给一个不多于5位的正整数，要求：一、求它是几位数，二、逆序打印出各位数字。

``````def num_reverse(num):
print(' '.join(str(num)))
numLen = len(str(num))
print(numLen)
for i in range(numLen):
toPrint = num % 10
num = int((num - toPrint)/10)
print(toPrint,end=' ')

num_reverse(9523684)
``````
1. 有n个人围成一圈，顺序排号。从第一个人开始报数（从1到3报数），凡报到3的人退出圈子，问最后留下的是原来第几号的那位。
``````def who_remain(n):
lst = list(range(1, n+1))
while n > 2:
lst.pop(2)
before = lst[:2]
lst = lst[2:]
lst.extend(before)
n = len(lst)
return lst[-1]
print(who_remain(29))
``````

4.题：编写一个程序，根据控制台输入的事务日志计算银行帐户的净金额。 事务日志格式如下所示：
D 100
W 200

D表示存款，而W表示提款。

D 300
D 300
W 200
D 100

500

``````netAmount = 0
while True:
print("请输入：")
s = input()
if not s:
break
values = s.split(" ")
operation = values[0]
amount = int(values[1])
if operation=="D":
netAmount+=amount
elif operation=="W":
netAmount-=amount
else:
pass
print (netAmount)

``````

5.机器人从原点（0,0）开始在平面中移动。 机器人可以通过给定的步骤向上，向下，向左和向右移动。 机器人运动的痕迹如下所示：
UP 5
DOWN 3
LETF 3
RIGHT 2

UP 5
DOWN 3
LETF 3
RIGHT 2

``````import math

pos = [0, 0]
print("请输入：")
while True:
s = input()
if not s:
break
movement = s.split(" ")
direction = movement[0]
steps = int(movement[1])
if direction == "UP":
pos[0] += steps
elif direction == "DOWN":
pos[0] -= steps
elif direction == "LEFT":
pos[1] -= steps
elif direction == "RIGHT":
pos[1] += steps
else:
pass

print(int(round(math.sqrt(pos[1] ** 2 + pos[0] ** 2))))

``````

### python字符串练习题

1.判断用户输入的变量名是否合法:
1.变量名可以由字母,数字或者下划线组成
2.变量名只能以字母或者下划线开头

1.判断变量名的第一个元素是否为字母或者下划线 s[0]
2.如果第一个元素符合条件,判断除了第一个元素之外的其他元素s[1:]

image.png
``````while True:
s = input('变量名:')
if s == 'q':
exit()
# 判断首字母是否符合变量名要求
if s[0] == '_' or s[0].isalpha():
# 依次判断剩余的所有字符
for i in s[1:]:
# 只要有一个字符不符合,便不是合法的变量;alnum表示字母或数字
if not (i.isalnum() or i == '_'):
print('%s不是一个合法的变量名' % s)
break
else:
print('%s是一个合法的变量名' % s)
else:
print('%s不是一个合法的变量名' % s)

``````

2.给定一个字符串来代表一个学生的出勤纪录，这个纪录仅包含以下三个

'A' : Absent，缺勤
'L' : Late，迟到
'P' : Present，到场

image.png
``````print("""
出勤记录规则
'A' : Absent   缺勤
'L' : Late     迟到
'P' : Present  到场
""")

while True:
c = input('请输入考勤记录:')

# count() 表示指定字符出现的次数
if c.count('A') <= 1 and c.count('LLL') == 0 and c != 'q':
print('True')
elif c == 'q':
exit()
else:
print('False')

``````

3.输入两个字符串，从第一字符串中删除第二个字符串中所有的字符。例

• 输入描述:
每个测试输入包含2个字符串

• 输出描述:
输出删除后的字符串

• 示例1:

They are students.
aeiou

Thy r stdnts.

image.png
``````s1 = input('s1:')
s2 = input('s2:')
# 遍历字符串s1
for i in s1:
#  依次判断s1中的每个字符是否在s2中
if i in s2:
# replace 表示替换;
# 将s1中与s2中相同的所有字符,替换为空字符
s1 = s1.replace(i,'')
print(s1)

``````

### python集合综合练习

1.地铁站编号和站名对应关系如下：
1=朱辛庄
2=育知路
3=平西府
4=回龙观东大街
5=霍营
//....

//...

2.计算地铁票价规则：

3站以上但不超过5站（包含5站）的收费4元，
5站以上的，在4元的基础上，每多1站增加2元，
10元封顶；

3.打印格式（需要对键盘录入的上车站和到达站进行判断，如果没有该站，提示重新输入，直到站名存在为止）：

``````
st = """十三号街站   05:30   23:00   ——  ——

lst = st.split()

llsstt = list(filter(lambda x : '站' in x,lst))
print(llsstt)

while True:
upstation = input('请输入上车站：')
if upstation not in llsstt:
print(f'您输入的上车站：{upstation}不存在，请重新输入上车站')

upstation_idx = llsstt.index(upstation)

downstation = input('请输入下车站：')
if downstation not in llsstt:
print(f'您输入的下车站：{upstation}不存在，请重新输入下车站')
else:
downstation_idx = llsstt.index(downstation)
if downstation_idx < upstation_idx:
print('下车站必须在上车站之后')
else:
break

diff = downstation_idx - upstation_idx
price = 0
if diff <= 3:
price = 3
elif diff <= 5:
price = 4
else:
price = 4 + (diff - 5)*2

if price > 10:
price = 10

print(f'从{upstation}到{downstation}共经过{diff}站收费{price}元，大约需要{diff*2}分钟')

``````

### python函数综合练习

1.编写一个函数cacluate, 可以接收任意多个数,返回的是一个元组.

image.png
``````# 1.定义函数; *args:可变参数
def cacluate(*args):
# 2.计算平均值; args的数据类型为元组,sum求和
average = sum(args) / len(args)
# 3.将所有大于平均值数的值存入列表
list=[]
for i in args:
if i > average:
list.append(i)
# 4.将平均值和列表元素存入元组
tuple=(average,list)
return tuple

print(cacluate(1,1,2,3,4))

``````

2.编写一个函数, 接收字符串参数, 返回一个元组,

image.png

``````# 直接在函数里print输出,在调用函数时只能打印不能使用
# 如果想要使用函数里的变量值，此时需要在定义函数时用return返回函数值

def fun(c):
# 记录大写字母个数
upper = 0
# 记录小写字母个数
lower = 0
# 统计大小写字母的个数
for i in c:
if i.isupper():
upper += 1
# 注意:不能用else,因为字符串之间有空格
if i.islower():
lower += 1
tuple = (upper,lower)
# 函数返回值
return tuple

# 此时直接调用函数将不会有输出值，必须用print输出
print(fun(input('请输入字符串:')))

``````

3.编写函数, 接收一个列表(包含30个1~100之间的随机整形数)

- 将列表下标k之前对应(不包含k)的元素逆序;
- 将下标k及之后的元素逆序;

``````# 导入生成随机数的包
import random

# 定义空列表
list = []
# 生成30个随机数
for i in range(30):
num = random.randint(1,100)
# 将生成的随机数添加到列表中
list.append(num)
# 打印原始列表
print(list)

# 定义函数
def fun(list,k):
# k表示下标
if k < 0 or k >= len(list):
print('error key')
else:
# [:k] k之前的元素   [::-1] 逆序   + 连接
return list[:k][::-1] + list[k:][::-1]

print(fun(list,3))

``````

4.模拟轮盘抽奖游戏

``````import random

# 定义(得奖情况)字典
rewardDict ={'一等奖':(0,0.08),'二等奖':(0.08,0.3),'三等奖':(0.3,1.0)}

# 判断用户是否得奖
def rewardfun():
num = random.random()
# 遍历key-value
for k,v in rewardDict.items():
if num >= v[0] and num < v[1]:
return k

# 定义空字典
resultDict = {}

# 将得奖记录添加到字典中,记录1000人玩游戏的得奖情况
for i in range(1000):
# 将函数的返回值赋给reskey
reskey = rewardfun()
# print(reskey)
if reskey not in resultDict:
# 增加元素
resultDict[reskey] = 1
else:
resultDict[reskey] += 1

# 遍历输出字典的 key-value值
for k,v in resultDict.items():
print(k,'---->',v)

``````

5.题目需求:

f(13) = 12 + 32 = 10
f(207) = 22 + 02 + 72 = 53

f(n)=n

*18, a<=b;

``````k=51
a=5000
b=10000
7293 143
7854 154
7905 155
3
``````
``````# 1.接收用户输入
k = int(input('k='))
a = int(input('a='))
b = int(input('b='))

# 2.定义函数,计算f
def fun(c):
f = 0
for i in str(c):
f += int(i)**2
return f

# fun(207)

# 定义计数器
count = 0

# 3.统计满足条件的n的个数
for n in range(a,b+1):
if k * fun(n) == n:
print(n,fun(n))
count += 1
# 打印个数
print(count)

``````