顺序
和大多数变成语言一样(此处略)
选择
if…else…
if…elif…elif…else…
注意:后面的冒号和其他编程语言的不同点
例子1:剪刀石头布游戏
import random
player = int(input("请输入数字——0(剪刀)1(石头)2(布):"))
computer = random.randint(0,2)
if (player == 0 and computer == 2) or (player == 1 and computer == 0) or (palyer == 2 and computer == 1):
print("player win!")
elif player == computer:
print("draw")
else:
print("computer win!")
例子2:坐火车过安检
# if嵌套(执行事情有先后顺序)
is_ticket = 1
is_knife = 1
if is_ticket == 1:
print("请进行安检!")
if is_knife == 1:
print("您随身携带违禁物品,请等待处理!")
else:
print("安检通过,请乘车!")
else:
print("您还未购票,请买票之后再进站!")
循环
两种:while和for
break和continue
例子1:打印1-100之间的数
i = 1
while i < = 100:
print(i)
i+=1
例子2:打印图形
*
**
***
****
******
i= 1
while i <= 5:
j = 1
while j <= i:
print("*",end=" ")
j+=1
print(" ")
i += 1
循环问题的框架
i = 1
while i <= 100:
代码
i += 1
例子3:打印九九乘法表
i = 1
while i <= 9:
j = 1
while j <= i:
print("%d*%d=%d\t"%(j,i,i*j),end="") #不换行显示
j += 1
print(" ") #换行
i += 1
例子4:打印1-100之间的前20个偶数
i = 1
k = 0
while i < 100:
if i % 2 == 0:
if k == 20:
break
print(i)
k += 1
i += 1
例子5:for循环
循环输出字符串的内容
name = 'zhangsan'
for temp in name:
print(temp)
例子7:使用break来结束循环
i = 1
while i < 5:
if i = 3:
break #break用来结束while循环
print(i)
i += 1
例子8:使用continue来结束本次循环
i = 1
while i < 5:
if i = 3:
continue #continue用来结束本次循环,执行下一次循环
print(i)
i += 1