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

Basic learning of conditional judgment statements in Python

不言
Release: 2018-04-27 15:25:36
Original
1658 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template