一,条件语句
1,if,else,elif语句
这三个语句通常连起来使用,当需判断三次及以上时才使用elif语句。
代码为:
temp=input("请输入您猜测的数字")
gusse=int(temp)
if gusse==8:
print("恭喜您猜对了")
elif gusse>8:
print("大了")
else:
print("小了")
注意:temp就是英文单词temporary(临时的)的简写,也就是这个变量是临时的,只是临时借用而已。
其实代码可以不用temp而直接写成一行,如下:
guess=int(input(“猜一下哪个数字”))
另:input()函数在python3中,接收输入,即使是数字,返回的也是字符串,不能直接用于下面数字比较,所以要用int()函数把字符串转为整数,用于后面比较大小。
结果为:
请输入您猜测的数字7
小了
2,assert关键词
基本上每一种编程语言中都有assert声明。
总的来说,assert condition的意义是令程序测试condition,并在condition测试结果为false的时候抛出异常。
代码为:
assert False
结果为:
Traceback (most recent call last):
File "D:/Enclosure/python/seconday/if.py", line 11, in <module>
assert False
AssertionError
代码为:
assert 2>5
结果为:
Traceback (most recent call last):
File "D:/Enclosure/python/seconday/if.py", line 11, in <module>
assert 2>5
AssertionError
代码为
assert 2<5
结果为
进程完成,退出码 0
可见当assert后接的事件为为ture时,不出现任何情况,只有当接的事件为false时才会抛出异常。
二,循环语句
1,while循环
代码为:
count=0
while(count<9):
print("The count is:",count)
count+=1
结果为:
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
2,for循环
代码为:
for letter in 'Python': # 第一个实例
print('当前字母 :', letter)
fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # 第二个实例
print('当前水果 :', fruit)
print("Good bye!")
结果为:
当前字母 : P
当前字母 : y
当前字母 : t
当前字母 : h
当前字母 : o
当前字母 : n
当前水果 : banana
Good bye!
当前水果 : apple
Good bye!
当前水果 : mango
Good bye!
for循环的一般格式为for……in……
3,range()函数
python range() 函数可创建一个整数列表,一般用在 for 循环中。
函数语法
range(start, stop[, step])
参数说明:
start: 计数从 start 开始。默认是从 0 开始。例如range(5)等价于range(0, 5);
stop: 计数到 stop 结束,但不包括 stop。例如:range(0, 5) 是[0, 1, 2, 3, 4]没有5
step:步长,默认为1。例如:range(0, 5) 等价于 range(0, 5, 1)
代码为:
for i in range(0,10,2):
print(i,end=" ")
结果为:
0 2 4 6 8
4,enumerate()函数
描述
enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
语法
enumerate(sequence, [start=0])
参数
sequence – 一个序列、迭代器或其他支持迭代对象。
start – 下标起始位置。
返回值
返回 enumerate(枚举) 对象。
普通for循环
代码
i=0
seq=["0ne","two","three","for"]
for j in seq:
print(i,seq[i])
i+=1
结果
0 0ne
1 two
2 three
3 for
for 循环使用 enumerate
代码
seq = ['one', 'two', 'three']
for i, element in enumerate(seq):
print(i, element)
结果
0 one
1 two
2 three
5,break语句
用于中断循环
代码为:
for letter in 'Python':
if letter=="h":
break
print(letter)
结果为:
P
y
t
6,continue语句
Python continue 语句跳出本次循环,而break跳出整个循环。
continue 语句用来告诉Python跳过当前循环的剩余语句,然后继续进行下一轮循环。
continue语句用在while和for循环中。
代码为:
for letter in 'Python': # 第一个实例
if letter == 'h':
continue
print('当前字母 :', letter)
结果为:
当前字母 : P
当前字母 : y
当前字母 : t
当前字母 : o
当前字母 : n
结果跳过了“h”,继续了剩下的循环
7,pass语句
Python pass 是空语句,是为了保持程序结构的完整性。
pass 不做任何事情,一般用做占位语句。
def sample(n_samples):
pass
该处的 pass 便是占据一个位置,因为如果定义一个空函数程序会报错,当你没有想好函数的内容是可以用 pass 填充,使程序可以正常运行。