教程集 www.jiaochengji.com
教程集 >  Python编程  >  Python入门  >  正文 Python3条件控制

Python3条件控制

发布时间:2021-12-15   编辑:jiaochengji.com
教程集为您提供Python3条件控制等资源,欢迎您收藏本站,我们将为您提供最新的Python3条件控制资源

Python 条件控制

if 语句

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

<pre class="brush:html;toolbar:false">if condition_1:     statement_block_1 elif condition_2:     statement_block_2 else:     statement_block_3</pre>

如果 "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语句。

实例

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

<pre class="brush:html;toolbar:false">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>')</pre>

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

<pre class="brush:html;toolbar:false">python dog.py Age of the dog: 1 about 14 human years</pre>

实例

<pre class="brush:html;toolbar:false"># 程序演示了 == 操作符 # 使用数字 print(5 == 6) # 使用变量 x = 5 y = 8 print(x == y)</pre>

以上实例输出结果:

<pre class="brush:html;toolbar:false">False False</pre>

high_low.py文件:

<pre class="brush:html;toolbar:false">#!/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.")</pre>

您可能感兴趣的文章:
Python3条件控制
python3怎么获取控制台输入的数据
php5中哪几种流程结构
php中有哪几种流程控制结构
一文了解Python虚拟环境
python3有serial库吗
linux shell学习之shell流程控制
C#进度条ProgressBar和定时器Timer控件的应用举例
jQuery条目展示插件 Easy Paginate
使用条件语句

[关闭]
~ ~