电脑也会做决定?

你可能会想,电脑不就是按指令执行吗?它怎么"思考"?

条件判断就是让电脑根据不同情况做不同的事情。

就像你每天出门前会想:

  • 下雨了?带伞
  • 没下雨?带太阳镜

电脑也能做这样的判断!

if语句的基本语法

if 条件:
    # 条件成立时执行的代码
    pass

注意冒号和缩进! 这是Python最重要的两个语法:

  • 冒号表示条件判断的开始
  • 缩进(4个空格)表示属于这个if的代码块
age = 18

if age >= 18:
    print("你已经成年了!")
    print("可以办身份证了!")

运行结果:

你已经成年了!
可以办身份证了!

if-else:二选一

if 条件:
    # 条件成立时执行
else:
    # 条件不成立时执行
age = 16

if age >= 18:
    print("你已经成年了!")
else:
    print("你还没成年!")

运行结果:

你还没成年!

if-elif-else:多选一

if 条件1:
    # 条件1成立时执行
elif 条件2:
    # 条件2成立时执行
elif 条件3:
    # 条件3成立时执行
else:
    # 以上条件都不成立时执行
score = 85

if score >= 90:
    print("优秀!")
elif score >= 80:
    print("良好!")
elif score >= 60:
    print("及格!")
else:
    print("不及格!")

运行结果:

良好!

比较运算符(记住这些就够了)

运算符 说明 例子
> 大于 age > 18
< 小于 age < 18
>= 大于等于 age >= 18
<= 小于等于 age <= 18
== 等于(注意是两个等号!) age == 18
!= 不等于 age != 18

重点注意:=是赋值,==是判断相等!

# 错误写法
if age = 18:  # 报错!=是赋值,不能用在if里

# 正确写法
if age == 18:  # 判断age是否等于18
    print("你刚好18岁!")

逻辑运算符(组合条件)

and:并且

两个条件都要成立。

age = 25
has_job = True

if age >= 18 and has_job:
    print("你已经成年,而且有工作!")

or:或者

只要有一个条件成立就行。

weather = "晴天"
weekend = True

if weather == "晴天" or weekend:
    print("可以出去玩!")

not:否定

取反。

is_raining = False

if not is_raining:
    print("没下雨,可以出门!")

复杂的条件判断

# 判断是否能办信用卡
age = 25
has_job = True
has_bad_credit = False

if age >= 18 and has_job and not has_bad_credit:
    print("你可以办信用卡!")
else:
    print("你不符合办信用卡的条件!")

# 判断要不要带伞
weather = "多云"
temperature = 28

if weather == "下雨":
    print("带伞!")
elif temperature > 30:
    print("带太阳镜!")
elif weather == "多云" and temperature < 20:
    print("带外套!")
else:
    print("什么都不用带!")

嵌套if(if里面再套if)

age = 20
has_job = True

if age >= 18:
    if has_job:
        print("你已经是成年人,而且有工作!")
    else:
        print("你是成年人,但没有工作!")
else:
    print("你还没成年!")

嵌套不要太深,超过3层就考虑重构了!

常见坑及解决方案

坑1:忘记冒号

if age >= 18  # 报错!缺少冒号
    print("成年")

解决: 记得if后面加冒号!

坑2:缩进不一致

if age >= 18:
    print("成年")
    print("哈哈")  # 缩进不一致会报错

解决: Python推荐用4个空格,不要用Tab和空格混用!

坑3:用=代替==

if age = 18:  # 报错!=是赋值
    print("刚好18")

解决: 判断用==,赋值用=

实战小项目1:计算器

# 简单的加法计算器
num1 = float(input("请输入第一个数字:"))
num2 = float(input("请输入第二个数字:"))
operator = input("请输入运算符(+、-、*、/):")

if operator == "+":
    result = num1 + num2
    print(f"{num1} + {num2} = {result}")
elif operator == "-":
    result = num1 - num2
    print(f"{num1} - {num2} = {result}")
elif operator == "*":
    result = num1 * num2
    print(f"{num1} * {num2} = {result}")
elif operator == "/":
    if num2 == 0:
        print("除数不能为0!")
    else:
        result = num1 / num2
        print(f"{num1} / {num2} = {result}")
else:
    print("不支持的运算符!")

实战小项目2:成绩评级系统

score = float(input("请输入你的成绩(0-100):"))

if score < 0 or score > 100:
    print("成绩必须在0-100之间!")
elif score >= 90:
    print("优秀!你的成绩是:" + str(score))
elif score >= 80:
    print("良好!你的成绩是:" + str(score))
elif score >= 60:
    print("及格!你的成绩是:" + str(score))
else:
    print("不及格!你的成绩是:" + str(score))
    print("还要继续努力啊!")

实战小项目3:猜数字游戏

import random

# 电脑随机生成1-100的数字
secret = random.randint(1, 100)

while True:  # 无限循环,直到猜对
    guess = int(input("猜一个1-100的数字:"))

    if guess < secret:
        print("太小了,再大点!")
    elif guess > secret:
        print("太大了,再小点!")
    else:
        print("恭喜你猜对了!数字就是" + str(secret))
        break  # 退出循环

试试看,你能猜几次猜对?

本章小结

  • if语句:基本条件判断
  • if-else:二选一
  • if-elif-else:多选一
  • 比较运算符><>=<===!=
  • 逻辑运算符andornot
  • 嵌套if:条件里再套条件

条件判断让电脑学会了思考,但只能做一次判断。下一章我们学习循环,让电脑一次做1000件事!

继续学下去,马上就能做实用项目了!