2 Python语句学习
条件判断语句
2.1 for
语法:
if 条件 :
语句1
elif 条件 :
语句2
else :
语句3
- 示例
if True:# 注意:True和False首字母必须大写
print("True")
else:
print("False")
Python指定任何非0和非空值为True,0或者None为False
注意事项:
- if 后面的条件没有符号,且 : 必须要英文字符
- 且if 后面的语句必须要缩进,且同一个层次的代码缩进必须一样(Python代码通过缩进来判断它属于那个层次)
举例:随机生成一个成绩判断是那个等级
import random #引入随机库
score = random.randint(0,100) #随机生成[0,100]的整数
print("生成的成绩为:",score)
if score>=90 and score<=100:
print("A")
elif score>=80 and score<90:
print("B")
elif score >= 60 and score < 80:
print("C")
elif score <60 and score >=0:
print("D")
else:
print("输入错误")
循环语句
语法
for i in range(begin,end,step) :
语句
- 对数字
range(5)==range(0,5)==range(0,5,1)
for i in range(0,10,3):
print(i)
- 对字符串
- 直接输出
str="Hello"
for s in str:
print(s,end="\t")
- 通过数组下标
str="Hello"
for i in range(len(str)):
print(i," ",str[i])
- 对数组
str=["aa","bb","cc"]
for i in range(len(str)):
print(i," ",str[i])
2.2 while
语法:
num=?
while i<num :
语句(注意要有控制循环条件的,避免死循环)
i=0
while i<5 :
print(i,end="\t")
i+=1
- break
结束当前循环 - continue
跳过本次循环下面的语句,进行下一次循环 - pass
一个占位的效果