栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

自学python-2(判断语句和循环语句)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

自学python-2(判断语句和循环语句)

条件判断
if False:
    print("True")
else:
    print("False")
print("end")

python指定任何非0和非空值为True,0或None为False

score = 87

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 >=0 and score <60:
#else:                 #else和elif一起使用
    print("本次考试·等级为E")

 

 if 条件(and条件):elif条件:else:

xingbie = 1  #1代表男生,0代表女生
danshen = 1  #1代表单身,0代表有对象

if xingbie == 1 :
    print("男生")
    if danshen == 1:
        print("我给你介绍一个吧?")
    else:
        print("你给我介绍一个吧")
else:
    print("女生")
    print(".....")

 

 “套娃”

生成随机库

import random   #引入随机库
x= random.randint(0,2)      #随机生成(0,2)的随机数,包括0,1,2三个数字

print(x)

课堂练习之剪刀石头布 

#课堂练习
import random
x = random.randint(0,2)
print("随机生成数字为:",x)
password = input("你的输入为:")
if password == 0:
    print("你的输入为:剪刀(0)")
elif password == 1:
    print("你的输入为:石头(1)")
else:
    print("你的输入为:布(2)")

if password == x:
    print("平局")
elif password ==0 and x==1:
    print("哈哈,你输了:)")
elif password ==1 and x ==2:
    print("哈哈,你输了:)")
else:
    print("恭喜你赢啦!")

循环语句 
for i in range(5):
    print(i)

 range也可以换成name、len(a)。(5)是指从0、1、2、3、4。

for i in range(0,13,3):   #从0开始,到13结束,步进值为3
    print(i)

 (1,2,3)1指开始,2指结束,3指步进值。

for i in range (-10,-100,-30):
    print(i)

 负数也可以

name = "chengdu"

for x in name:
    print(x,end="t")

a = ["aa","bb","cc","dd"]
for i in range(len(a)):
    print(i,a[i])

 a[i]指a列表里第i个元素

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

 课堂练习之1-100求和

#1-100求和
n = 100
sum = 0
counter = 1
while counter <= n:
    sum = sum+counter
    counter += 1

print("1到%d的和为:%d"%(n,sum))

count=0
while count<5:
    print(count,"小于5")
    count +=1
else:
    print(count,"大于等于5")

i=0
while i<10:
    i=i+1
    print("-"*30)
    if i==5:
        break    #结束整个while循环
    print(i)

break结束整个while循环

i=1
while i<10:
    i=i+1
    print("-"*30)
    if i==5:
        continue  #结束本次循环
    print(i)

continue结束套娃里的本次循环

课堂练习之写10以内乘法表

for i in range(1,10):
    for j in range (1,i+1):
        print('%d*%d=%dt'%(j,i,i*j),end='')
    print('')
i=1
j=1
while i<10:
    while j<(i+1):
        print('%d*%d=%d'%(j,i,i*j),end="t")
        j=j+1
    print()
    i+=1
    j=1

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/918785.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号