python学习笔记(二) 基本运算
1. 条件运算
基本语法
if condition1:
do somethings1
elif condition2:
do somethings2
else:
do somethngs3
案例
# guess nums
nums = 5
a = int(input('请输入数字'))
if a > nums :
print('input num is to big')
elif a < nums :
print('input num is to small')
else:
print('guess success')
2. 循环遍历
2.1 while
循环
语法
while 条件 :
do some things
2.2 for in
循环
语法
# item 单个数据 datas 数组
for item in datas:
do some things
else:
2.2 range
函数
语法
#i 标识下表 len 循环的长度 可以指定代下标位置 (5,9)
for i in range(len):
# eg
>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
... print(i, a[i])
...
0 Mary
1 had
2 a
3 little
4 lamb
break
和continue
用法和java是相同的
3. 函数(继承)
class people:
# 全局变量
name = ''
age = 0
# 定义私有变量
_height =0.00
# 构造方法
def __init__(self,n,a,h):
self.name = n
self.age = a
self._height = h
def speak(self):
print('我叫{},今年{}岁了,身高为{}cm'.format(self.name,self.age,self._height))
# 继承
class student(people):
grade =''
def __init__(self,n,a,h,g):
# 调用父类方法
people.__init__(self,n,a,h)
self.grade =g
# 重写父类方法
def speak(self):
print('我叫{},今年{}岁了,身高为{}cm,今年读{}年纪'.format(self.name,self.age,self._height,self.grade))
class action:
role =''
faver =''
def __init__(self,r,f):
self.role = r
self.faver = f
def speak(self):
print('我是{},我的爱好是{}'.format(self.role,self.faver))
class test(action,people):
def __init__(self,n,a,h,r,f):
people.__init__(self,n,a,h)
action.__init__(self,r,f)
## 私有方法 定义的时候__开头
def __private_test(self):
print("测试私有方法")
a = test('音乐家','弹钢琴',12,'音乐家','弹钢琴')
a.speak()
a.__private_test()