SoFunction
Updated on 2024-11-17

Learning the Basics of Conditional Judgment Statements in Python Tutorial

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

Use if statements:

#!/usr/bin/python
# Filename:  

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

Output:

$ python 
Enter an integer : 50
No, it is a little lower than that
Done
$ python 
Enter an integer : 22
No, it is a little higher than that
Done
$ python 
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 to see if that number is the one we have in hand. We set the variable number to whatever integer we want, in this case 23. We then use the raw_input() function to get the user's guessed number. The function is just a reused program segment.
We provide the built-in raw_input function with a string that is printed on the screen and then waits for user input. Once we type something and then after pressing 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. Actually, int is a class, but all you want to know about it is that it converts a string to an integer (assuming the string contains a valid integer text message).

Next, we compare the user's guess with the number we chose. If they are equal, we print a success message. Notice that we used the indentation hierarchy to tell Python which block each statement belongs to, respectively. This is why indentation is so important in Python. I hope you're sticking to the "one tab per indentation level" rule. Do you?

Notice that the if statement contains a colon at the end - we use it to tell Python that a block of statements follows below.

We then test to see if the guess is smaller than our number, and if it is, we tell the user that it's a little bigger. We're using an elif clause here, which in effect combines two related if else-if else statements into a single if-elif-else statement. This makes the program simpler and reduces the number of indentations required.

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

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

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

if True:
 print 'Yes, it is true'

After Python executes a complete if statement and the elif and else clauses associated with it, it moves to the next statement in the if statement block. In this example, this statement block is the main block. The program starts execution from the main block, and the next statement is the print 'Done' statement. After this, Python sees the end of the program and simply ends the run.

Although this is a very simple program, I've pointed out a number of things you should be aware of in this simple program. All of them are very straightforward (especially easy for those with a C/C++ background). They will catch your attention at first, but later you will feel familiar and "natural" with them.

Let's look at another code example below:

#! /usr/bin/env python
#coding:utf-8

print "Please enter any integer number:"

number = int(raw_input()) # The number entered via raw_input() is a string
    # Convert the string to an integer with int()

if number == 10:
 print "The number you have entered is: %d"%number
 print "You are SMART."
elif number > 10:
 print "The number you have entered is: %d"%number
 print "This number is more than 10."
elif number < 10:
 print "The number you have entered is: %d"%number
 print "This number is less than 10."
else:
 print "Are you a human?" 

 
In particular, we have already used the raw_input() function, which gets the information entered by the user in the interface, and the data obtained through it is of string type.

The above program, based on the conditions for judgment, different conditions to do different things. Need to remind is in the conditions: number == 10, in order to read easily, in the number and == between a space is the best, similarly, there is also a back. Here 10, is an int type, number is also an int type.

Save this program as a file with a .py extension, e.g. , go to the directory where the file is stored, run Python, and you'll see the results of the program execution. For reference, here's what I did.

$ Python 
Please enter any integer number:

Copy Code The code is as follows.

12


The number you have entered is:12
This number is more than 10.
$ Python 
Please enter any integer number:

Copy Code The code is as follows.

10


The number you have entered is:10
You are SMART.
$ Python 
Please enter any integer number:

Copy Code The code is as follows.

9


The number you have entered is:9
This number is less than 10.

I don't know if you noticed, but that code above, there is a line at the beginning:

#! /usr/bin/env python

What does that mean?

This sentence begins with #, indicating that it was not originally run in the program. The purpose of this sentence is to tell the machine to find the Python interpreter on the device, and the operating system uses the interpreter it finds to run the program code in the file. Some programs write /usr/bin Python to indicate that the Python interpreter is inside /usr/bin. However, if you write /usr/bin/env, you are looking for the Python interpreter through the system search path. The location of the interpreter may vary from system to system, so this approach makes the code more portable. By the way, this is for the Unix family of operating systems. For windows systems, this statement does not exist.

In "Condition", it is the various conditional expressions mentioned in the previous section, if it is True, then the statement under the condition will be executed.

ternary operator (computing)
The ternary operation, a more concise form of assignment in conditional statements, looks like this:

>>> name = "qiwsir" if "laoqi" else "github"
>>> name
'qiwsir'
>>> name = 'qiwsir' if "" else "python"
>>> name
'Python'
>>> name = "qiwsir" if "github" else ""
>>> name
'qiwsir'

To summarize: A = Y if X else Z

What it means can be seen in the context of the previous example:

  • If X is true, then execute A=Y
  • If X is false, perform A=Z

e.g.

>>> x = 2
>>> y = 8
>>> a = "python" if x>y else "qiwsir"
>>> a
'qiwsir'
>>> b = "python" if x<y else "qiwsir"
>>> b
'python'