python的条件控制语句

1.if语句
if 条件:
  语句1
else:
  语句2
(1)语句的缩进部分是一个完整的代码块
if age >= 18:
    print '您已经成年,欢迎进入网吧'
else:
    print '你未满18'
if 要判断的条件:
    条件成立的时候要做的事情
else:
    条件不成立的时候,要做的事情

(2)逻辑运算符
and 与
or 或
not 非

2.elif语句
if 条件1:
   语句1
elif 条件2:
   语句2
else:
   语句3

3.if嵌套
if 条件1:
   语句1
   if 条件2(满足条件1的基础上):
      语句2
   else:
      语句3
else:
   语句4(条件1不满足,执行代码)


4.综合案例
(1)产生随机数
import random  导入随机数模块(导入的语句要放在文件的顶部,这样方便下方的代码,在需要的时候使用工具)
random.randint(a.b) a永远要大于b
random.randint(1,10) 生成1-10之间的随机数,包括1和10
(2)石头剪刀步游戏
#1.玩家出拳
player = int(raw_input('请输入你要出的拳:(石头1,剪刀2,布3)'))
print '玩家出拳为 %d' %player
#2.电脑出拳
computer = random.randint(1,3)
print '电脑出拳为 %d' %computer
#3.比赛
if (player == 1 and computer == 2) \
       or (player == 2 and computer == 3) \
               or (player ==3 and computer ==1):
                  print '玩家赢'
elif player == computer:
                   print '平局'
else:
                   print '玩家输'


(3)判断润年
year = int(raw_input('请输入年份:'))
if (year % 4 == 0 and (not year % 100 == 0)) or (year % 400 == 0):
    print '%d是闰年' %year
else:
       print '%d不是闰年' %year


(4)输入年月,输出本月有多少天
year = int(raw_input('请输入年份:'))
month = int(raw_input('请输入月份:'))
if month == (1 or 3 or 5 or 7 or 8 or 10 or 12):
     print '本月31天'
elif month == (4 or 6 or 8 or 11):
    print '本月为30天'
elif (year % 4 == 0 and (not year % 100 == 0)) or (year % 400 == 0) and month == 2:
     print '本月为29天'
else:
     print '本月位28天'

扫描二维码关注公众号,回复: 2992579 查看本文章

猜你喜欢

转载自blog.csdn.net/qq_42224396/article/details/82085065