#!/usr/bin/python
print "Hello, World!";
注意Python3.0+要这样写
print("Hello,World!");
#!/usr/bin/python
# -*- coding: gbk -*-
print "你好,世界";
Python的代码块不使用扩号,而是使用缩进来写。如:
if True:
print "True"
else:
print "False"
Python语句中一般以新行作为为语句的结束符。
可以使用斜杠( \)将一行的语句分为多行显示,如下所示:
total = item_one + \
item_two + \
item_three
语句中包含[] {}或()的不需要使用连接符,如:
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
word = 'word'
sentence = "这是一个句子。"
paragraph = """这是一个段落。
包含了多个语句"""
单行注释使用#号
多行注释使用三个引号括起来
raw_input("\nplease input");
使用;隔开
count=1
a=b=c=1
a,b,c=1,2,"abc"
标准数据类型:
del var1,var2
子串
str="abcd"
print str[0:2]
list=[1,2,'abc']
print list
print list[1:2]
print list[1:]
print list * 2 #输出列表2次
print list + list1 #列表组合
类似于List,相当于只读列表
list=(1,2,3,"abc)
print list[1:2]
dict={}
dict['a']="str"
dict[2]="abc"
print dict['a']
print dict.keys()
print dict.values()
内置函数进行类型转换
函数 | 描述 |
---|---|
int(x [,base]) | 将x转换为一个整数 |
long(x [,base] ) | 将x转换为一个长整数 |
float(x) | 将x转换到一个浮点数 |
complex(real [,imag]) | 创建一个复数 |
str(x) | 将对象 x 转换为字符串 |
repr(x) | 将对象 x 转换为表达式字符串 |
eval(str) | 用来计算在字符串中的有效Python表达式,并返回一个对象 |
tuple(s) | 将序列 s 转换为一个元组 |
list(s) | 将序列 s 转换为一个列表 |
set(s) | 转换为可变集合 |
dict(d) | 创建一个字典。d 必须是一个序列 (key,value)元组。 |
frozenset(s) | 转换为不可变集合 |
chr(x) | 将一个整数转换为一个字符 |
unichr(x) | 将一个整数转换为Unicode字符 |
ord(x) | 将一个字符转换为它的整数值 |
hex(x) | 将一个整数转换为一个十六进制字符串 |
oct(x) | 将一个整数转换为一个八进制字符串 |
if ( b not in list):
print 2
else:
print 3
if ( a is b):
print a
else:
print b
if num ==3:
print "3"
elif num==2:
print "2"
else:
print "else"
简单语句组:
if (var ==1) : print "1"
count = 0
while (count < 9):
print 'The count is:', count
count = count + 1
for letter in 'Python': # 第一个实例
print '当前字母 :', letter
for i in range(1, 5):
print(i)
else:
print('for循环结束')
控制循环:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import time; # 引入time模块
ticks = time.time()
print "当前时间戳为:", ticks
time.sleep 挂起
time.clock windows第一次调用该方法到现在的秒数,精确度高于1微秒,可以用来计算程序执行的时间。
time.gmtime([sec])
可选的参数sec表示时间戳。
返回time.struct_time类型的对象
time.localtime
与time.gmtime类似,返回一个stuct_time对象
time.mktime
执行与gmtime localtime相反的操作,它接收struct_time对象作为参数,返回用秒数来表示时间的浮点数。
import time
#下面两个函数返回相同(或相近)的结果
print time.mktime(time.localtime())
print time.time()
import time
print time.strftime("%Y-%m-%d") //输出当前日期
print time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime())
print time.strftime('Weekday: %w; Day of the yesr: %j')
#---- result
#2009-06-23 15:30:53
#Weekday: 2; Day of the yesr: 174
import time
print time.strptime('2009-06-23 15:30:53', '%Y-%m-%d %H:%M:%S')
#---- result
#time.struct_time(tm_year=2009, tm_mon=6, tm_mday=23, tm_hour=15, tm_min=30, tm_sec=53, tm_wday=1, tm_yday=174, tm_isdst=-1)
import calendar
monthRange = calendar.monthrange(2013,6)
print(monthRange)
输出:
(5, 30)
在线学习资料:
http://www.runoob.com/python/python-tutorial.html
在线运行环境:
http://c.runoob.com/compile/6
资源库设置:
新安装资源时,要添加option参数,如下图:
--trusted-host mirrors.aliyun.com