赞
踩
Python是一种强类型的动态脚本语言。
强类型就是指不允许不同类型相加。例如:整型+字符串会报类型错误。
动态:可以不使用数据类型声明,且确定一个变量的类型是在给它赋值的时候来确定一个变量的类型。
脚本语言:一般是指解释性语言,运行代码只需要一个解释器,不需要编译器。代码会边解释边运行,直到所有代码解释完或遇到错误问题才结束。
- print(str(50)+"Hello World!") #正确
- print(50+"Hello World!") #错误
- print(int('50')+5) #正确,把字符串'50'转为50,输出结果为55
- uid = 100
- print(id(uid)) #标识
- print(type(uid)) #变量类型
- print(uid) #变量的值
在Python中,变量也成为:对象的引用。因为,变量存储的就是对象的地址。变量通过地址引用了“对象”。
变量位于:栈内存。
对象位于:堆内存。
在Python语言中,声明变量的同时需要为其赋值,Python不允许有未赋值的变量存在,如上代码uid若未对其进行复制,则之后的代码都会报错。
条件判断使用双等号==、缩进(4个空格,不使用{})表示结构。在Python语言底层,会将布尔值True看作1,将布尔值False看作0。
- print("True+False+20的计算结果:",True+False+20) #结果为21
-
- #单分支
- uid = None
- if uid == 0:
- print("root")
-
- num = input('Please input a number: ')
- if int(num) < 10:
- print(num)
-
- #三目运算符
- print("None") if uid == 0 else print("Full")
-
- #多分支运算符
- score = input("Please enter your score: ")
- score = int(score)/10
- if score >= 9:
- print('A')
- elif score >= 8:
- print('B')
- elif score >= 7:
- print('C')
- elif score >= 6:
- print('D')
- else:
- print('E')

- #打印0-9这10个数,并不换行,最后输出10个数
- count = 0
- while count < 9:
- print(count,end = " ")
- count += 1
- print()
- print("Done")
-
- #把0-9这10个数拼接在一起,最后打印,输出为一个字符串
- result = ''
- count = 0
- while count < 10:
- result += str(count)
- count += 1
- print(result)
Python可以遍历的对象有序列(字符串、列表、元组)、字典、迭代器对象(iterator)、生成器函数文件对象。
- #遍历
- names = ['Tom', 'Peter', 'Jerry', 'Jack']
- for name in names:
- print(name,end=' ')
-
- #嵌套循环
- #打印9*9乘法表
- i = 1
- while i < 10:
- j = 1
- while j < 10:
- print('%d*%d=%d'%(i,j,i*j),end='\t')
- j += 1
- print()
- i += 1
break语句可用于while和for循环,用来结束整个循环。当有嵌套循环时,break语句只能跳出最近一层的循环。
continue用于结束本次循环,继续下一次。多个循环嵌套时,continue也是应用于最近的一层循环。
- state = False
- list1 = [1,5,7,4,4,0,5,6,8]
- for i in range(0,len(list1)-1):
- for j in range(i+1,len(list1)):
- if list1[i] == list1[j]:
- state = True
- break
- if state:
- print('True')
- break
- else:
- print('False')
5、Python常用数据类型

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。