Python3条件控制

Python 条件控制

if 语句

Python中if语句的一般形式如下所示:

if condition_1:
    statement_block_1
elif condition_2:
    statement_block_2
else:
    statement_block_3

如果 "condition_1" 为 True 将执行 "statement_block_1" 块语句,如果 "condition_1" 为False,将判断 "condition_2",如果"condition_2" 为 True 将执行 "statement_block_2" 块语句,如果 "condition_2" 为False,将执行"statement_block_3"块语句。

Python中用elif代替了else if,所以if语句的关键字为:if – elif – else。

注意:

1、每个条件后面要使用冒号(:),表示接下来是满足条件后要执行的语句块。

2、使用缩进来划分语句块,相同缩进数的语句在一起组成一个语句块。

3、在Python中没有switch – case语句。

实例

以下实例演示了狗的年龄计算判断:

age = int(input("Age of the dog: "))
print()
if age < 0:  print("This can hardly be true!") elif age == 1:  print("about 14 human years") elif age == 2:  print("about 22 human years") elif age > 2:
  human = 22 + (age -2)*5
   print("Human years: ", human)

### 
input('press Return>')

将以上脚本保存在dog.py文件中,并执行该脚本:

python dog.py
Age of the dog: 1

about 14 human years

实例

# 程序演示了 == 操作符
# 使用数字
print(5 == 6)
# 使用变量
x = 5
y = 8
print(x == y)

以上实例输出结果:

False
False

high_low.py文件:

#!/usr/bin/python3 
# 该实例演示了数字猜谜游戏
number = 7
guess = -1
print("Guess the number!")
while guess != number:
    guess = int(input("Is it... "))
 
    if guess == number:
        print("Hooray! You guessed it right!")
    elif guess < number:         print("It's bigger...")     elif guess > number:
        print("It's not so big.")

相关推荐

  1. python笔记(12)条件控制

    2023-12-26 21:06:03       13 阅读
  2. python 条件控制语句(基础)学习笔记

    2023-12-26 21:06:03       36 阅读
  3. 3python布尔类型和条件表达式

    2023-12-26 21:06:03       32 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-26 21:06:03       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-26 21:06:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-26 21:06:03       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-26 21:06:03       20 阅读

热门阅读

  1. 阿里云服务器助力企业出海跨境电商解决方案

    2023-12-26 21:06:03       41 阅读
  2. 【Unity】对象池技术

    2023-12-26 21:06:03       38 阅读
  3. arm32 arm64 读取PMCCNTR cpu cycle counter

    2023-12-26 21:06:03       69 阅读
  4. 【Git使用小技巧】一个项目使用多个远程仓库

    2023-12-26 21:06:03       43 阅读
  5. .NET 7(C#)配置使用log4net日志框架的方法

    2023-12-26 21:06:03       29 阅读
  6. 前端面试题html

    2023-12-26 21:06:03       32 阅读
  7. Day01-BootStrap

    2023-12-26 21:06:03       31 阅读