[关闭]
@Channelchan 2018-01-09T17:33:15.000000Z 字数 2695 阅读 137178

Python基础语法

交互式:

命令逐条运行

交互式编程不需要创建脚本文件,是通过 Python 解释器的交互模式进来编写代码。

  1. >>> 1+1
2
  1. >>> a=1
  2. >>> b=1
  3. >>> a+b
2

脚本式:

一次性全部运行

通过脚本参数调用解释器开始执行脚本,直到脚本执行完毕。当脚本执行完成后,解释器不再有效。

  1. my_dream='I want to be a quantitative trader.'
  2. print('Hello,world!!! '+my_dream)
  3. print (my_dream + ' What can I do?')
  4. #点击run,显示运行结果:
Hello,world!!! I want to be a quantitative trader.
I want to be a quantitative trader. What can I do?

代码缩进:

缩进替代({})

学习Python与其他语言最大的区别就是,Python的代码块不使用大括号({})来控制类,函数以及其他逻辑判断。
python最具特色的就是用缩进来写模块。

代码缩进(错误)

  1. price = 1
  2. if price>0:
  3. print ('True')
  4. print ('price is greater than 0')
  5. # 没有严格缩进,在执行时会报错
  6. else:
  7. print ("False")
  File "<ipython-input-4-95ffcc1a2fae>", line 4
    print ('price is greater than 0')
    ^
IndentationError: unexpected indent

代码缩进(正确)

  1. price = 1
  2. if price>0:
  3. print ('True')
  4. print ('price is greater than 0')
  5. else:
  6. print ("False")
True
price is greater than 0

注释代码

单行注释用 # 开头

多行注释用三个引号(''')

  1. ### 世界你好
  2. print('hello world')
hello world
  1. ### 世界你好
  2. # print('hello world')
  1. """
  2. 世界你好
  3. print('hello world')
  4. print('all in')
  5. """
  6. print('all in')
all in

报错处理

定位与调试(第几行什么错怎么改)

以下报错代码显示第四行出现错误,是缩进错误。

  1. price = 1
  2. if price>0:
  3. print ('True')
  4. print (price is greater than 0)
  5. else:
  6. print "False"
  File "<ipython-input-9-1d2f1bbcc104>", line 4
    print (price is greater than 0)
                               ^
SyntaxError: invalid syntax

以下报错代码显示第六行出现错误,是少了括号。

  1. price=1
  2. if price>0:
  3. print ('True')
  4. print ('price is greater than 0')
  5. else:
  6. print "False"
  File "<ipython-input-10-cf69990590e3>", line 6
    print "False"
                ^
SyntaxError: Missing parentheses in call to 'print'

以下是正确修改后的代码

  1. price=1
  2. if price>0:
  3. print ('True')
  4. print ('price is greater than 0')
  5. else:
  6. print ("False")
True
price is greater than 0

try/except

捕捉异常可以使用try/except语句。

try/except语句用来检测try语句块中的错误,从而让except语句捕获异常信息并处理。

如果你不想在异常发生时结束你的程序,只需在try里捕获它。

try:

正常的操作

......................

except:

发生异常,执行这块代码

......................

else:

如果没有异常执行这块代码
  1. # 定义函数
  2. def test_price(price):
  3. return int(price)
  4. # 调用函数
  5. test_price("xyz")
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-12-33744945d97f> in <module>()
      3     return int(price)
      4 # 调用函数
----> 5 test_price("xyz")


<ipython-input-12-33744945d97f> 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'
  1. # 定义函数
  2. def test_price(price):
  3. try:
  4. p = int(price)
  5. except ValueError:
  6. print ("参数不是数字\n")
  7. else:
  8. print(p+100)
  9. # 调用函数
  10. test_price("z66")
参数不是数字

raise

使用raise语句自己触发异常

  1. def check_price(price):
  2. if price < 0:
  3. raise Exception("Invalid price!", price)
  4. # 触发异常后,后面的代码就不会再执行
  1. try:
  2. check_price(-1)
  3. print('right')
  4. ##触发异常
  5. except Exception as e:
  6. print (e)
  7. else:
  8. print ('can_trade')
('Invalid price!', -1)

文件处理

open()/write()/read()/close()

os.rename()/os.remove()

  1. who = open("channel.txt", "r+")
  1. who.write("www.fxdayu.com!\nVery good site!\n")
32
  1. who.close()
  1. who = open("channel.txt", "r+")
  1. channel = who.read(50)
  1. channel
'www.fxdayu.com!\nVery good site!\n'
  1. who.close()
  1. import os
  2. os.rename('channel.txt', 'website.txt')
  1. os.remove('website.txt')
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注