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

文章目录

  • 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. ↩︎

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

运维开发面试题第一期

1.tail -f和tail -F的区别是什么? tail -f 根据文件描述符进行追踪&#xff0c;当文件改名或被删除&#xff0c;追踪停止。 tail -F 根据文件名进行追踪&#xff0c;并保持重试&#xff0c;即该文件被删除或改名后&#xff0c;如果再次创建相同的文件名&#xff0c;会继续…

Tomcat相关

1. 运行项目 将java项目打包为war或者war所对应的文件夹&#xff0c;放置于tomcat的webapps目录下。其实tomcat运行时会解压war到项目中并运行class文件&#xff0c;延伸开来&#xff0c;为啥不能用jar包&#xff0c;因为jar可能可以表示项目但也能表示依赖&#xff0c;tomcat…

国产4 通道模拟复合视频解码芯片MIPI CSI 接口,XS9922B

XS9922B 是一款 4 通道模拟复合视频解码芯片&#xff0c;支持 HDCCTV 高清协议和 CVBS 标 清协议&#xff0c;视频制式支持 720P/1080P 高清制式和 960H/D1 标清制式。芯片将接收到的高清 模拟复合视频信号经过模数转化&#xff0c;视频解码以及 2D 图像处理之后…

git在工作中如何搭建和运用(巨详细!!)

最近有点闲&#xff0c;出一版git在实际公司上的一些运用 1&#xff0c;下载git&#xff0c; 下载git就不多说了&#xff0c;官方上下载安装就好了。 2&#xff0c;初始化 下载安装完成后&#xff0c;找个项目的空文件夹进去&#xff0c;右键点击git bash here &#xff0c;…

Android 视频直播提拉流 嵌入式硬件 流媒体开发详细内容

1 Linux 系统编程网络编程基础 2 Linux 网络编程流媒体服务器&#xff0c;客户端开发实践 3 Android流媒体客户端 FFmpeg OpenGL ES 开发实践 4 Android H.264 AAC 封装mp4开发实战 5 流媒体开发实战之Rtmp推流 6 流媒体开发实战之RTSP推流 7 流媒体开发实战之UDP 8 P2P点对点项…

培训报名小程序报名列表页开发

目录 1 创建页面2 组件搭建3 设置URL参数4 设置筛选条件5 首页跳转6 最终的效果总结 这节我们来开发报名列表功能&#xff0c;先看原型 1 创建页面 功能要在页面上呈现&#xff0c;需要先创建页面。打开我们的培训报名小程序&#xff0c;在页面区&#xff0c;点击创建页面的…

多元回归预测 | Matlab主成分分析PCA降维,PLS偏小二乘回归预测。PCA-PLS回归预测模型

文章目录 效果一览文章概述部分源码参考资料效果一览 文章概述 多元回归预测 | Matlab主成分分析PCA降维,PLS偏小二乘回归预测。PCA-PLS回归预测模型 评价指标包括:MAE、RMSE和R2等,代码质量极高,方便学习和替换数据。要求2018版本及以上。 部分源码 %% 清空环境变量 warn…

CUDA+CUDNN+torch+torchvision安装

弄了好久&#xff0c;终于弄好了&#xff01;&#xff01;&#xff01; 原因&#xff1a;其实之前我是已经配置好pytorch的相关环境的了。但是这段时间&#xff0c;在跑GNN相关论文中的代码时&#xff0c;发现代码中的某个函数要求torch必须得是1.8 而我之前安装的是torch1.1…

《MySQL技术内幕》读书总结(一):MySQL体系结构和存储引擎

文章目录 前言&#xff1a;1、定义数据库和实例2、MySQL体系结构3、MySQL存储引擎InnoDBMyISAM 4、连接MySQL 前言&#xff1a; 该技术文章是我阅读《MySQL技术内幕 InnoDB存储引擎》第2版的总结梳理 我写这里文章的目的&#xff1a;书中的内容过于系统和繁琐&#xff0c;并不是…

C++学习 数组

目录 数组 一维数组 数组名 案例&#xff1a;冒泡排序 二维数组 数组名 数组 数组就是一个集合&#xff0c;里面存放了相同类型的数据元素。 下面的数字对应为数组的下标(索引)&#xff0c;可以看到索引范围为0~数组长度-1 特点&#xff1a; 数组中数据元素的数据类型相同。…

