python与以前学习的JAVA,C等最大的不同就是,python代码块不适用{}来控制类,函数以及其他逻辑判断。python是使用缩进来写模块的。
下面描述一下Python和其他语言的几点区别:
(1)缩进的空白数量是可变的,但所有的代码块语言必须包含相同的缩进空白数量。
(2)python一行一般为一个语句,但当一个语句要分多行写时,需要使用 \ 将一行语句分多行显示。
total = item_one + \
item_two + \
item_three
语句中包含[]、{}和()时,不需要使用多行连接符。例如:
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
(3)python单行注释用#,多行注释可以用三个单引号'''
或者三个双引号"""
.
(4)缩进相同的一组语句构成一个代码块,我们称之为代码组。
if expression :
suite (代码组)
elif expression :
suite
else :
suite
(5)python变量不需要声明,直接赋值即可。
变量的赋值,也是用=来赋值,这和其他语言一样。
a=b=c=1 #三个值均为1
a,b,c=1,2,3 #相当于a=1 b=2 c=3
(6)python数据类型有Number(数字),String(字符串),List(列表),Tuple(元组),Dictionary(字典)。
稍微细说一下List(列表),Tuple(元组),Dictionary(字典)
List(列表)
列表类似于数组,内部元素是可以重复的。
list=['abc',12,34,'def',56] #list的元素是从0开始算起。
list2=[78,9]
print list[0] #输出abc
print list[1:3] #输出[12, 34] 输出1,2号元素
print list[2:] #输出[34, 'def', 56]从第二个开始至末尾
print list*2 #输出['abc', 12, 34, 'def', 56, 'abc', 12, 34, 'def', 56]
print list+list2 #输出['abc', 12, 34, 'def', 56, 78, 9]
Tuple(元组)
元组和列表近似,只是元组使用()表示,而且元组的内容是不能改变的。
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
tuple[2]=1000 #就会报错,但是list就可以。
Dictionary(字典)
字典类似于java中的hashmap。
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print dict['one'] # 输出键为'one' 的值
print dict[2] # 输出键为 2 的值
print tinydict # 输出完整的字典
print tinydict.keys() # 输出所有键
print tinydict.values() # 输出所有值