Python学习笔记2-Python神奇的语法和格式化输出

来源:互联网 发布:上古卷轴5跳出优化补丁 编辑:程序博客网 时间:2024/06/06 09:26

先来看一个例子:

class Fish:    hungry=True    def eat(self,food):        if food is not None:            self.hungry=False            class  User:    def __init__(self,name):        self.name=namef=Fish()Fish.eat(f, None)print(f.hungry)Fish.eat(f,'rice')f.eat('noodle')print(f.hungry)user=User('zhangsan')print(user.name)

Python是非常简化的语言,所以类与方法之间没有大括号,连if判断的代码块都没有大括号;类的实例不需要使用new关键字;

代码的结尾分号也被省略掉了,这让写习惯Java代码的我,刚上手很不习惯;

但Python对格式要求很严格,不同层次的代码必须要对齐,要不然会报错;



Python 语法:

行注释使用“#” 进行注释,例:  

# 这是一个注释

块注释使用三个单撇号  ''' ,例:
''' 这是一个块注释  '''

可以使用\来使代码进行换行 例:
str1=Nonestr2=Noneif(str1<>1) and \    (str2<>1):    print "两个变量都不等于1"


不等于号可以使用<>或者!=  都可以,例:
print 1<>2print 1!=2

在Python中字符串可以使用单引号或者双引号
print '这是一个字符串'print "这是一个字符串"

与、或、非逻辑符号分别使用  and、or、not None
print True and False # Falseprint True or False  # Trueprint not not None   # False

Python 变量赋值
count=0count=count+1 #这里count++或者++count无效的count+=1count*=1count-=1print countname='bobi'print namex=y=z=1 #可以三个变量一起赋值print x,y,zx,y,z=1,'string',0.5 #可以实现不同类型变量一起赋值print x,y,zx,y=y,x #可以这样实现变量之间的值的调换print x,yx,y=15.5,24.2print 'x: %d,y: %d' % (x,y) #格式化为整数print 'x: %f,y: %f' % (x,y) #格式化为浮点数print 'x: %x,y: %x' % (x,y) #格式化为十六进制数print 'x: %o,y: %o' % (x,y) #格式化为八进制数print '两位小数:%.2f' % (1.765555) #保留两位小数print 'My name is %s,i\'m %s.' % ('Tom',18) #带入字符串

更多Python 数值/字符串格式化

http://blog.csdn.net/feelang/article/details/37594313

http://www.cnblogs.com/plwang1990/p/3757549.html


字符串操作

str='Python'print str[0] # 取第一位 Pprint str[2:5] # 取2~5之间的 thoprint str[:2] # 取前两位 Pyprint str[3:] # 取第三位开始到最后honprint str[-1] # 取最后一位  nprint str[:]  # 取所有print strcool=' is Cool'print str+cool # 字符串与字符串相加print str+' '+cool # 字符串与字符串相加print str*2 # 相当于 str + str 两个字符串相加str=1000 # 变量可以进行任意数据类型转换print strprint '#'*20 # '#'乘以20个#



0 0
原创粉丝点击