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
- Python学习笔记2-Python神奇的语法和格式化输出
- python中神奇的格式化输出
- python中神奇的格式化输出
- Python学习笔记之格式化输出
- Python学习-格式化输出
- python格式化输出学习
- Python 的格式化输出
- python格式化输出 学习学习
- Python学习笔记2--Python语句和语法
- Python format 格式化输出语法讲解
- python学习03--格式化输出
- python logging 日志输出 学习笔记 时间格式化
- Python学习笔记(10)--print格式化输出大全
- python学习笔记-语法
- Python的print 格式化输出
- Python的print 格式化输出
- python的格式化输出format
- python学习七--用户交互和格式化输出
- hdu3552I can do it!(贪心)
- Sql Server 向上取整,向下取整,四舍五入
- 151Reverse Words in a String
- dig安装
- 运行rails server 出现There was an error while trying to load the gem 'uglifier'. (Bundler::GemRequireErr
- Python学习笔记2-Python神奇的语法和格式化输出
- 理解C++的链接:C++内链接与外链接的意义
- Android开发者网址导航
- iOS的certificates和provisioning profiles
- web IDE Eclipse Che安装
- 风向标 ps:表白csdn
- 多个window.onscroll的解决方法
- 数据结构--冒泡排序
- UICollectionView