Chapter 3: Conditional | Python for Everybody 讲义笔记_En

news2024/9/23 11:22:58

文章目录

  • Python for Everybody
    • 课程简介
    • Chapter 3: Conditional execution
      • Boolean expressions
      • Logical operators
      • Conditional execution
      • Alternative execution
      • Chained conditionals
      • Nested conditionals
      • Catching exceptions using try and except
      • Short-circuit evaluation of logical expressions
      • Debugging
      • Glossary


Python for Everybody


课程简介

Python for Everybody 零基础程序设计(Python 入门)

  • This course aims to teach everyone the basics of programming computers using Python. 本课程旨在向所有人传授使用 Python 进行计算机编程的基础知识。
  • We cover the basics of how one constructs a program from a series of simple instructions in Python. 我们介绍了如何通过 Python 中的一系列简单指令构建程序的基础知识。
  • The course has no pre-requisites and avoids all but the simplest mathematics. Anyone with moderate computer experience should be able to master the materials in this course. 该课程没有任何先决条件,除了最简单的数学之外,避免了所有内容。任何具有中等计算机经验的人都应该能够掌握本课程中的材料。
  • This course will cover Chapters 1-5 of the textbook “Python for Everybody”. Once a student completes this course, they will be ready to take more advanced programming courses. 本课程将涵盖《Python for Everyday》教科书的第 1-5 章。学生完成本课程后,他们将准备好学习更高级的编程课程。
  • This course covers Python 3.

在这里插入图片描述

coursera

Python for Everybody 零基础程序设计(Python 入门)

Charles Russell Severance
Clinical Professor

在这里插入图片描述

个人主页
Twitter

在这里插入图片描述

University of Michigan


课程资源

coursera原版课程视频
coursera原版视频-中英文精校字幕-B站
Dr. Chuck官方翻录版视频-机器翻译字幕-B站

PY4E-课程配套练习
Dr. Chuck Online - 系列课程开源官网


Chapter 3: Conditional execution

We look at how Python executes some statements and skips others.


Boolean expressions

A boolean expression is an expression that is either true or false. The following examples use the operator ==, which compares two operands and produces True if they are equal and False otherwise:

>>> 5 == 5
True
>>> 5 == 6
False

True and False are special values that belong to the class bool; they are not strings:

>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>

The == operator is one of the comparison operators; the others are:

x != y               # x is not equal to y
x > y                # x is greater than y
x < y                # x is less than y
x >= y               # x is greater than or equal to y
x <= y               # x is less than or equal to y
x is y               # x is the same as y
x is not y           # x is not the same as y

Although these operations are probably familiar to you, the Python symbols are different from the mathematical symbols for the same operations. A common error is to use a single equal sign (=) instead of a double equal sign (==). Remember that = is an assignment operator and == is a comparison operator. There is no such thing as =< or =>.

Logical operators

There are three logical operators: and, or, and not. The semantics (meaning) of these operators is similar to their meaning in English. For example,

x > 0 and x < 10

is true only if x is greater than 0 and less than 10.

n%2 == 0 or n%3 == 0 is true if either of the conditions is true, that is, if the number is divisible by 2 or 3.

Finally, the not operator negates a boolean expression, so not (x > y) is true if x > y is false; that is, if x is less than or equal to y.

Strictly speaking, the operands of the logical operators should be boolean expressions, but Python is not very strict. Any nonzero number is interpreted as “true.”

>>> 17 and True
True

This flexibility can be useful, but there are some subtleties to it that might be confusing. You might want to avoid it until you are sure you know what you are doing.

Conditional execution

In order to write useful programs, we almost always need the ability to check conditions and change the behavior of the program accordingly. Conditional statements give us this ability. The simplest form is the if statement:

if x > 0 :
    print('x is positive')

