1.简介
大家编程时必然会使用新的编译器, 那这里就设计了一个问题:你的 Python 是否可以正常工作?相信很多人都会print一句hello world就结束了, 但编码的时候难免会遇到类似import不了库这样的问题, 会造成很多麻烦, 今天就教大家测试你的Python.
2.设计测试
正式开始看内容之前, 我们先了解一下三大结构, 即顺序、分支、循环结构(了解详情就看这篇文章, 不是我写的).
2-1.输出测试
嗯...这块不多讲, 都是大部分人会做的事情
print('TEST 1 SUCCESS')
2-2.分支结构/变量测试
说起分支结构, 大家想到的肯定是if, 继续想, 肯定会想到配套的elif和else, 是的, 我们只需要把这些代码敲一遍就行了, 在这里我把变量定义也和进了这个测试(其实就是定义变量然后用它比大小).
相信很多人都会问顺序结构去哪里了, 其实如果编译器能执行到第二个字母, 那就相当于顺序结构正常.
代码在此处:
n = 0
if n > 1:
print('ERROR1: if')
elif n % 2 == 1:
print('ERROR2: elif')
else:
print('TEST 2 SUCCESS')
2-3.循环结构/输入测试
循环结构, 我们这里用的是for循环, 逻辑是循环的时候输出序号, 循环完输入终端看到的最后一个数字, 再和循环次数做对比, 看对不对.代码献上:
for i in range(10):
print(f"Python ranging: number{i + 1}") #i + 1,becuse i starts from 0
n = int(input("Count what's the last number?"))
if n == 10:
print('TEST 3 SUCCESS')
else:
print('ERROR3: range')
2-4.import测试
为了捕捉错误, 我们这里要运用try语句(不知道try是什么就看这篇文章, 同样不是我写的)
这块为什么import这两个库(os, time)呢?待会你就知道了.
try:
import os, time
except:
print('ERROR4: import')
2-5.结尾
揭晓os+time的用法:
time.sleep(10)
os.system('clean') #MAC的话换成clear
最后在测试开头加一点注释:
# This is a Python test that can check is your Python working well.
# Error1: the 'if' is not good
# Error2: the 'elif' is not good
# Error3: "for ... range" is not good
# Error4: cannot import libraries
# IMPORTANT NOTICE: if it doesn't print "SUCCESS", it's also not good!!!
# (except it is test 4)
3.完整代码分享和鸣谢
废话不多说, 现在就把代码搬过来
# This is a Python test that can check is your Python working well.
# Error1: the 'if' is not good
# Error2: the 'elif' is not good
# Error3: "for ... range" is not good
# Error4: cannot import libraries
# IMPORTANT NOTICE: if it doesn't print "SUCCESS", it's also not good!!!
print('TEST 1 SUCCESS')
n = 0
if n > 1:
print('ERROR1: if')
elif n % 2 == 1:
print('ERROR2: elif')
else:
print('TEST 2 SUCCESS')
for i in range(10):
print(f"Python ranging: number{i + 1}")
n = int(input("Count what's the last number?"))
if n == 10:
print('TEST 3 SUCCESS')
else:
print('ERROR3: range')
try:
import os, time
except:
print('ERROR4: import')
time.sleep(10)
print(os.path.islink('www.runoob.com'))
大家可以直接复制使用~
如有什么错误请各位大佬在评论区多指教~