search
HomeBackend DevelopmentPython TutorialBasic learning of conditional judgment statements in Python

Basic learning of conditional judgment statements in Python

Apr 27, 2018 pm 03:25 PM
pythonjudgmentstatement

This article mainly introduces the basic learning tutorial of conditional judgment statements in Python. The article uses the Python2.x version, but the usage rules of the conditional statements have not changed in 3.x. Friends who need it can refer to it

The if statement is used to test a condition. If the condition is true, we run a block of statements (called if-block), otherwise we process another block of statements (called else-block). The else clause is optional.

Use if statement:

#!/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 &#39;No, it is a little higher than that&#39; # Another block
 # You can do whatever you want in a block ...
else:
 print &#39;No, it is a little lower than that&#39; 
 # you must have guess > number to reach here

print &#39;Done&#39;
# This last statement is always executed, after the if statement is executed

Output:

$ 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

In this program, we get the guessed number from the user, and then check whether the number is the one we have. We set the variable number to any integer we want, in this case 23. Then, we use the raw_input() function to get the number guessed by the user. Functions are just reused program segments.
We provide a string to the built-in raw_input function, which is printed on the screen and then waits for user input. Once we type something and press enter, the function returns the input. For the raw_input function, it is a string. We convert this string to an integer via int and store it in the variable guess. In fact, int is a class, but all you need to know about it is that it converts a string to an integer (assuming that the string contains a valid integer literal).

Next, we compare the user’s guess with the number we selected. If they are equal, we print a success message. Note that we use indentation levels to tell Python which block each statement belongs to. This is why indentation is so important in Python. I hope you stick to the "one tab per indentation level" rule. Is this true of you?

Note that the if statement contains a colon at the end - we tell Python that a block of statements follows.

We then check if the guess is smaller than our number, and if so, we tell the user that their guess is a bit too large. What we are using here is an elif clause, which actually combines two related if else-if else statements into one if-elif-else statement. This makes the program simpler and reduces the amount of indentation required.

Both elif and else clauses must have a colon at the end of the logical line, followed by a corresponding statement block (including correct indentation, of course).

You can also use another if statement within an if block, etc. - this is called a nested if statement.

Remember, the elif and else parts are optional. One of the simplest valid if statements is:

if True:
 print &#39;Yes, it is true&#39;

After Python has executed a complete if statement and its associated elif and else clauses, it Move to the next statement in the if statement block. In this example, this block of statements is the main block. The program execution starts from the main block and the next statement is the print 'Done' statement. After this, Python sees the end of the program and simply terminates.

Although this is a very simple program, I have pointed out many things you should pay attention to in this simple program. All of this is very straightforward (especially simple for those coming from a C/C background). They will catch your attention at first, but later they will feel familiar and "natural" to you.

Let’s look at another code example:

#! /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?"

Specially remind readers that we have already used the raw_input() function before. This is to obtain the user’s input in the interface. The input information is obtained through it, and the data obtained through it is string type data.

The above program is judged based on conditions and does different things under different conditions. What needs to be reminded is that in the condition: number == 10, for the convenience of reading, it is best to have a space between number and ==. Similarly, there is also a space after it. 10 here is of type int, and number is also of type int.

Save this program into a file with a .py extension, for example, save it as num.py, enter the directory where this file is stored, and run Python num.py, you can see the program execution results. Below are the results of my execution for reference.

$ Python num.py

请输入任意一个整数数字:

Copy code The code is as follows:

12

您输入的数字是:12
This number is more than 10.

$ Python num.py

请输入任意一个整数数字:


Copy code The code is as follows:

10

您输入的数字是:10
You are SMART.

$ Python num.py

请输入任意一个整数数字:

Copy code The code is as follows:

9

您输入的数字是:9
This number is less than 10.

I don’t know if you have noticed, above That piece of code starts with a line:

#! /usr/bin/env python

What does this mean?

这句话以 # 开头,表示本来不在程序中运行。这句话的用途是告诉机器寻找到该设备上的 Python 解释器,操作系统使用它找到的解释器来运行文件中的程序代码。有的程序里写的是 /usr/bin Python,表示 Python 解释器在 /usr/bin 里面。但是,如果写成 /usr/bin/env,则表示要通过系统搜索路径寻找 Python 解释器。不同系统,可能解释器的位置不同,所以这种方式能够让代码更将拥有可移植性。对了,以上是对 Unix 系列操作系统而言。对与 windows 系统,这句话就当不存在。

在“条件”中,就是上节提到的各种条件运算表达式,如果是 True,就执行该条件下的语句。

三元操作符
三元操作,是条件语句中比较简练的一种赋值方式,它的模样是这样的:

>>> name = "qiwsir" if "laoqi" else "github"
>>> name
&#39;qiwsir&#39;
>>> name = &#39;qiwsir&#39; if "" else "python"
>>> name
&#39;Python&#39;
>>> name = "qiwsir" if "github" else ""
>>> name
&#39;qiwsir&#39;

总结一下:A = Y if X else Z

什么意思,结合前面的例子,可以看出:

  • 如果 X 为真,那么就执行 A=Y

  • 如果 X 为假,就执行 A=Z

如此例

>>> x = 2
>>> y = 8
>>> a = "python" if x>y else "qiwsir"
>>> a
&#39;qiwsir&#39;
>>> b = "python" if x<y else "qiwsir"
>>> b
&#39;python&#39;

相关推荐:

python中的文件打开与关闭操作命令介绍

Python中的array数组模块相关使用

The above is the detailed content of Basic learning of conditional judgment statements in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

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.

Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?Apr 02, 2025 am 07:12 AM

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor