1.简介
2.变量、运算符与数据类型
1. 注释
注释有单行注释和多行注释 下面展示一些 内联代码片 。
#这是一个单行注释
'''
这里面是多行注释
'''
2. 运算符
运算符有以下几种: 算术运算符 比较运算符 逻辑运算符:and,or,and 位运算符 三元运算符
x, y = 4, 5
small = x if x < y else y
print(small) # 4
其他运算符:in,not in,is,not is 注意:
- is, is not 对比的是两个变量的内存地址
- 比较的两个变量,指向的都是地址不可变的类型(str等),那么is,is not 和 ==,!= 是完全等价的
- 对比的两个变量,指向的是地址可变的类型(list,dict,tuple等),则两者是有区别的
比如
比较的两个变量均指向不可变类型
a = "hello"
b = "hello"
print(a is b, a == b) # True True
print(a is not b, a != b) # False False
比较的两个变量均指向可变类型
a = ["hello"]
b = ["hello"]
print(a is b, a == b) # False True
print(a is not b, a != b) # True False
3. 变量和赋值
1.在使用变量之前,需要对其先赋值。 2.变量名可以包括字母、数字、下划线、但变量名不能以数字开头。 3.Python 变量名是大小写敏感的,foo != Foo。
4. 数据类型与转换
查看数据类型用type函数
a = 1031
print(a, type(a))
如果要判断两个类型是否相同推荐使用 isinstance()
print(isinstance(1, int)) # True
print(isinstance(5.2, float)) # True
print(isinstance(True, bool)) # True
print(isinstance('5.2', str)) # True
类型转换
1.转换为整型 int(x, base=10) 2.转换为字符串 str(object=’’) 3.转换为浮点型 float(x)
5. print()函数
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
如果print没有参数,默认每次输出后会换行,如果不想要换行,可以加上end参数
3.位运算
1. 原码、反码和补码
2. 按位运算
3. 利用位运算实现快速计算
4. 利用位运算实现整数集合
4.条件语句
1. if 语句
if 2 > 1 and not 2 > 3:
print('Correct Judgement!')
2. if - else 语句
temp = input("猜一猜小姐姐想的是哪个数字?")
guess = int(temp)
if guess == 666:
print("你太了解小姐姐的心思了!")
print("哼,猜对也没有奖励!")
else:
print("猜错了,小姐姐现在心里想的是666!")
print("游戏结束,不玩儿啦!")
3. if - elif - else 语句
temp = input('请输入成绩:')
source = int(temp)
if 100 >= source >= 90:
print('A')
elif 90 > source >= 80:
print('B')
elif 80 > source >= 60:
print('C')
elif 60 > source >= 0:
print('D')
else:
print('输入错误!')
4. assert 关键词
在进行单元测试时,可以用来在程序中置入检查点,只有条件为 True 才能让程序正常工作。
assert 3 > 7
5.循环语句
1. while 循环
count = 0
while count < 3:
temp = input("猜一猜小姐姐想的是哪个数字?")
guess = int(temp)
if guess > 8:
print("大了,大了")
else:
if guess == 8:
print("你太了解小姐姐的心思了!")
print("哼,猜对也没有奖励!")
count = 3
else:
print("小了,小了")
count = count + 1
print("游戏结束,不玩儿啦!")
2. while - else 循环
count = 0
while count < 5:
print("%d is less than 5" % count)
count = count + 1
else:
print("%d is not less than 5" % count)
count = 0
while count < 5:
print("%d is less than 5" % count)
count = 6
break
else:
print("%d is not less than 5" % count)
3. for 循环
member = ['张三', '李四', '刘德华', '刘六', '周润发']
for each in member:
print(each)
dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
for key, value in dic.items():
print(key, value, sep=':', end=' ')
dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
for key in dic.keys():
print(key, end=' ')
4. for - else 循环
for num in range(10, 20):
for i in range(2, num):
if num % i == 0:
j = num / i
print('%d 等于 %d * %d' % (num, i, j))
break
else:
print(num, '是一个质数')
5. range() 函数
for i in range(2, 9):
print(i)
6. enumerate()函数
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
lst = list(enumerate(seasons))
print(lst)
lst = list(enumerate(seasons, start=1))
print(lst)
for i, language in enumerate(languages, 2):
print(i, 'I love', language)
print('Done!')
7. break 语句
import random
secret = random.randint(1, 10)
while True:
temp = input("猜一猜小姐姐想的是哪个数字?")
guess = int(temp)
if guess > secret:
print("大了,大了")
else:
if guess == secret:
print("你太了解小姐姐的心思了!")
print("哼,猜对也没有奖励!")
break
else:
print("小了,小了")
print("游戏结束,不玩儿啦!")
8. continue 语句
for i in range(10):
if i % 2 != 0:
print(i)
continue
i += 2
print(i)
9. pass 语句
def a_func():
pass
10. 推导式
x = [(i, i ** 2) for i in range(6)]
print(x)
a = (x for x in range(10))
print(a)
print(tuple(a))
b = {i: i % 2 == 0 for i in range(10) if i % 3 == 0}
print(b)
c = {i for i in [1, 2, 3, 4, 5, 5, 6, 4, 3, 2, 1]}
print(c)
s = sum([i for i in range(101)])
print(s)
s = sum((i for i in range(101)))
print(s)
6.异常语句
1. Python 标准异常总结
2. Python 标准警告总结
3. try - except 语句
try:
f = open('test.txt')
print(f.read())
f.close()
except OSError:
print('打开文件出错')
try:
int("abc")
s = 1 + '1'
f = open('test.txt')
print(f.read())
f.close()
except OSError as error:
print('打开文件出错\n原因是:' + str(error))
except TypeError as error:
print('类型出错\n原因是:' + str(error))
except ValueError as error:
print('数值出错\n原因是:' + str(error))
4. try - except - finally 语句
def divide(x, y):
try:
result = x / y
print("result is", result)
except ZeroDivisionError:
print("division by zero!")
finally:
print("executing finally clause")
5. try - except - else 语句
try:
fh = open("testfile.txt", "w")
fh.write("这是一个测试文件,用于测试异常!!")
except IOError:
print("Error: 没有找到文件或读取文件失败")
else:
print("内容写入文件成功")
fh.close()
6. raise语句
try:
raise NameError('HiThere')
except NameError:
print('An exception flew by!')
|