02-if条件和while、for循环

一 if语句

  • != 不等于
  • == 等于
  • if 条件: …elif 条件: …else…
weather = input('请输入今天的天气:')
sex = input('请输入性别:')
if weather =='sun':
   print('晴天')
elif weather == '阴天':
   print('阴天')
else:
   print('雨天')

二 三目运算

  • True if 条件 else False
print('晴天') if weather == 'sun' else print('雨天')

三 逻辑运算

  • 与and 或or 非not
  • 优先级:not>and>or
# 逻辑运算  多条件 
# print( num<5 and num>9 )                      # False
# print( num<5 or num>9 )                       # True
# print( not num<5 )                            # False
# print( not 1==2 and 1==1 or 2==3 and 3==3 )   # True
# print( not 2==2 or 1==2 and 2==3 or 3==3 )    # True

if weather == 'sun' and sex == 'women':
    print('出去玩吧')
else:
    print('今天有事')    
  • 逻辑短路
# 逻辑短路   前面条件满足条件后不会继续往后判断    对实际结果无影响
print(1 == 2 and 2 == 1)  # False
print(2 == 2 or 2 == 1)  # True

四 While循环

  • 字符串不能与数字直接拼接
  • 循环三要素:1.循环的初始值;2.循环的结束条件;3.循环的代码块
  • while … while…else…
  • 必须有结束条件
i = 0  # 1.循环的初始值
while i < 10:  # 2.循环的结束条件
    i += 1  # i = i+1
    if i == 5:
        print('不行了,第五圈我跑不动了!')
        ##        break        # 直接结束循环  不会执行else
        continue  # 跳出本次循环 可以执行else
    print('墨染在跑圈,当前是第' + str(i) + '圈')  # 3.循环的代码块
else:  # 在循环正常终止的情况下会执行
    print('已经跑完了,优秀')

# while True:
#     break;  

五 for循环

1.可迭代对象:

range()、字符串、列表、元组、字典、集合

2.continue----跳出本次循环,进入循环

3.break----终止本次循环,循环结束

# for in循环:  循环次数由 可迭代对象 len()决定
# 循环多少次:range(开始位置,结束位置,步长)
# 变量值不受影响
# 计数循环 迭代循环

for i in range(1, 20, 2):
    print(i, end=',')
    i = 'python'
    print(i, '*')
else:
    print('循环正常执行完毕!')

for i in range(100):
    print(i)
    # 偶数
    if i % 2 == 0 or i % 3 == 0:
        continue
    elif i % 5 == 0:
        break
else:
    print('循环正常执行完毕!')

六 练习

在这里插入图片描述

print('>1.九九乘法表:jjtable()\n>2.猜字游戏(10次机会):rand()')

# 九九乘法表
def jjtable():
    i = 1
    while i < 10:
        j = 1
        while j <= i:
            # --:0>2    0为填充   >右对齐   2为长度
            print(f'{j}*{i}={i * j:0>2}', end='\t')
            j += 1
        print()
        i += 1   
jjtable()

# 猜字游戏
def rand():
    import random
    r = random.randint(0, 101)
    print('猜字游戏(10次机会) ' + str(r))
    i = 0
    while i < 10:
        try:
            i += 1
            a = float(input(f'这是第{i}次机会,请输入一个数字0-100:'))
            if a < 0 or a >= 100:
                print("请输入[0,100]之间的整数")
            elif a > r:
                print('你输入的整数偏大')
            elif a < r:
                print('你输入的整数偏小')
            elif a == r:
                print('恭喜你猜对了')
                break
        except:
            print('请输入正确的数字!')
    else:
        print('你的10次机会已用完!游戏失败')
rand()              
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值