Python之if判断语句

Python之if判断语句

  • if判断语句格式

if 要判断的条件(True):
条件成立的时候,要做的事情
elif 再判断的条件
else:
条件不成立的时候要做的事情

  • if判断语句示例

判断年龄是否满18岁:

age = 20
if age >= 18:
    print('haha',age)
else:
    print('sorry')
print('@@@@@@@')

分数等级:

score = 79
if 90 < score <= 100:
     grade = 'A'
elif 80 < score <= 90:
     grade = 'B'
else:
     grade = 'C'

print(grade)

判断用户的输入是否为空:

value = input('Value:')
if value == '':
   print('请输入合法的值!!!')
if not value:
   print('请输入合法的值!!!')
  • if判断语句案例

程序需求:
1.从控制台输入要出的拳 —石头(1)/剪刀(2)/布(3)
2.电脑随即出拳
3.比较胜负
石头 胜 剪刀
剪刀 胜 布
布 胜 石头

这里说明一个python程序中生成随机数的模块random:

>>> import random  #python的第三方模块库
>>> random.randint(12,20) #返回[12,20]之间的整数
16
>>> random.randint(12,20)
13
>>> random.randint(12,20)
12
>>> random.randint(12,20)
20
# 下限必须小于上限

程序编写如下:

import random
# print(random.randint(2,10))

# 1.从控制台输入要输出的拳 ---石头(1)/剪刀(2)/布(3)
player = int(input('请输入你要出的拳头:---石头(1)/剪刀(2)/布(3)'))

# 2.让电脑随即出拳
computer = random.randint(1,3)
print('玩家:%d,电脑:%d' %(player,computer))

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('玩家输了~~~')
  • 逻辑运算符号

and
条件1 and 条件2
两个条件同时满足,就返回True
只要有一个条件不满足,就返回False

or
条件1 or 条件2
两个条件只要有一个满足,就返回True
两个条件都不满足的时候,就返回False

示例:

python_score = 40
c_score = 50

if python_score >= 60 or c_score >=60:  ##此处or代表满足一个则考试通过,若换成and,则必须两个条件都满足考试通过
    print('考试通过')
else:
    print('请继续努力')
  • if判断语句综合练习

1.判断闰年?
用户输入年份year, 判断是否为闰年?
year能被4整除但是不能被100整除 或者 year能被400整除, 那么就是闰年;

year = int(input('请输入年份'))

if   ((year % 4 == 0 and year % 100 != 0)
     or (year % 400 == 0)):
    print('闰年')
else:
    print('平年')

2.随机选择一个三位以内的数字作为答案。用户输入一个数字,程序会提示大了或是小了

user = int(input('请输入一个数字:'))

import random

computer = random.randint(0, 999)
if user < computer:
    print('小了')
elif user > computer:
    print('大了')
else:
    print('恭喜你猜对了')

3.输入年、月,输出本月有多少天。合理选择分支语句完成设计任务。
输入样例1:2004 2
输出结果1:本月29天
输入样例2:2010 4
输出结果2:本月30天

year = int(input('请输入年份:'))
month = int(input('请输入月份:'))

if (month == 4 or month == 6 or month == 9 or month == 11):
    print('%d有30天' % (month))
elif (month == 2):
    if ((year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)):
        print('%d有29天' % (month))
    else:
        print('%d有28天' % (month))

else:
    print('%d有31天' % (month))

4.根据用于指定月份,打印该月份所属的季节。
**提示: 3,4,5 春季 6,7,8 夏季 9,10,11 秋季 12, 1, 2 冬季

season = int(input('请输入月份'))

if (season==3 or season==4 or season==5):
    print('春季')
elif (season==6 or season==7 or season==8):
    print('夏季')
elif(season==9 or season==10 or season==11):
    print('秋季')
else:
    print('冬季')

END

猜你喜欢

转载自blog.csdn.net/weixin_44828950/article/details/90574662
今日推荐