python的基本语句结构

这篇博客详细介绍了Python的基础语句结构,包括判断语句的if-else和elif,if语句的嵌套应用,以及猜拳游戏示例。在循环语句部分,讲解了while和for循环的使用,结合实际应用例如计算1~100的累积和、偶数累积和以及打印九九乘法表,并阐述了break和continue在循环控制中的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、判断语句

如果某些条件满足,才能做某件事情,而不满足时不允许做,这就是所谓的判断

if-else语句

age = 19
if age > 18:
	print('已成年....')
else:
	print('未成年....')

elif语句

score = 77
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>=0 and score<60:
    print('本次考试,等级为E')

if嵌套

chePiao = 1  # 用1代表有车票,0代表没有车票
daoLenght = 9  # 刀子的长度,单位为cm

if chePiao == 1:
    print("有车票,可以进站")
    if daoLenght < 10:
        print("通过安检")
        print("终于可以见到Ta了,美滋滋~~~")
    else:
        print("没有通过安检")
        print("刀子的长度超过规定,等待警察处理...")
else:
    print("没有车票,不能进站")
    print("亲爱的,那就下次见了,一票难求啊~~~~(>_<)~~~~")

猜拳游戏

import random
player = input('请输入:剪刀(0)  石头(1)  布(2):')
player = int(player)
computer = random.randint(0,2)
# 用来进行测试
#print('player=%d,computer=%d',(player,computer))
if ((player == 0) and (computer == 2)) or ((player ==1) and (computer == 0)) or ((player == 2) and (computer == 1)):
    print('获胜,哈哈,你太厉害了')
elif player == computer:
    print('平局,要不再来一局')
else:
    print('输了,不要走,洗洗手接着来,决战到天亮')

二、循环语句

一般情况下,需要多次重复执行的代码,都可以用循环的方式来完成
循环不是必须要使用的,但是为了提高代码的重复使用率,所以有经验的开发者都会采用循环

while循环

i = 0
while i<5:
    print("当前是第%d次执行循环"%(i+1))
    i+=1

执行结果
在这里插入图片描述

while循环的应用

计算计算1~100的累积和(包含1和100)

i = 1
sum = 0
while i<=100:
    sum = sum + i
    i += 1

print("1~100的累积和为:%d"%sum)

计算1~100之间偶数的累积和(包含1和100)

i = 1
sum = 0
while i<=100:
    if i%2 == 0:
        sum = sum + i
    i+=1

print("1~100的累积和为:%d"%sum)

打印九九乘法表

i = 1
while i<=9:
    j=1
    while j<=i:
        print("%d*%d=%d "%(j,i,i*j),end='')
        j+=1
    print('')
    i+=1

结果:
在这里插入图片描述

for循环

像while循环一样,for可以完成循环的功能。在Python中 for循环可以遍历任何序列的项目,如一个列表或者一个字符串等。

list1 = [1,2,3,4,5,6]
for i in list1:
	print(i)

break和continue

break用来结束整个循环:

list1 = [1,2,3,4,5,6]
for i in list1:
	print(i)
	if i==4:
		break

执行结果:
在这里插入图片描述

continue用来结束本次循环,紧接着执行下一次的循环

i = 0
while i<10:
	i = i+1
    if i==5:
    	continue
    print(i)

执行结果:
在这里插入图片描述
注意
break/continue只能用在循环中,除此以外不能单独使用
break/continue在嵌套循环中,只对最近的一层循环起作用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值