您的位置:首页 > 编程语言 > Python开发

python基础快速了解-hello.py

2015-02-03 11:10 471 查看
#coding=utf-8

# hello.py python学习起步

# ====== 注释  ======
# python使用#符号标示注释

#one comment
print 'hello world!'

#  ====== 运算符 ======
# 算术运算符
# 不支持自增1 自减1 运算符
# **表示乘方 优先级最高
print -2*4 + 3**2

# 比较运算符 返回布尔值(True/False)
print 2 < 4;
print 6.2 > 6.2001

#逻辑运算符 将任意表达式连接在一起 返回布尔值
print 3 < 4 and 4 < 5
print not 6 <= 6.2
print 2 > 4 or 2 < 4

#  ====== 变量 ======
# 不需要预先声明变量类型
count = 10
print "count is %d" % (count)

# ====== 字符串 ======
# 定义字符串 单引号或双引号(三引号可用于包含特殊字符)
pystr = 'Python'
iscool = 'is cool!'
# 字符串连接
print pystr + ' ' + iscool

# 索引:[] 切片:[:]
# 索引规则:第一个字符的索引是0,最后一个字符的索引是-1
print pystr[0]
print pystr[2:5]
print iscool[:2]
print iscool[3:]
print iscool[-1]

# ====== 列表 ======
# 列表元素用[]包裹 个数和值可以改变
# 操作类似数组 可以索引和切片
aList = [1, 2, 3, 4]
print aList
print aList[0]

# ====== 元组 ======
# 元组元素用()包裹 个数和值不可以改变
# 操作类似数组 可以索引和切片
aTuple = ('robots', 77, 93, 'try')
print aTuple
print aTuple[:3]

# ====== 字典 ======
# 映射数据类型 由键-值(key-value)对构成
# 字典元素用{}包裹
aDict = {'host':'localhost'}
print aDict
aDict['port'] = 8080
print aDict.keys()
print aDict['host']

# ====== 控制操作 ======
# 关键字后跟表达式 ':'号结束
x = -1
if x < .0:
print '"x" must be atleast 0!'

count = 0;
while count < 3:
print 'loop #%d' % (count)
count += 1

foo = 'abc'
for c in foo:
print c

# ====== 列表解析 ======
squared = [x**2 for x in range(4)]
for i in squared:
print i

# ====== 函数 ======
# 定义函数由def关键字及其后的函数名再加上所需的函数参数组成 ':'号结束
# 函数参数可以定义一个默认值
def addMe2Me(x):
'apply + operation to argument'
return (x + x)

print addMe2Me(4.25)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: