Python Basics | Notes

WeChat official account tweet: https://mp.weixin.qq.com/s/iO1yTp4kbNKt57WAmhhu7Q

Code comment is to comment on the code. It is equivalent to annotating Chinese interpretation of an English word.

Comments are used to prompt or explain the functions and functions of certain codes to the user, and will not be executed by the computer. The biggest role is to improve the readability of the program.

Comments are divided into single-line comments and multi-line comments.

single line comment

Python uses the pound sign # as a symbol for single-line comments, and the syntax format is:

#注释内容

Everything from the pound sign # until the end of the line is a comment. When the Python interpreter encounters a #, it ignores the entire line following it.

When explaining the function of multiple lines of code, the comment is generally placed on the previous line of the code, for example:

#使用print输出下列字符串 
print('Python') 
print('Finance') 
print('Python for Finance') 

When explaining the function of a single line of code, comments are generally placed on the right side of the code, for example:

print('Python')    #输出Python字符串 
print('Finance')   #输出Finance字符串 

multiline comment

A multi-line comment refers to the content of multiple lines (including one line) in a one-time comment program.

Python uses three consecutive single quotes ''' or three consecutive double quotes """ to comment multi-line content. The specific format is as follows:

''' 
这是多行注释,用三个单引号 
这是多行注释,用三个单引号 
这是多行注释,用三个单引号 
''' 

or:

 """ 
这是多行注释,用三个双引号 
这是多行注释,用三个双引号 
这是多行注释,用三个双引号 
"""  

Let me show you another program example, that is, to compile the option pricing function

  • Lines 1-8 are a multi-line comment, which details the meaning of the specific parameters of the function
  • Lines 11 and 14 each have a single-line comment explaining what that line of code does
  • There is a single-line comment on line 12, indicating that the option pricing function is defined starting from line 13
'''
运用布莱克-斯科尔斯定价模型计算欧式看涨期权、看跌期权价格 
S:期权标的资产的价格 
X:期权执行价格 
sigma:波动率 
r:无风险利率 
T:期权有效期
''' 

import math 
import scipy.stats as stats  #导入SciPy的子模块stats 
#定义期权定价函数
def cal_option_price(S,X,sigma,r,T): 
    T = T/365        #将期权有效期天数转为为年单位 
    d1 = (math.log(S/X)+(r+sigma**2/2)*T)/(sigma*math.sqrt(T)) 
    d2 = d1-sigma*math.sqrt(T) 
    c = S*stats.norm.cdf(d1)-X*math.exp(-r*T)*stats.norm.cdf(d2) 
    p = X*math.exp(-r*T)*stats.norm.cdf(-d2)-S*stats.norm.cdf(-d1) 
    return c,p 

Guess you like

Origin blog.csdn.net/mfsdmlove/article/details/129396724