Lesson 62 python中if语句的基本知识与示例
文章目录
- 1. 最基本的if条件判断
- 2. if-else判断
- 3. if案例(电脑猜拳游戏)
- 4. if练习
- 4.1 判断闰年
- 4.2 随机选择一个三位以内的数字作为答案。用户输入一个数字,程序会提示大了或是小了
1. 最基本的if条件判断
if 要判断的条件:
条件成立的时候做的事情
# 1.定义一个变量
age = 20
# 2.判断年龄是否满足18
if age >= 18:
print(age)
else:
print('sorry~')
2. if-else判断
if 要判断的条件(True):
条件成立的时候,要做的事情
elif 要判断的条件(True):
...
else:
条件不成立的时候要做的事
score = 79
if 90 < score <=100:
grade = 'A'
elif 80 < score <= 90:
grade = 'B'
else:
grade = 'C'
print(grade)
判断用户的输入是否为空
方法1:value = input('Value:')
if value == '':
print('请输入合法的值')
方法2:value = input('Value:')
if not value:
print('请输入合法的值')
3. if案例(电脑猜拳游戏)
- 需求:
1.从控制台输入要出的拳 —石头(1)/剪刀(2)/布(3)
2.电脑随即出拳
3.比较胜负
石头 胜 剪刀
剪刀 胜 布
布 胜 石头
补充内容:python第三方模块
>>> import random
>>> random.randint(12,20) 返回[12,20]之间的整数
16
>>> random.randint(12,20)
14
>>> random.randint(12,20)
13
>>> random.randint(12,20)
14
# 下限必须小于上限
>>> random.randint(20,12)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/kiosk/anaconda3/lib/python3.7/random.py", line 222, in randint
return self.randrange(a, b+1)
File "/home/kiosk/anaconda3/lib/python3.7/random.py", line 200, in randrange
raise ValueError("empty range for randrange() (%d,%d, %d)" % (istart, istop, width))
ValueError: empty range for randrange() (20,13, -7)
# 结果永远是20
>>> random.randint(20,20)
20
导入生成随机数的包
输出12到20之间的随机整数
左区间必须小于或等于右区间,若左边的数字大于右边,则报错
当左区间等于右区间时,永远只能输出这一个数
import random
# 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('玩家 win')
elif player == computer:
print('平局')
else:
print('玩家 lose')
4. if练习
4.1 判断闰年
用户输入年份year, 判断是否为闰年?
year能被4整除但是不能被100整除 或者 year能被400整除, 那么就是闰年
year = int(input('Year:'))
if (year % 4 == 0 and year %100 !=0) or (year %400 == 0):
print('%d是闰年' %(year))
else:
print('%d不是闰年' %(year))
运行代码, 先用1995测试
可以看到, 运行的结果是:1995不是闰年
运行代码, 再用2000测试
可以看到,运行的结果是2000是闰年
4.2 随机选择一个三位以内的数字作为答案。用户输入一个数字,程序会提示大了或是小了
import random
num = random.randint(0,999)