(一)判断语句和循环语句
(1)条件判断语句
Python指定任何非0和非空值Ture,0或者None为False.
if语句用于控制程序的执行,基本形式为:
if 判断条件1:
执行语句1
elif 判断条件2
执行语句2
else: 执行语句3
注:同一个程序段中,缩进距离得一样。
练习一:
score=53时,90-100为A等级,80-90为B等级,70-80为C等级,60-70为D等级,少于60为不及格,编写一个程序判断score=53时在哪个等级。
score=53
if score>=90 and score<=100:
print("我的本次考试等级为A")
elif score>=80 and score<=90:
print("我的本次考试等级为B")
elif score>=70 and score<=80:
print("我的本次考试等级为C")
elif score>=60 and score<=70:
print("我的本次考试等级为D")
elif score<=60:
print("我的本次考试成绩不及格")
输出结果为:我的本次考试成绩不及格
shengao=1 #1代表身高超过170,0代表身高不超过170
tizhong=1 #1代表体重超过100斤,0代表体重不超过100斤
if shengao==0:
print("你还挺高的")
if tizhong==0:
print("你好重啊")
else:
print("你好瘦欸")
else:
print("你真矮")
以上代码也是采用了非0 为Ture,0为Fasle.
①引入随机数
import random 引入随机库
import random
x=random.randint(0,3)
print(x)
输出结果会随机出现0,1,2,3四位数的其中一位。
练习题二:
剪刀(0),石头(1),布(2),玩家随意输入一位0到2中的一个数字,与系统随机生成的数字比较,输入0后,显示如下:
你的输入为:剪刀(0)
随机生成数字为:1
哈哈,你输了:)
代码如下:
import random
print("请输入一位数:剪刀代表0,石头代表1,布代表2")
a=int(input())
print("你输入的数字为%d"%a)
x=random.randint(0,2)
print("系统随机生成的数字为%d"%x)
if (a==1 and x==0) or (a==2 and x==1) or (a==0 and x==2):
print("恭喜玩家获胜")
elif a==x:
print("咱们平局啦")
else:
print("哈哈,你输啦")
'''
(2)循环语句
1.for循环
①
for in in range(5):
print(i)
输出结果为:0 1 2 3 4
②
for i in range(0,10,3):
print(i)
输出结果为0 3 6 9 (步进值为3)
③
name="henan"
for x in range:
print(x)
输出结果为
h
e
n
a
n
当把print(x)换成print(x,end="\t")时,输出结果变成:
h e n a n
④
a=["aa","bb","cc","dd"]
for i in range(len(a))
print(i,a[i])
输出结果为:
0 aa
1 bb
2 cc
3 dd
2.while循环
①
i=0
while i<3
print("当前是第%d次执行循环”%(i+1))
print("i=%d"%i)
i+=1
输出结果为:
当前是第1次执行循环
i=0
当前是第2次执行循环
i=1
当前是第3次执行循环
i=2
②
count=0
while count<3
print(count,"小于3")
count+=1
else:
print(count,"大于或等于3")
输出结果为:
0 小于3
1 小于3
2 小于3
3 大于或等于3
练习三:求1+2+3+......+100的总和。
n=100
sum=0
counter=1
while counter<=n:
sum=sum+counter
counter+=1
print("1到100的总和为:%d"%(n,sum))
输出结果为:1到100的总和为:5050
3. break,countinue,pass语句
①break语句可以跳出for和while的循环体
②countinue语句可以跳过当前循环,直接进入下一个循环
③pass语句一般用做占位语句,不做任何事情
(三)字符串(string)
Python中的string可以使用单引号,双引号和三引号括起来,使用反斜杠转义特殊字符。
①
my_str="I'm a student"
print(my_str)
输出结果是:I'm a student
②当用单引号时 ,应是如下:使用反斜杠来转义特殊字符
my_str('I\'m a student')
注:\\反斜杠符号;\'单引号;\"双引号
③
str="chengdu"
print(str)
print(str[0])
print(str[0:5])
print(str[1:7:2])
print(str[5:])
print(str[:5])
print(str+",你好")
print(str*3)
以上全部输出结果如下所示:
chengdu
c
cheng
hnd
du
cheng
chengdu,你好
chengduchengduchengdu
④当前面加个r时,代表引号里面的内容全部输出;
print(r"hello\nworld")
输出结果为:hello\nworld