修订日期 | 内容 |
---|---|
2021-2-6 | 初稿 |
2021-2-9 | 更新了方法(函数)的语法 |
2021-2-12 | 更新异常处理语法 |
2021-3-10 | 更新异常处理语法例子 |
2.python基础学习-基础语法,判断,循环,if/for
if判断
amount = 1000
ipv = int(input("你要多少啊?"))
if amount >= ipv:
amount -= ipv
print("成功,还剩:"+str(amount))
else:
print("数量不够啊")
# ======多条件分支结构=====
score = int(input("请输入分数评级。。。"))
if score == 100:
print('哇塞满分哦!')
elif 80 <= score < 100:
print('针不错,你很优秀')
elif score >= 60:
print("可以了,合格")
else:
print('下次加油哦!')
while 循环
a = 10
sum = 0
while a > 0:
sum += a
a -= 1
print('sum:', sum) # 55
for in 循环(break ,continue)
a = 10
sum = 0
while a > 0:
sum += a
a -= 1
print('sum:', sum)
for item in 'helloworld':
print(item, end='') # helloworld
for i in range(5, 10):
print(i, end='') # 56789
print()
for item in [1, 5, 8, 99]:
print(item, end='') # 1 5 8 99
print()
for item in [1, 5, 8, 99]:
if item == 5:
break
print(item, end='') # 1
print()
for item in [1, 5, 8, 99]:
if item == 5:
continue
print(item, end='') # 1 8 99
# else与while循环搭配使用
a = 10
sum = 0
while a > 0:
sum += a
a -= 1
else:
print('sum:', sum)
# else与for in循环搭配使用
print()
for item in [1, 5, 8, 99]:
if item == 5:
continue
print(item, end='\t') # 1 8 99
else:
print('循环正常结束')
方法(函数)的定义
语法
分类 | 方法 | 调用 |
---|---|---|
无参函数 | def fun(): | fun() |
普通参数函数 | def fun(p1,p2): | 1.fun(1,2) 2.指定参数顺序调用fun(p2=5,p1=9) |
带默认值参数方法 | def fun(p1,p2=100): | 1.调用时不传p2,将采用默认值100如:fun(5) 2.fun(5,10) |
参数个数不确定 | def fun(*s): | s是一个元组tuple,调用:fun(1,2,3) |
参数名与个数都不确定 | def fun(**d) | d是一个字典dict 调用:fun(a=1,b=2,c=3) |
代码例子
# 定义方法
def fun(a, b):
return a * b
print(fun(10, 20)) # 200
def fun2(a, b=1000):
return a * b
print(fun2(2)) # 2000
print(fun2(20, 30)) # 600
def fun3(p1, p2=1, p3=10): # 第二个参数采用了默认值,则后面的参数也必须提供默认值
print(p2)
return p1 + p3
print(fun3(100, p3=100)) # 200
# 位置可变,参数名确定,但不确定个数
def fun4(*s):
print(s, type(s)) # ('Python', 'Hello') <class 'tuple'>
print(fun4('Python', 'Hello'))
# 参数名与参数个数均可变的参数
def fun5(**d):
print(type(d), d) # <class 'dict'> {'a': 1, 'b': 2, 'c': 3}
return list(d.keys())[0],list(d.values())[0]
print(fun5(a=1,b=2,c=3)) # ('a', 1) 多参数返回值是一个元组tuple类型
异常处理
try…except…else…finally
try...except...else结构
# 简单例子
try:
i = 1/0
except:
pass
# 未出异常时进入else
try:
i = int('java')
except Exception as e:
# 异常时执行
print('异常', e)
else:
print('未出错')
# 异常 invalid literal for int() with base 10: 'java'
try...except...else...finally结构
try:
i = int(input('请输入1'))
j = int(input('请输入2'))
z = i/j
except BaseException as e:
print('异常', e)
else:
print('正常时执行:', z)
finally:
print('正常与否均执行')
traceback 输出日志 V
import traceback
try:
i = 100 / 0
except:
traceback.print_exc()
else:
print("正常执行")