Python基础语法
交互式:
命令逐条运行
交互式编程不需要创建脚本文件,是通过 Python 解释器的交互模式进来编写代码。
>>>1+12
>>>a=1
>>>b=1
>>>a+b2
脚本式:
一次性全部运行
通过脚本参数调用解释器开始执行脚本,直到脚本执行完毕。当脚本执行完成后,解释器不再有效。
my_dream='I want to be a quantitative trader.'
print('Hello,world!!! '+my_dream)
print(my_dream+' What can I do?')
#点击run,显示运行结果:Hello,world!!! I want to be a quantitative trader.
I want to be a quantitative trader. What can I do?
代码缩进:
缩进替代({})
学习Python与其他语言最大的区别就是,Python的代码块不使用大括号({})来控制类,函数以及其他逻辑判断。
python最具特色的就是用缩进来写模块。
代码缩进(错误)
price=1
ifprice>0:
print('True')
print('price is greater than 0')
# 没有严格缩进,在执行时会报错
else:
print("False")File "", line 4
print ('price is greater than 0')
^
IndentationError: unexpected indent
代码缩进(正确)
price=1
ifprice>0:
print('True')
print('price is greater than 0')
else:
print("False")True
price is greater than 0
注释代码
单行注释用 # 开头
多行注释用三个引号(''')
### 世界你好
print('hello world')hello world
### 世界你好
# print('hello world')
"""
世界你好
print('hello world')
print('all in')
"""
print('all in')all in
报错处理
定位与调试(第几行什么错怎么改)
以下报错代码显示第四行出现错误,是缩进错误。
price=1
ifprice>0:
print('True')
print(priceisgreater than0)
else:
print"False"File "", line 4
print (price is greater than 0)
^
SyntaxError: invalid syntax
以下报错代码显示第六行出现错误,是少了括号。
price=1
ifprice>0:
print('True')
print('price is greater than 0')
else:
print"False"File "", line 6
print "False"
^
SyntaxError: Missing parentheses in call to 'print'
以下是正确修改后的代码
price=1
ifprice>0:
print('True')
print('price is greater than 0')
else:
print("False")True
price is greater than 0
try/except
捕捉异常可以使用try/except语句。
try/except语句用来检测try语句块中的错误,从而让except语句捕获异常信息并处理。
如果你不想在异常发生时结束你的程序,只需在try里捕获它。
try:正常的操作
......................
except:发生异常,执行这块代码
......................
else:如果没有异常执行这块代码
# 定义函数
deftest_price(price):
returnint(price)
# 调用函数
test_price("xyz")---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
in ()
3 return int(price)
4 # 调用函数
----> 5 test_price("xyz")
in test_price(price)
1 # 定义函数
2 def test_price(price):
----> 3 return int(price)
4 # 调用函数
5 test_price("xyz")
ValueError: invalid literal for int() with base 10: 'xyz'
# 定义函数
deftest_price(price):
try:
p=int(price)
exceptValueError:
print("参数不是数字\n")
else:
print(p+100)
# 调用函数
test_price("z66")参数不是数字
raise
使用raise语句自己触发异常
defcheck_price(price):
ifprice<0:
raiseException("Invalid price!",price)
# 触发异常后,后面的代码就不会再执行
try:
check_price(-1)
print('right')
##触发异常
exceptExceptionase:
print(e)
else:
print('can_trade')('Invalid price!', -1)
文件处理
open()/write()/read()/close()
os.rename()/os.remove()
who=open("channel.txt","r+")
who.write("www.fxdayu.com!\nVery good site!\n")32
who.close()
who=open("channel.txt","r+")
channel=who.read(50)
channel'www.fxdayu.com!\nVery good site!\n'
who.close()
importos
os.rename('channel.txt','website.txt')
os.remove('website.txt')