Unity3D 场景添加obj模型

有一个立方体的obj模型&#xff1b;将其拖到Assets文件夹节点上&#xff0c;在此节点放手&#xff0c;资源被加入项目&#xff1b; 在右侧显示出对象概览&#xff1b; 点击箭头&#xff0c;显示此模型下的子对象&#xff1b; 然后按住Assets面板中的cube1对象&#xff0c;拖动…

36.RocketMQ之Broker如何实现磁盘文件高性能读写

highlight: arduino-light Broker读写磁盘文件的核心技术:mmap Broker中大量的使用mmap技术去实现CommitLog这种大磁盘文件的高性能读写优化的。 通过之前的学习&#xff0c;我们知道了一点&#xff0c;就是Broker对磁盘文件的写入主要是借助直接写入os cache来实现性能优化的&…

【Java项目】Vue+ElementUI+Ceph实现多类型文件上传功能并实现文件预览功能

文章目录 效果演示前端后端Java 效果演示 先说一下我们的需求&#xff0c;我们的需求就是文件上传&#xff0c;之前的接口是只支持上传图片的&#xff0c;之后需求是需要支持上传pdf&#xff0c;所以我就得换接口&#xff0c;把原先图片上传的接口换为后端ceph&#xff0c;但是…

诚迈科技董事长、统信软件董事长王继平出席全球数字经济大会

7月5日&#xff0c;2023全球数字经济大会“数字未来新一代软件产业高质量发展论坛”在北京大兴隆重举行。论坛以“数字新高地&#xff0c;数创兴未来”为主题&#xff0c;共同探讨产业升级新路径&#xff0c;凝聚数字经济合作新共识&#xff0c;构建数字产业集聚发展新高地。诚…

基于Qt5 实现的简易慕课爬取程序

基于Qt5 实现的简易慕课爬取程序 一、项目概述二、源代码 一、项目概述 名称&#xff1a;MookScrapy 这个项目主要是使用了 Qt 里面的 QNetworkAccessManager 去下载慕课网站的数据 https://coding.imooc.com&#xff0c;也就是这个网站里面的卡片信息。然后做一定的分析和展示…

每次装完 homebrew,ohmyzsh 就会报错:Insecure completion-dependent directories detected:

参考:https://zhuanlan.zhihu.com/p/313037188 这是因为在big sur安装homebrew后&#xff0c;会在/usr/local/share/生成一个zsh文件夹&#xff0c;里面包含了 因此&#xff0c;zsh文件默认设置的权限是775&#xff0c;也就是group user有writer的权利&#xff0c;zsh认为这是…

centos下./configure报错:Permission denied

./configure 文章目录 ./configure报错解决方案使用chmod给./configure赋予x权限sftp给configure文件赋予x权限 ./configure报错 -bash: ./configure: Permission denied解决方案 使用chmod给./configure赋予x权限 sudo chmod x ./configuresftp给configure文件赋予x权限

webrtc源码阅读之h264 RTP打包

本文来分析webrtc打包h264 rtp包的代码&#xff0c;版本m98 一、RTP协议 1.1 RTP协议概述 实时传输协议&#xff08;RTP&#xff09;是一个网络协议&#xff0c;它允许在网络上进行实时的音频和视频数据传输。RTP协议主要用于解决多媒体数据的实时传输问题&#xff0c;特别是…

React + TypeScript 实践

主要内容包括准备知识、如何引入 React、函数式组件的声明方式、Hooks、useRef<T>、useEffect、useMemo<T> / useCallback<T>、自定义 Hooks、默认属性 defaultProps、Types or Interfaces、获取未导出的 Type、Props、常用 Props ts 类型、常用 React 属性类…

macbook安装chatglm2-6b

1、前言 chatglm安装环境还是比较简单的&#xff0c;比起Stable diffusion安装轻松不少。   安装分两部分&#xff0c;一是github的源码&#xff0c;二是Hugging Face上的模型代码&#xff1b;安装过程跟着官方的readme文档就能顺利安装。以下安装内容&#xff0c;绝大部分是…