The boolean expression after the if statement is called the condition. We end the if statement with a colon character (😃 and the line(s) after the if statement are indented.


在这里插入图片描述


If Logic
If the logical condition is true, then the indented statement gets executed. If the logical condition is false, the indented statement is skipped.

if statements have the same structure as function definitions or for loops1. The statement consists of a header line that ends with the colon character (😃 followed by an indented block. Statements like this are called compound statements because they stretch across more than one line.

There is no limit on the number of statements that can appear in the body, but there must be at least one. Occasionally, it is useful to have a body with no statements (usually as a place holder for code you haven’t written yet). In that case, you can use the pass statement, which does nothing.

if x < 0 :
    pass          # need to handle negative values!

If you enter an if statement in the Python interpreter, the prompt will change from three chevrons to three dots to indicate you are in the middle of a block of statements, as shown below:

>>> x = 3
>>> if x < 10:
...    print('Small')
...
Small
>>>

When using the Python interpreter, you must leave a blank line at the end of a block, otherwise Python will return an error:

>>> x = 3
>>> if x < 10:
...    print('Small')
... print('Done')
  File "<stdin>", line 3
    print('Done')
        ^
SyntaxError: invalid syntax

A blank line at the end of a block of statements is not necessary when writing and executing a script, but it may improve readability of your code.

Alternative execution

A second form of the if statement is alternative execution, in which there are two possibilities and the condition determines which one gets executed. The syntax looks like this:

if x%2 == 0 :
    print('x is even')
else :
    print('x is odd')

If the remainder when x is divided by 2 is 0, then we know that x is even, and the program displays a message to that effect. If the condition is false, the second set of statements is executed.


在这里插入图片描述


If-Then-Else Logic
Since the condition must either be true or false, exactly one of the alternatives will be executed. The alternatives are called branches, because they are branches in the flow of execution.

Chained conditionals

Sometimes there are more than two possibilities and we need more than two branches. One way to express a computation like that is a chained conditional:

if x < y:
    print('x is less than y')
elif x > y:
    print('x is greater than y')
else:
    print('x and y are equal')

elif is an abbreviation of “else if.” Again, exactly one branch will be executed.


在这里插入图片描述


If-Then-ElseIf Logic
There is no limit on the number of elif statements. If there is an else clause, it has to be at the end, but there doesn’t have to be one.

if choice == 'a':
    print('Bad guess')
elif choice == 'b':
    print('Good guess')
elif choice == 'c':
    print('Close, but not correct')

Each condition is checked in order. If the first is false, the next is checked, and so on. If one of them is true, the corresponding branch executes, and the statement ends. Even if more than one condition is true, only the first true branch executes.

Nested conditionals

One conditional can also be nested within another. We could have written the three-branch example like this:

if x == y:
    print('x and y are equal')
else:
    if x < y:
        print('x is less than y')
    else:
        print('x is greater than y')

The outer conditional contains two branches. The first branch contains a simple statement. The second branch contains another if statement, which has two branches of its own. Those two branches are both simple statements, although they could have been conditional statements as well.


在这里插入图片描述


Nested If Statements
Although the indentation of the statements makes the structure apparent, nested conditionals become difficult to read very quickly. In general, it is a good idea to avoid them when you can.

Logical operators often provide a way to simplify nested conditional statements. For example, we can rewrite the following code using a single conditional:

if 0 < x:
    if x < 10:
        print('x is a positive single-digit number.')

The print statement is executed only if we make it past both conditionals, so we can get the same effect with the and operator:

if 0 < x and x < 10:
    print('x is a positive single-digit number.')

Catching exceptions using try and except

Earlier we saw a code segment where we used the input and int functions to read and parse an integer number entered by the user. We also saw how treacherous doing this could be:

>>> prompt = "What is the air velocity of an unladen swallow?\n"
>>> speed = input(prompt)
What is the air velocity of an unladen swallow?
What do you mean, an African or a European swallow?
>>> int(speed)
ValueError: invalid literal for int() with base 10:
>>>

When we are executing these statements in the Python interpreter, we get a new prompt from the interpreter, think “oops”, and move on to our next statement.

However if you place this code in a Python script and this error occurs, your script immediately stops in its tracks with a traceback. It does not execute the following statement.

Here is a sample program to convert a Fahrenheit temperature to a Celsius temperature:

inp = input('Enter Fahrenheit Temperature: ')
fahr = float(inp)
cel = (fahr - 32.0) * 5.0 / 9.0
print(cel)

# Code: http://www.py4e.com/code3/fahren.py

If we execute this code and give it invalid input, it simply fails with an unfriendly error message:

python fahren.py
Enter Fahrenheit Temperature:72
22.22222222222222
python fahren.py
Enter Fahrenheit Temperature:fred
Traceback (most recent call last):
  File "fahren.py", line 2, in <module>
    fahr = float(inp)
ValueError: could not convert string to float: 'fred'

There is a conditional execution structure built into Python to handle these types of expected and unexpected errors called “try / except”. The idea of try and except is that you know that some sequence of instruction(s) may have a problem and you want to add some statements to be executed if an error occurs. These extra statements (the except block) are ignored if there is no error.

You can think of the try and except feature in Python as an “insurance policy” on a sequence of statements.

We can rewrite our temperature converter as follows:

inp = input('Enter Fahrenheit Temperature:')
try:
    fahr = float(inp)
    cel = (fahr - 32.0) * 5.0 / 9.0
    print(cel)
except:
    print('Please enter a number')

# Code: http://www.py4e.com/code3/fahren2.py

Python starts by executing the sequence of statements in the try block. If all goes well, it skips the except block and proceeds. If an exception occurs in the try block, Python jumps out of the try block and executes the sequence of statements in the except block.

python fahren2.py
Enter Fahrenheit Temperature:72
22.22222222222222
python fahren2.py
Enter Fahrenheit Temperature:fred
Please enter a number

Handling an exception with a try statement is called catching an exception. In this example, the except clause prints an error message. In general, catching an exception gives you a chance to fix the problem, or try again, or at least end the program gracefully.

Short-circuit evaluation of logical expressions

When Python is processing a logical expression such as x >= 2 and (x/y) > 2, it evaluates the expression from left to right. Because of the definition of and, if x is less than 2, the expression x >= 2 is False and so the whole expression is False regardless of whether (x/y) > 2 evaluates to True or False.

When Python detects that there is nothing to be gained by evaluating the rest of a logical expression, it stops its evaluation and does not do the computations in the rest of the logical expression. When the evaluation of a logical expression stops because the overall value is already known, it is called short-circuiting the evaluation.

While this may seem like a fine point, the short-circuit behavior leads to a clever technique called the guardian pattern. Consider the following code sequence in the Python interpreter:

>>> x = 6
>>> y = 2
>>> x >= 2 and (x/y) > 2
True
>>> x = 1
>>> y = 0
>>> x >= 2 and (x/y) > 2
False
>>> x = 6
>>> y = 0
>>> x >= 2 and (x/y) > 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>>

The third calculation failed because Python was evaluating (x/y) and y was zero, which causes a runtime error. But the first and the second examples did not fail because in the first calculation y was non zero and in the second one the first part of these expressions x >= 2 evaluated to False so the (x/y) was not ever executed due to the short-circuit rule and there was no error.

We can construct the logical expression to strategically place a guard evaluation just before the evaluation that might cause an error as follows:

>>> x = 1
>>> y = 0
>>> x >= 2 and y != 0 and (x/y) > 2
False
>>> x = 6
>>> y = 0
>>> x >= 2 and y != 0 and (x/y) > 2
False
>>> x >= 2 and (x/y) > 2 and y != 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>>

In the first logical expression, x >= 2 is False so the evaluation stops at the and. In the second logical expression, x >= 2 is True but y != 0 is False so we never reach (x/y).

In the third logical expression, the y != 0 is after the (x/y) calculation so the expression fails with an error.

In the second expression, we say that y != 0 acts as a guard to insure that we only execute (x/y) if y is non-zero.

Debugging

The traceback Python displays when an error occurs contains a lot of information, but it can be overwhelming. The most useful parts are usually:

  • What kind of error it was, and

  • Where it occurred.

Syntax errors are usually easy to find, but there are a few gotchas. Whitespace errors can be tricky because spaces and tabs are invisible and we are used to ignoring them.

>>> x = 5
>>>  y = 6
  File "<stdin>", line 1
    y = 6
    ^
IndentationError: unexpected indent

In this example, the problem is that the second line is indented by one space. But the error message points to y, which is misleading. In general, error messages indicate where the problem was discovered, but the actual error might be earlier in the code, sometimes on a previous line.

In general, error messages tell you where the problem was discovered, but that is often not where it was caused.

Glossary

body
The sequence of statements within a compound statement.
boolean expression
An expression whose value is either True or False.
branch
One of the alternative sequences of statements in a conditional statement.
chained conditional
A conditional statement with a series of alternative branches.
comparison operator
One of the operators that compares its operands: ==, !=, >, <, >=, and <=.
conditional statement
A statement that controls the flow of execution depending on some condition.
condition
The boolean expression in a conditional statement that determines which branch is executed.
compound statement
A statement that consists of a header and a body. The header ends with a colon (😃. The body is indented relative to the header.
guardian pattern
Where we construct a logical expression with additional comparisons to take advantage of the short-circuit behavior.
logical operator
One of the operators that combines boolean expressions: and, or, and not.
nested conditional
A conditional statement that appears in one of the branches of another conditional statement.
traceback
A list of the functions that are executing, printed when an exception occurs.
short circuit
When Python is part-way through evaluating a logical expression and stops the evaluation because Python knows the final value for the expression without needing to evaluate the rest of the expression.


  1. We will learn about functions in Chapter 4 and loops in Chapter 5. ↩︎

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/732503.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

从零开始simulink自定义代码生成----自定义硬件驱动库文件(3)

文章目录 前言C mex文件mdlInitializeSizesmdlInitializeSampleTimesmdlOutputsmdlTerminatemdlRTWc文件结尾编译c文件 tlc文件Start函数Outputs函数模型及生成的代码 总结 前言 在很早的时候&#xff0c;做过一些Simulink自定义硬件驱动库的相关探索&#xff0c;但是后面没有…

惊喜!Alibaba架构师终于发布“微服务架构与实践”文档

前言&#xff1a; 对于微服务架构的概念&#xff0c;相信大家应该都不陌生&#xff0c;无论使用 Apache Dubbo、还是 Spring Cloud&#xff0c;都可以去尝试微服务&#xff0c;把复杂而庞大的业务系统拆分成一些更小粒度且独立部署的 Rest 服务。 但是这个过程&#xff0c;具…

单表查询练习

查看表的字符集编码 show create table tbname; 查看系统默认字符集 SHOW VARIABLES LIKE character_set_database; 显示所有可用的字符集 SHOW CHARACTER SET; 修改系统默认字符集 ①在 /etc/my.cnf 文件中的 [mysqld] 下添加&#xff1a; ②重启数据服务 systemctl re…

Linux:PXE网络装机

要实现需要开启以下服务 dhcp --- 开机没有u盘或光盘的引导电脑会去寻找网络中的引导 tftp --- 用于引导系统 ftp&& http --- 制作yum仓库让引导的系统去ftp或者http上找rpm包 1.ftp&& http yum仓库搭建 Linux&#xff1a;YUM仓库服务_鲍海超-GNUBHC…

Mycat【Mycat安全设置(SQL拦截白名单、SQL拦截黑名单、Mycat-web安装 )】(九)-全面详解(学习总结---从入门到深化)

目录 Mycat安全设置_user标签权限控制 Mycat安全设置_privileges标签权限控制 Mycat安全设置_SQL拦截白名单 Mycat安全设置_SQL拦截黑名单 Mycat性能监控_Mycat-web安装 Mycat性能优化 Mycat实施指南 Mycat安全设置_user标签权限控制 目前 Mycat 对于中间件的连接控制并…

Mac矢量绘图工具 Sketch

Sketch是一款适用于 UI/UX 设计、网页设计、图标制作等领域的矢量绘图软件&#xff0c; 其主要特点如下&#xff1a; 1. 简单易用的界面设计&#xff1a;Sketch 的用户界面简洁明了&#xff0c;使得用户可以轻松上手操作&#xff0c;不需要复杂的学习过程。 2. 强大的矢量绘图功…

Lua快速入门笔记

文章目录 Lua快速入门笔记前言1、Lua概述2、Lua环境安装3、快速体验Lua编程4、数据类型5、变量6、循环7、流程控制8、函数9、运算符10、字符串11、数组12、迭代器13、表14、模块与包15、元表16、协同程序 Lua快速入门笔记 前言 本文是笔者参考菜鸟教程对Lua的一个快速入门学习&…

2023-07-08:RabbitMQ如何做到消息不丢失?

2023-07-08&#xff1a;RabbitMQ如何做到消息不丢失&#xff1f; 答案2023-07-08&#xff1a; 1.持久化 发送消息时设置delivery_mode属性为2&#xff0c;使消息被持久化保存到磁盘&#xff0c;即使RabbitMQ服务器宕机也能保证消息不丢失。同时&#xff0c;创建队列时设置du…

vue开发:Vue的状态管理 - Vuex

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态&#xff0c;并以相应的规则保证状态以一种可预测的方式发生变化。 我个人的理解是&#xff0c;如果有一些公共的数据需要在多个组件中共享或者某一个状态的改变会影响多个组件&a…

基础之linux常用命令精华

目录 第一章.shell 1.1查看内部命令 1.2外部命令存放于 echo $PATH 一个一个找&#xff0c;找到为止&#xff0c;找不到就报无命令 第二章.linux常用命令 2.1.编辑linux命令行的辅助操作 2.2命令帮助help和--help&#xff0c;man手册使用 2.3.目录和文件的管理命令 2.…

消失的她-InsCode Stable Diffusion 美图活动一期

一、 Stable Diffusion 模型在线使用地址&#xff1a; https://inscode.csdn.net/inscode/Stable-Diffusion 二、模型相关版本和参数配置&#xff1a; Model: Cute_Animals Version: v1.2.0 Size: 512x512 Model hash: 57bd734213 Steps: 20 Sampler: Heun CFG scale: 7 三、图…

操作系统中的线程进程和同步异步和并发并行

目录 一、进程和线程1.1 进程1.2 线程1.3 实现多任务的方法1.3.1 使用多进程实现多任务1.3.2 使用多线程(单个进程包含多个线程)实现多任务1.3.3 使用多进程多进程实现多任务 1.4 进程和线程的比较1.5 Java的多线程模型的应用 二、同步和异步2.1 同步2.2 异步 三、并发与并行3.…

QTday2

点击登录&#xff0c;登陆成功&#xff0c;跳转到新的界面 主函数 #include "widget.h" #include "second.h" #include <QApplication>int main(int argc, char *argv[]) {QApplication a(argc, argv);Widget w;w.show();Second s;QObject::connect…

MySQL数据库介绍流程(最新mysql)

版本介绍 第一步&#xff1a;下载MySQL数据库 1、下载地址&#xff1a;http://dev,mysql.com/downloads/windows/installer/8.0html 2、就是直接搜索&#xff1a;mysql官方 msyql官方网站 这里就安装成功 第二步&#xff1a;这么启动和停止mysql 第三步&#xff1a;这么快捷停…

B - Get an Even String

Get an Even String - 洛谷 | 计算机科学教育新生态 (luogu.com.cn) 题意&#xff1a;题目要使字符串变成偶字符串&#xff0c;对于每一个奇数i都和后面i1的位置字符相同。求给定字符串最少去掉几个字符能得到偶字符串。 解题思路&#xff1a;贪心&#xff0c;找每次第一对出现…

黑客(网安)自学

建议一&#xff1a;黑客七个等级 黑客&#xff0c;对很多人来说充满诱惑力。很多人可以发现这门领域如同任何一门领域&#xff0c;越深入越敬畏&#xff0c;知识如海洋&#xff0c;黑客也存在一些等级&#xff0c;参考知道创宇 CEO ic&#xff08;世界顶级黑客团队 0x557 成员…

5、Task_stat() always report used == size他两总是相等

1、今天想查看一下任务的堆栈使用情况&#xff0c;按官方手册加入下面调试下面代码 Task_Stat statbuf; /* declear buffer */ Task_stat(Task_self(),&statbuf); /*call func to get status */ If(statbuf.used > (statbuf.stackSize * 9 / 10)) { System_printf(“…

Python——— 函数大全

&#xff08;一&#xff09;初识函数 函数是可重用的程序代码块。 函数的作用&#xff0c;不仅可以实现代码的复用&#xff0c;更能实现代码的一致性。一致性指的是&#xff0c;只要修改函数的 代码&#xff0c;则所有调用该函数的地方都能得到体现。 在编写函数时&#xff0…

LabVIEW开发空气动力学实验室的采集和控制系统

LabVIEW开发空气动力学实验室的采集和控制系统 在航空航天模拟设施中&#xff0c;通常的做法是准备一种针对当前正在进行的实验的数据采集和控制软件。该软件通常是根据当前要求编辑的更通用程序的修订版&#xff0c;或者可能是专门为该测试编写的自定义程序&#xff0c;具体取…

iview-admin前后台分离管理系统

加油&#xff0c;新时代打工人&#xff01; layui已淘汰&#xff0c;下面介绍vue管理后台系统&#xff0c;当然市场上不止下面一种框架。 layuimini后台管理系统的简单使用 iview-admin是iview生态圈的成员之一。是一套基于 Vue.js&#xff0c;搭配ivew UI(https://www.iviewu…