跟老齐学Python之复习if语句
基本语句结构
代码如下:
if 判断条件1:
执行语句1……
elif 判断条件2:
执行语句2……
elif 判断条件3:
执行语句3……
else:
执行语句4……
只有当“判断条件”的值是True的时候,才执行下面的执行语句。
那么,在python中,怎么知道一个判断条件是不是真呢?这个问题我们在眼花缭乱的运算符中已经讲解了一种数据类型:布尔类型。可以通过一个内置函数bool()来判断一个条件的结果True还是False。看看下面的例子,是不是能够理解bool()的判断规则?
代码如下:
>>> bool("")
False
>>> bool(0)
False
>>> bool('none')
True
>>> bool(False)
False
>>> bool("False")
True
>>> bool(True)
True
>>> bool("True")
True
>>> bool(3>4)
False
>>> bool("b">"a")
True
>>> bool(not "")
True
>>> bool(not True)
False
忘记了怎么办?看下面的语句:
if 忘记:
复习-->眼花缭乱的运算符一讲
在执行语句中,其实不一定非要把bool()写上的。如同这样:
代码如下:
>>> x = 9
>>> if bool(x>7): #条件为True则执行下面的
... print "%d more than 7"%x
... else:
... print "%d not more than 7"%x
...
9 more than 7
>>> if x>7:
... print "%d more than 7"%x
... else:
... print "%d not more than 7"%x
...
9 more than 7
以上两个写法是等效的,但是,在实际的编程中,我们不用if bool(x>7)的格式,而是使用if x>7的样式,还要特别提醒,如果写成if (x>7),用一个括号把条件表达式括起来,是不是可以呢?可以,但也不是python提倡的。
代码如下:
>>> if (x>7): #不提倡这么写,这不是python风格
... print "%d more than 7"%x
...
9 more than 7
拉出来溜溜
平时总有人在不服气的时候说“是骡子是马,拉出来溜溜”,赵本山有一句名言“走两步”。其本质都是说“光说不练是假把式”。今天收到一个朋友的邮件,也询问,在学习python的时候,记不住python的内容。其实不用记,我在前面的课程中已经反复讲过了。但是,在应用中,会越来越熟练。
下面就做一个练习,要求是:
接收任何字符和数字的输入
判断输入的内容,如果不是整数是字符,就告诉给用户;如果是小数,也告诉用户
如果输入的是整数,判断这个整数是奇数还是偶数,并且告诉给用户
在这个练习中,显然要对输入的内容进行判断,以下几点需要看官注意:
通过raw_input()得到的输入内容,都是str类型
要判断一个字符串是否是由纯粹数字组成,可以使用str.isdigit()(建议看官查看该内置函数官方文档)
下面的代码是一个参考:
代码如下:
#! /usr/bin/env python
#coding:utf-8
print "请输入字符串,然后按下回车键:"
user_input = raw_input()
result = user_input.isdigit()
if not result:
print "您输入的不完全是数字"
elif int(user_input)%2==0:
print "您输入的是一个偶数"
elif int(user_input)%2!=0:
print "您输入的是一个奇数"
else:
print "您没有输入什么呢吧"
特别提醒列为,这个代码不是非常完善的,还有能够修改的地方,看官能否完善之?
再来一个如何?
已知一个由整数构成的list,从中跳出奇数和偶数,并且各放在一个list中。
请看官在看下面的参考代码之前,自己写一写。
代码如下:
#!/usr/bin/env python
#coding:utf-8
import random
numbers = [random.randint(1,100) for i in range(20)] #以list解析的方式得到随机的list
odd = []
even = []
for x in numbers:
if x%2==0:
even.append(x)
else:
odd.append(x)
print numbers
print "odd:",odd
print "even:",even
用这个例子演示一下if在list解析中的应用。看能不能继续改进一些呢?
可以将循环的那部分用下面的list解析代替
代码如下:
#!/usr/bin/env python
#coding:utf-8
import random
numbers = [random.randint(1,100) for i in range(20)] #以list解析的方式得到随机的list
odd = [x for x in numbers if x%2!=0]
even = [x for x in numbers if x%2==0]
print numbers
print "odd:",odd
print "even:",even
一个有趣的赋值
对赋值,看官应该比较熟悉了吧,如果要复习,请看《[赋值,简单也不简单]》(./127.md)以及《[正规地说一句]》(./201.md)的相关内容。
这里说的有趣赋值是什么样子的呢?请看:
代码如下:
>>> name = "qiwsir" if "laoqi" else "github"
>>> name
'qiwsir'
>>> name = 'qiwsir' if "" else "python"
>>> name
'python'
>>> name = "qiwsir" if "github" else ""
>>> name
'qiwsir'
总结一下:A = Y if X else Z
什么意思,结合前面的例子,可以看出:
如果X为真,那么就执行A=Y
如果X为假,就执行A=Z
再看看上面的例子,是不是这样执行呢?
if语句似乎简单,但是在编程时间中常用到。勤加练习吧。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











A common if statement in computer programming is a conditional judgment statement. The if statement is a selective branch structure. It selects the execution path based on clear conditions, rather than strictly following the order. In actual programming, the appropriate branch statement must be selected according to the program flow. It changes the execution according to the result of the condition. program; the simple syntax of the if statement is "if (conditional expression) {//code to be executed;}".

Conditional control structure in PHP In PHP programming, conditional control structure is a very important syntax, which allows the program to execute different code blocks based on different conditions. By using conditional control structures, we can implement the branching logic of the program and determine the execution path of the program based on the result of the condition. This article will introduce the commonly used conditional control structures in PHP, including if statements, else statements, elseif statements and switch statements, and give specific code examples. The if statement is the most basic conditional control in PHP

Python is a very powerful and popular programming language that is widely used in fields such as data analysis, machine learning, and web development. However, when writing Python code, we will inevitably encounter repeated if statements, which may lead to problems such as inefficient code and complicated maintenance. Therefore, this article will introduce some methods and techniques to solve repeated if statement errors in Python code. Simplify if statements using Boolean operators In many cases, repeated logic in an if statement can be simplified into Boolean operations. example

Detailed explanation of Python flow control statements: if, else, elif, while, for In programming, flow control statements are essential. They are used to determine the execution flow of the program based on conditions. Python provides several commonly used flow control statements, including if, else, elif, while and for. This article explains these statements in detail and provides specific code examples. if statement The if statement is used to determine whether a certain condition is true. If the condition is true, execute the if code block.

Master the advanced skills of if statements in Go language and optimize code quality: use if-else chains to check multiple conditions and execute the corresponding code block according to each condition. Compares values using relational expressions and returns a Boolean value. Control code flow by combining Boolean values with the help of logical operators. Use switch statements to execute different blocks of code based on variable values.

Common mistakes when using if statements include incorrect use of comparison operators, omitting braces, using multiple conditions, and using elseif as the default case. To avoid these errors, use == for comparisons, always use braces, use separate if statements or Boolean operators to check multiple conditions, and always use else as the default case.

Control flow statement: if and switch statement In programming, control flow statement is a key concept, which is used to control the way and order of program execution. Control flow statements can change the execution order of the program based on conditions, allowing the program to perform different operations according to specific situations. Among them, if statement and switch statement are one of the most commonly used control flow statements. if statement The if statement is used in a program to determine whether to execute some code based on a condition. The syntax is as follows: if(condition){/

Exam strategy: How to prepare for the Go language exam efficiently, you need specific code examples. As a strongly typed and highly concurrency programming language, the Go language is increasingly favored by programmers. For those who want to improve their skills and pass relevant certification exams, preparing for the Go language exam is an important task. In this article, we will share some efficient strategies for preparing for the Go language exam, and provide some specific code examples to help readers better understand and master the relevant knowledge of the Go language. 1. Deeply understand the basic knowledge of Go language
