if语句用来检验一个条件, 如果 条件为真,我们运行一块语句(称为 if-块 ), 否则 我们处理另外一块语句(称为 else-块 )。 else 从句是可选的。
使用if语句:
#!/usr/bin/python # Filename: if.py number = 23 guess = int(raw_input('Enter an integer : ')) if guess == number: print 'Congratulations, you guessed it.' # New block starts here print "(but you do not win any prizes!)" # New block ends here elif guess < number: print 'No, it is a little higher than that' # Another block # You can do whatever you want in a block ... else: print 'No, it is a little lower than that' # you must have guess > number to reach here print 'Done' # This last statement is always executed, after the if statement is executed
输出:
$ python if.py Enter an integer : 50 No, it is a little lower than that Done $ python if.py Enter an integer : 22 No, it is a little higher than that Done $ python if.py Enter an integer : 23 Congratulations, you guessed it. (but you do not win any prizes!) Done
在这个程序中,我们从用户处得到猜测的数,然后检验这个数是否是我们手中的那个。我们把变量number设置为我们想要的任何整数,在这个例子中是23。然后,我们使用raw_input()函数取得用户猜测的数字。函数只是重用的程序段。
我们为内建的raw_input函数提供一个字符串,这个字符串被打印在屏幕上,然后等待用户的输入。一旦我们输入一些东西,然后按回车键之后,函数返回输入。对于raw_input函数来说是一个字符串。我们通过int把这个字符串转换为整数,并把它存储在变量guess中。事实上,int是一个类,不过你想在对它所需了解的只是它把一个字符串转换为一个整数(假设这个字符串含有一个有效的整数文本信息)。
接下来,我们将用户的猜测与我们选择的数做比较。如果他们相等,我们打印一个成功的消息。注意我们使用了缩进层次来告诉Python每个语句分别属于哪一个块。这就是为什么缩进在Python如此重要的原因。我希望你能够坚持“每个缩进层一个制表符”的规则。你是这样的吗?
注意if语句在结尾处包含一个冒号——我们通过它告诉Python下面跟着一个语句块。
然后,我们检验猜测是否小于我们的数,如果是这样的,我们告诉用户它的猜测大了一点。我们在这里使用的是elif从句,它事实上把两个相关联的if else-if else语句合并为一个if-elif-else语句。这使得程序更加简单,并且减少了所需的缩进数量。
elif和else从句都必须在逻辑行结尾处有一个冒号,下面跟着一个相应的语句块(当然还包括正确的缩进)。
你也可以在一个if块中使用另外一个if语句,等等——这被称为嵌套的if语句。
记住,elif和else部分是可选的。一个最简单的有效if语句是:
if True: print 'Yes, it is true'
在Python执行完一个完整的if语句以及与它相关联的elif和else从句之后,它移向if语句块的下一个语句。在这个例子中,这个语句块是主块。程序从主块开始执行,而下一个语句是print 'Done'语句。在这之后,Python看到程序的结尾,简单的结束运行。
尽管这是一个非常简单的程序,但是我已经在这个简单的程序中指出了许多你应该注意的地方。所有这些都是十分直接了当的(对于那些拥有C/C++背景的用户来说是尤为简单的)。它们在开始时会引起你的注意,但是以后你会对它们感到熟悉、“自然”。
下面我们再来看一个代码实例:
#! /usr/bin/env python #coding:utf-8 print "请输入任意一个整数数字:" number = int(raw_input()) #通过 raw_input()输入的数字是字符串 #用 int()将该字符串转化为整数 if number == 10: print "您输入的数字是:%d"%number print "You are SMART." elif number > 10: print "您输入的数字是:%d"%number print "This number is more than 10." elif number < 10: print "您输入的数字是:%d"%number print "This number is less than 10." else: print "Are you a human?"
特别提醒看官注意,前面我们已经用过 raw_input() 函数了,这个是获得用户在界面上输入的信息,而通过它得到的是字符串类型的数据。
上述程序,依据条件进行判断,不同条件下做不同的事情了。需要提醒的是在条件中:number == 10,为了阅读方便,在 number 和 == 之间有一个空格最好了,同理,后面也有一个。这里的 10,是 int 类型,number 也是 int 类型.
把这段程序保存成一个扩展名是.py 的文件,比如保存为 num.py,进入到存储这个文件的目录,运行 Python num.py,就能看到程序执行结果了。下面是我执行的结果,供参考。
$ Python num.py
请输入任意一个整数数字:
12
您输入的数字是:12 This number is more than 10.
$ Python num.py
请输入任意一个整数数字:
10
您输入的数字是:10 You are SMART.
$ Python num.py
请输入任意一个整数数字:
9
您输入的数字是:9 This number is less than 10.
不知道各位是否注意到,上面的那段代码,开始有一行:
#! /usr/bin/env python
这是什么意思呢?
这句话以 # 开头,表示本来不在程序中运行。这句话的用途是告诉机器寻找到该设备上的 Python 解释器,操作系统使用它找到的解释器来运行文件中的程序代码。有的程序里写的是 /usr/bin Python,表示 Python 解释器在 /usr/bin 里面。但是,如果写成 /usr/bin/env,则表示要通过系统搜索路径寻找 Python 解释器。不同系统,可能解释器的位置不同,所以这种方式能够让代码更将拥有可移植性。对了,以上是对 Unix 系列操作系统而言。对与 windows 系统,这句话就当不存在。
在“条件”中,就是上节提到的各种条件运算表达式,如果是 True,就执行该条件下的语句。
三元操作符
三元操作,是条件语句中比较简练的一种赋值方式,它的模样是这样的:
>>> 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
如此例
>>> x = 2 >>> y = 8 >>> a = "python" if x>y else "qiwsir" >>> a 'qiwsir' >>> b = "python" if x<y else "qiwsir" >>> b 'python'

Python's flexibility is reflected in multi-paradigm support and dynamic type systems, while ease of use comes from a simple syntax and rich standard library. 1. Flexibility: Supports object-oriented, functional and procedural programming, and dynamic type systems improve development efficiency. 2. Ease of use: The grammar is close to natural language, the standard library covers a wide range of functions, and simplifies the development process.

Python is highly favored for its simplicity and power, suitable for all needs from beginners to advanced developers. Its versatility is reflected in: 1) Easy to learn and use, simple syntax; 2) Rich libraries and frameworks, such as NumPy, Pandas, etc.; 3) Cross-platform support, which can be run on a variety of operating systems; 4) Suitable for scripting and automation tasks to improve work efficiency.

Yes, learn Python in two hours a day. 1. Develop a reasonable study plan, 2. Select the right learning resources, 3. Consolidate the knowledge learned through practice. These steps can help you master Python in a short time.

Python is suitable for rapid development and data processing, while C is suitable for high performance and underlying control. 1) Python is easy to use, with concise syntax, and is suitable for data science and web development. 2) C has high performance and accurate control, and is often used in gaming and system programming.

The time required to learn Python varies from person to person, mainly influenced by previous programming experience, learning motivation, learning resources and methods, and learning rhythm. Set realistic learning goals and learn best through practical projects.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft