作者:tobecrazy 出处:http://www.iyunv.com/tobecrazy 欢迎转载,转载请注明出处。thank you!
基本概念 :
常量:
常量名全部大写,如PI
变量:
python没有变量类型,也不必声明,直接赋值即可. 变量可以是数字,字符串,布尔值(True,Flase,注意大小写),列表,字典等类型.
如: var=1 str='hello'
变量名:
字母数字下划线,不能以数字开头。全局变量最好全部大写,一般变量注意避免保留字。
有效变量名: test123 _68 py
字符串:
在双引号中的字符串与单引号中的字符串的使用完全相同.
如:'this is a test'=="this is a test"
三引号'''/"""
利用三引号,你可以指示一个多行的字符串。你可以在三引号中自由的使用单引号和双引号,三引号可以做为多行注释。
''' what's your name ?
my name is Young'''
转义字符,如果要输出' "等有特殊意义的字符,需要将其转义才能输出
\' \" 引号 \n 换行
如:"Jason:\"what's your name?\"\nYoung:\'my name is Young\' "
此外转义字符也有跨行链接符的作用
如:
"Jason:\"where are you from\"\n\
Young:\'I come from China\' "
如果你想要指示某些不需要如转义符那样的特别处理的字符串,那么你需要指定一个自然字符串。自然字符串通过给字符串加上前缀r或R来指定。例如r"Newlines are indicated by \n"。
代码如下:
1 #!/usr/bin/python
2 '''
3 this is a Python script
4 create by Young
5 2014-06-28
6 '''
7 var=3.14
8 str='this is a python string'
9 print var
10 print str
11 _123="this is variable _123"
12 print _123
13 print '''what's your name ?
14 my name is Young'''
15 print "Jason:\"what's your name?\"\nYoung:\'my name is Young\' "
16 print "Jason:\"where are you from\"\
17 \nYoung:\'I come from China\'
18 print r"\"what's your name?\"\n"
输出结果为:
3.14
this is a python string
this is variable _123
what's your name ?
my name is Young
Jason:"what's your name?"
Young:'my name is Young'
Jason:"where are you from"
Young:'I come from China'
\"what's your name?\"\n
总结:python变量和常量和别的编程语言基本相同,字符串有自己的特色,双引号和单引号效果相同,三引号可以作为python的注释,转义字符能当做跨行连接符使用,使用r/R可以是转义字符失去作用。