Home Backend Development Python Tutorial Basic learning of conditional judgment statements in Python

Basic learning of conditional judgment statements in Python

Apr 27, 2018 pm 03:25 PM
python judgment statement

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
Copy after login

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
Copy after login

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;
Copy after login

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?"
Copy after login

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 after login
Copy after login
Copy after login

请输入任意一个整数数字:
Copy after login
Copy after login
Copy after login

Copy code The code is as follows:

12

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

$ Python num.py
Copy after login
Copy after login
Copy after login

请输入任意一个整数数字:
Copy after login
Copy after login
Copy after login


Copy code The code is as follows:

10

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

$ Python num.py
Copy after login
Copy after login
Copy after login

请输入任意一个整数数字:
Copy after login
Copy after login
Copy after login

Copy code The code is as follows:

9

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

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

#! /usr/bin/env python
Copy after login

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;
Copy after login

总结一下: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;
Copy after login

相关推荐:

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 of this Website
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

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 ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Do mysql need to pay Do mysql need to pay Apr 08, 2025 pm 05:36 PM

MySQL has a free community version and a paid enterprise version. The community version can be used and modified for free, but the support is limited and is suitable for applications with low stability requirements and strong technical capabilities. The Enterprise Edition provides comprehensive commercial support for applications that require a stable, reliable, high-performance database and willing to pay for support. Factors considered when choosing a version include application criticality, budgeting, and technical skills. There is no perfect option, only the most suitable option, and you need to choose carefully according to the specific situation.

HadiDB: A lightweight, horizontally scalable database in Python HadiDB: A lightweight, horizontally scalable database in Python Apr 08, 2025 pm 06:12 PM

HadiDB: A lightweight, high-level scalable Python database HadiDB (hadidb) is a lightweight database written in Python, with a high level of scalability. Install HadiDB using pip installation: pipinstallhadidb User Management Create user: createuser() method to create a new user. The authentication() method authenticates the user's identity. fromhadidb.operationimportuseruser_obj=user("admin","admin")user_obj.

Navicat's method to view MongoDB database password Navicat's method to view MongoDB database password Apr 08, 2025 pm 09:39 PM

It is impossible to view MongoDB password directly through Navicat because it is stored as hash values. How to retrieve lost passwords: 1. Reset passwords; 2. Check configuration files (may contain hash values); 3. Check codes (may hardcode passwords).

How to optimize MySQL performance for high-load applications? How to optimize MySQL performance for high-load applications? Apr 08, 2025 pm 06:03 PM

MySQL database performance optimization guide In resource-intensive applications, MySQL database plays a crucial role and is responsible for managing massive transactions. However, as the scale of application expands, database performance bottlenecks often become a constraint. This article will explore a series of effective MySQL performance optimization strategies to ensure that your application remains efficient and responsive under high loads. We will combine actual cases to explain in-depth key technologies such as indexing, query optimization, database design and caching. 1. Database architecture design and optimized database architecture is the cornerstone of MySQL performance optimization. Here are some core principles: Selecting the right data type and selecting the smallest data type that meets the needs can not only save storage space, but also improve data processing speed.

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 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 to use AWS Glue crawler with Amazon Athena How to use AWS Glue crawler with Amazon Athena Apr 09, 2025 pm 03:09 PM

As a data professional, you need to process large amounts of data from various sources. This can pose challenges to data management and analysis. Fortunately, two AWS services can help: AWS Glue and Amazon Athena.

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 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.

Can mysql connect to the sql server Can mysql connect to the sql server Apr 08, 2025 pm 05:54 PM

No, MySQL cannot connect directly to SQL Server. But you can use the following methods to implement data interaction: Use middleware: Export data from MySQL to intermediate format, and then import it to SQL Server through middleware. Using Database Linker: Business tools provide a more friendly interface and advanced features, essentially still implemented through middleware.

See all articles