# -*- coding:utf-8 -*-
变量
关键字
输出
输入
# 表达式的计算直接就使用 eval(),简单方便好使
>>> a = 123
>>> b = eval(input())
a * 2
>>> b
246
算数运算符
>>> a = 12.5
>>> b = 2
>>> a % b
0.5
>>> a / b
6.25
>>> a // b
6.0
>>> a ** b
156.25
>>> b ** a
5792.618751480198
>>> -15 % -2 # 余数的正负,跟随 % 后数的正负
-1
>>> 15 % -2
-1
>>> -15 % 2
1
>>> 15 % 2
1
比较运算符
赋值运算符
位运算符
逻辑运算符和成员运算符
身份运算符
运算符优先级
$\quad\quad\quad\quad\quad$
注意 : 冒号
理论讲解
import random as rd
‘‘‘
规则: 剪刀(0),石头(1),布(2),退出(3),其他输入都是不合法
首先是一个while循环,然后不断的接收输入的数据,
输入数据合法
是退出信号
直接退出
石头剪刀布
我们的random数据做比较,输出你赢了,你输了,是平局
输入不合法
要求重新输入,并说出游戏规则
‘‘‘
gesture = ["石头", "剪刀", "布"];
while True:
print(‘--------------------------------------------------------‘);
_data = input(‘规则: 剪刀(0),石头(1),布(2),退出(3),其他输入都是不合法\n请输入数据:‘)
_rdm = rd.randint(0, 2);
if _data == ‘0‘ or _data == ‘1‘ or _data == ‘2‘: # 合法的正确输入,和随机数比大小
_data = int(_data);
print(‘玩家出的是%s‘ % gesture[_data]);
print(‘电脑出的是%s‘ % gesture[_rdm]);
if _data == _rdm:
print("双方平局");
elif _data == 0 and _rdm == 2 or _data == _rdm + 1:
print(‘玩家赢了‘);
else:
print(‘玩家输了‘);
elif _data == ‘3‘: # 游戏退出
print(‘游戏结束‘);
break;
else: # 非法输入
print(‘输入数据错误,请重新输入‘);
continue;
for循环形式
借助range()
for i in range(5): # 输出的是 0~4,不会到5的
print(i);
for i in range(1, 6, 2): # 输出的是1, 3, 5
print(i);
用于列表和字符串
name = ‘tengzhou‘
for i in name: #会把 tenghzhou 在一行输出
print(i, end=‘‘);
while循环形式
练习1~n的累加和,和偶数的 累加和
n = 100;
sum_all = 0; sum_even = 0; i = 1;
while i <= n:
sum_all += i; # 任意数
if (i & 1) == 0: # 偶数
sum_even += i;
i += 1
print(‘1~100的数字和为:‘, sum_all);
print(‘1~100的偶数和为:‘, sum_even);
break, continue, pass语句
break, continue, pass的区别与联系
练习打印九九乘法表
i = 1;
j = 1;
# 打印 i * j
# i 作为外层循环,j 作为内层循环
while i <= 9:
j = 1;
while j <= i:
if j < i:
print("%d * %d = %2d" % (i, j, i * j), end = ‘, \t‘);
else:
print("%d * %d = %2d" % (i, j, i * j));
j += 1;
i += 1;
String字符串
单引号、双引号、三引号选取的区别与联系 <\font>
下面我们给出几个例子来看出使用单引号和双引号的区别
example 1: 字符串 I‘am a student
example 2:字符串 Tom said "I like you"
三引号的应用:可以不在一行
下面看一下在代码中的显示
其中str1=str2, str3 = str4, s1=s2=s3=s4
# 单引号的和双引号的区别,关键在于转义字符
str1 = ‘I\‘am a student‘;
str2 = "I‘am a student";
str3 = ‘She said "I like you"‘;
str4 = "She said \"I like you\""
print(‘str1=‘, str1);
print(‘str2=‘, str2);
print(‘str3=‘, str3);
print(‘str4=‘, str4);
# 三引号
s1 = ‘‘‘line1
line2‘‘‘
s2 = ‘line1\nline2‘
s3 = "line1\nline2"
s4 = ‘line1\nline2‘
print(‘s1=‘, s1);
print(‘s2=‘, s2);
print(‘s3=‘, s3);
print(‘s4=‘, s4);
转义字符
字符串的截取与连接
# 字符串的截取与连接
str = "shandong"
print(str); # 输出字符串
print(str[:]); # 输出字符串
print(str[0:]) # 输出字符串
print(str[0:-1]); # 输出字符串0到倒数第二个
print(str[0]); # 输出第0个字符, 从0开始计数
print(str[2:5]); # 输出第2个到第4个字符,从0开始计数
print(str[2:]); # 输出第2个到最后
print(str * 2); # 输出两遍
print(str + ‘tengzhou‘) # 字符串连接后输出
print(str[:5]); # 输出从第0个到第5个字符
print(str[0:7:2]); # [起始:终止:步长]-->[st:step:ed],注意是取不到 ed 的
print(‘------------------------------‘);
print(‘hello\nshandong‘);
print(r‘hello\npython‘); # 在字符串面前加一个 r 表示原始字符串,不会发生转义。
字符串的常见操作
列表的定义与访问
详情请看下面的代码示例
test_list = [‘shanghai‘, ‘beijing‘, "hunan", 123];
for x in test_list: # 输出形式 1
print(x);
for i in range(len(test_list)): # 输出形式 2
print(test_list[i]);
列表的常用操作
列表的嵌套
import random
offices = [[], [], []]; # 三个办公室
teacher = [‘A‘, ‘B‘, ‘C‘, ‘D‘, ‘E‘, ‘F‘, ‘G‘, ‘H‘]; # 8个教室
for tea_name in teacher:
tmp = random.randint(0, 2);
offices[tmp].append(tea_name);
i = 1;
for off in offices:
print(‘办公室%d有%d人‘%(i, len(off)), end=‘\n\t‘);
for tea in off:
print(tea, end=‘ ‘);
print(‘‘);
print(‘-‘* 10);
i += 1;
编程作业
作业的实现的代码如下:
# 商品数据定义
products = [["iphone", 6888], ["MacPro", 14800], ["XiaoMin6", 2499],
["Coffee", 31], ["Book", 60], ["Nike", 699]];
# 商品显示
i = 0;
print(‘-‘*6, ‘ 商品列表 ‘, ‘-‘*6);
for goods in products:
print(‘%d\t‘%i, goods[0], ‘\t‘, goods[1]);
i += 1;
# 商品购买的循环
buy_goods = [];
while True:
tmp = input(‘请输入商品标号,或者是输入q退出\n‘);
if tmp == ‘q‘:
print(‘退出成功‘);
break;
elif tmp.isnumeric():
tmp = eval(tmp);
if tmp < 0 or tmp >= len(products):
print(‘数据输入错误,请重新输入‘);
continue;
else:
buy_goods.append(products[tmp]);
else:
print(‘数据输入错误,请重新输入‘);
continue;
# 打印购买的商品和总价
print(‘-‘*6, ‘ 购买的商品为 ‘, ‘-‘*6);
money = 0;
for goods in buy_goods:
print(‘%s\t%d‘%(goods[0], goods[1]));
money += goods[1];
print(‘总价=%d‘%money);
代码尝试:
my_tuple = ([1, 2, 3],);
for i in my_tuple: # 原本 tuple 元素的遍历输出
print(i);
my_tuple[0].append(2); # 添加的新元素
for i in my_tuple: # 原本 tuple 元素的遍历输出
print(i);
for i in my_tuple: # 标签指的是一个地方,是被删除的!!,相当于引用
i.pop();
for i in my_tuple:
print(i);
结果
[1, 2, 3]
[1, 2, 3, 2]
[1, 2, 3]
元组的定义和访问
# 创建空元祖
tuple1 = ();
# 创建仅仅一个元素的元组
tuple1 = (2, ); # 注意,元组指向内存单元的内容不可以改,但是变量作为便签是可以指向其他地方的
int1 = (2); # 这个不加逗号的不是元组,是一个整数表达式
# 元组的访问
tuple1 = (‘Google‘, ‘baidu‘, 2000, 2020);
tuple2 = (1, 2, 3, 4, 5, 6, ); # 这个后面的逗号是可加可不加的
print("tuple1[0]=%s"%tuple1[0]);
print("tuple1[2]=%d"%tuple1[2]);
print("tuple1[2]=%s"%tuple1[2]);
print(‘%s‘%1); # 整数也是可以直接 %s 转换为 string 类型的
print(str(1));
print(‘tuple2[1~5]:‘, tuple2[1:5]);
# 假设元组某个元素是可变类型list,我们看看list是否可以正常修改 --> 是可以正常修改的
tup3 = ([0], );
print(type(tup3));
for x in tup3:
print(x);
x.extend([2, 3, 4, 5, 6]);
x.pop();
for y in tup3:
print(y);
# 尝试修改其他的
tup1 = (12, 34.56);
tup2 = (‘abc‘, ‘xyz‘);
# 下面的操作是非法的
# tup1[0] += 2;
# 我们可以进行元组的连接
tup3 = tup1 + tup2;
for i in tup3:
print(i);
# 我们释放一下tup1内存试一试
del tup1
print(tup3); # 这个是ok的,所以说tup3是新开的内存
print(‘-‘ * 6);
‘‘‘ 都报错,说明还是别用了,释放之后,在为重新赋值之前就别用。
i = tup1;
print(‘1‘, type(i));
# print(tup1); # 什么都输出不了了,被释放了
‘‘‘
常用操作
操作名称 | 操作方法 | 举例 |
---|---|---|
元组的加法操作 | + | tup3 = tup1 + tup2 |
# 字典的测试
d = {‘Mich‘:99, ‘aadf‘:25, 123:24, 25:[123, ]} #[123,]:10不行,但是10:[123, ]是可以的,即key不可变,val可变
print(d[‘Mich‘])
print(d[123]) # 后面的会覆盖前面的
字典的定义与访问
info = {‘name‘:‘小妖怪‘, ‘age‘:21};
print(info[‘name‘]);
print(info[‘age‘]);
# print(info[‘sex‘]); # 不存在会报错
# 使用 get 成员函数
x = info.get(‘sex‘);
print(x);
print(type(x));
print(info.get(‘sex‘, ‘啥也没有‘))
常用操作
set1 = set([1, 2, 3, 4, 4, 0, 1, 2]);
for i in set1:
print(‘%d ‘%i, end=‘‘);
set1.add(‘adf‘); # 只能加一个
# set1.add([‘adfa‘, ‘dfa‘]) 应该是不能加可变类型list
set1.add((‘adfa‘, ‘dfa‘)) # 但是可以加元组 tuple
set1.update(set([5, 6, 7 , 8])); # 这个加的是一个集合
print(‘‘)
for i in set1:
print(i, end=‘ ‘);
常用操作
def 函数名():
代码
demo:
def printInfo():
print(‘-‘ * 6);
print(‘python 永远滴神‘);
print(‘-‘ * 6);
if __name__ == ‘__main__‘:
printInfo()
cmd的执行结果
demo代码如下
def mul(a, b):
print(‘%d*%d=%d‘%(a, b, a * b));
return;
if __name__ == ‘__main__‘:
mul(5, 2);
def divide(a, b):
return a//b, a%b;
if __name__ == ‘__main__‘:
print(divide(100, 3));
x, y = divide(100, 3);
print(‘x=%d, y=%d‘%(x, y))
运行结果:
课堂练习
代码
# 打印一条线的函数,默认含有 6 个‘-‘
def print_One_Line(cnt = 6):
print(‘-‘ * cnt);
return;
# 默认打1行,1行6个
def print_Line(a = 1, b = 6):
for i in range(a):
print_One_Line(b);
return;
# 三个数字的和
def three_sum(a, b, c):
return a + b + c;
# 三个数字的平均数值
def three_ave(a, b, c):
return three_sum(a, b, c) / 3;
# 主函数起始点,调用自定义函数
if __name__ == ‘__main__‘:
print_One_Line();
print_Line(5);
print(three_sum(1, 2, 3));
print(three_ave(1, 2, 3));
print(type(three_ave(1, 2, 3)));
附示例代码:
# 局部变量修改
def local_var_func():
print(‘-‘ * 8)
a = 5 # 因为后面有赋值,所有说是局部变量,局部变量必须在前面就有赋值,要在用 a 之前
print(‘before : a = %d‘ % (a))
a = 200
print(‘after : a = %d‘ % (a))
print(‘-‘ * 8)
# 全局变量修改
def global_var_func():
print(‘-‘ * 8)
global a # 全局变量必须要提前说,否则有问题,在 用 a 之前
print(‘before : a = %d‘ % (a))
a = 300
print(‘after : a = %d‘ % (a))
print(‘-‘ * 8)
a = 100 # 全局变量
# 主要是开始位置
if __name__ == ‘__main__‘:
# global a 有了会报错,默认是这个 global
print(‘main a = %d‘%a)
a = 1010
print(‘main a = %d‘ % a)
local_var_func()
print(‘after local : main a = %d‘ % a)
global_var_func()
print(‘after global : main a = %d‘ % a)
# 打开文件
f = open(‘test1.txt‘, ‘w‘); # 打开方式可以有很多,如上整理所示
# 关闭文件
f.close()
使用write写数据
$f.write(‘写入内容‘)$
demo:
# 打开文件
f = open(‘test1.txt‘, ‘w+‘); # 打开方式可以有很多
# 文件写入
f.write(‘this is write thing!!!!!‘) # 不会像 print 一样默认加 \n
# 关闭文件
f.close()
使用read读数据
demo:
# 打开文件
f = open(‘test1.txt‘, ‘r‘); # 打开方式可以有很多
# 文件读取
context = f.read(5)
print(context)
context = f.read()
print(context)
# 关闭文件
f.close()
readlines读数据
# 打开文件
f = open(‘test1.txt‘, ‘r‘); # 打开方式可以有很多
# 文件读取
context = f.readlines()
print(type(context))
print(context)
for i in context:
print(i, end=‘‘) # 注意我们的一行字符串已经包含 \n 了,输出的时候注意格式,可以把print 里面的\n给去掉
# 关闭文件
f.close()
结果展示
<class ‘list‘>
[‘123456789\n‘, ‘abc\n‘, ‘def\n‘, ‘ghi‘]
123456789
abc
def
ghi
readline读数据
# 打开文件
f = open(‘test1.txt‘, ‘r‘); # 打开方式可以有很多
# 文件读取
context = f.readline()
print(type(context))
i = 0
while context != ‘‘:
i += 1
print(‘i=%d:%s‘%(i, context), end=‘‘) # 同理,end 不要 \n,要换成空串
context = f.readline()
if context == ‘‘:
break
# 关闭文件
f.close()
运行结果:
<class ‘str‘>
i=1:123456789
i=2:abc
i=3:def
i=4:ghi
linecache模块输出特定行
$text=linecache.getline(‘filename‘, lineCnt)$
import linecache
text = linecache.getline(‘test1.txt‘, 2)
print(‘-‘ * 6)
print(text, end=‘‘)
print(‘-‘ * 6)
运行结果:
------
abc
------
基本都是调用 $OS$模块中的部分函数完成
文件重命名
倘若不在当前路径下,需要给他加全
import os
os.rename(‘D:\\pythonTry\\test.txt‘, ‘D:\\pythonTry\\test2.txt‘)
文件的删除
倘若不在当前路径下,需要给他加全
import os
os.remove(‘D:\\pythonTry\\test2.txt‘)
创建文件夹
倘若不在当前路径下,需要给他加全路径的位置
import os
os.mkdir(‘D:\\PythonTry\\test2‘) # 在 D:\pythonTry这里加一个名字为 test2的文件夹
获取当前目录(路径)
import os
print(os.getcwd())
获取目录列表
返回值是一个列表,内容是当前目录下的内容
import os
print(os.listdir("./"))
print(os.listdir("D:\\pythontry"))
结果输出:
[‘.idea‘, ‘2021_matplotlibOne.py‘, ‘2021_matplotlibTwo.py‘, ‘t1.png‘, ‘test2.txt‘]
[‘lessonOne11_8‘, ‘test1‘, ‘test2‘, ‘test2.txt‘]
改变默认目录
import os
print(os.getcwd()) # 查看当前路径
os.chdir(‘../‘) # 返回上一级
print(os.getcwd()) # 查看当前路径
os.chdir(‘D:\\PythonTry\\test1‘) # 返回特定路径
print(os.getcwd()) # 查看当前路径
结果显示
D:\PythonTry\test1
D:\PythonTry
D:\PythonTry\test1
删除文件夹
import os
os.rmdir(‘D:\\pythontry\\test2‘)
经典的语法示例
try:
<语句> #运行别的代码
except <名字>:
<语句> #如果在try部份引发了‘name‘异常
except <名字>,<数据>:
<语句> #如果引发了‘name‘异常,获得附加的数据
else:
<语句> #如果没有异常发生
下面我们以打开文件失败出现的 IOError示例
try:
f = open("D:\\pythontry\\123.txt", ‘r‘);
context = f.readlines();
for u in context:
print(u, end=‘‘);
except IOError: # 当不存在该文件,或者是无法打开时
print(‘文件打不开‘)
下面介绍几种常见的Error
详细查看链接:https://www.cnblogs.com/smilelin/p/11451581.html
TypeError:类型错误,对象用来表示值的类型非预期类型时发生的错误
AttributeError:属性错误,特性引用和赋值失败时会引发属性错误
NameError:试图访问的变量名不存在。
SyntaxError:语法错误,代码形式错误
KeyError:在读取字典中的key和value时,如果key不存在,就会触发KeyError错误。
IndexError:索引错误,使用的索引不存在,常索引超出序列范围,序列中没有此索引(index)
IndentationError:缩进错误
TabError: Tab 和空格混用
原文:https://www.cnblogs.com/lucky-light/p/14446766.html