Basic Learning Tutorial for conditional judgment statements in Python

Source: Internet
Author: User
The IF statement is used to test a condition, and if the condition is true, we run a block of statements (called if-blocks), otherwise we process another piece of statement (called else-block). The ELSE clause is optional.

Use the IF statement:

#!/usr/bin/python# Filename:if.py number = 23guess = Int (raw_input (' Enter an Integer: ')) if guess = = Number:print ' Cong Ratulations, you guessed the it. ' # new block starts here print ' (but don't win any prizes!) "# New block ends Hereelif G Uess < Number:print ' No, it's a little higher than that ' # another block # can do whatever you want in a block. . Else:print ' No, it's a little lower than that's  # you must has guess > number to reach Hereprint ' done ' # this LA St statement is always executed, after the IF statement is executed

Output:

$ python if.pyenter an integer:50no, it's a little lower than thatdone$ python if.pyenter an integer:22no, it's a Li Ttle higher than thatdone$ python if.pyenter an integer:23congratulations, you guessed it. (But don't win any prizes!) Done

In this program, we get the number of guesses from the user and then test whether the number is the one in our hands. We set the variable number to any integer we want, which in this case is 23. Then we use the Raw_input () function to get the number that the user guesses. Functions are simply reusable segments of the program.
We provide a string for the built-in raw_input function, which is printed on the screen and then waits for the user's input. Once we enter something, and then press ENTER, the function returns the input. is a string for the Raw_input function. We convert the string to an integer by int and store it in the variable guess. In fact, int is a class, but what you want to know about it is that it converts a string into an integer (assuming that the string contains a valid integer literal information).

Next, we compare the user's guess to the number we choose. If they are equal, we print a successful message. Note that we use the indentation level to tell Python which block each statement belongs to. That's why indenting is so important in python. I want you to stick to the "one tab per indent" rule. Is that what you do?

Note that the IF statement contains a colon at the end--we tell Python to follow a block of statements below it.

Then, we test whether the guess is less than our number, and if so, we tell the user that it's a bit bigger to guess. We are using the ELIF clause here, which in fact merges two associated if else-if else statements into a single if-elif-else statement. This makes the program simpler and reduces the amount of indentation required.

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

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

Remember that the elif and else sections 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 its associated elif and else clauses, it moves to the next statement in the IF statement block. In this example, the block of statements is the main block. The program executes from the main block, and the next statement is the print ' done ' statement. After that, Python sees the end of the program and simply ends the run.

Although this is a very simple program, I have already pointed out in this simple program a lot of places you should be aware of. All of this is very straightforward (especially simple for users who have a C + + background). They will get your attention at the beginning, but you will be familiar with them and "natural" in the future.

Let's look at a code example:

#! /usr/bin/env Python#coding:utf-8print "Please enter any number of integers:" number = Int (raw_input ()) #通过 raw_input () The numbers entered are strings    


In particular, crossing note that we have used the Raw_input () function earlier, which is to get the information that the user has entered on the interface, and it gets the string type of data.

The above procedure, according to the conditions of judgment, under different conditions to do different things. Need to remind is in the condition: number = = 10, in order to read convenience, between number and = = There is a space between the best, the same, there is a later. Here, 10, is the int type, and number is the int type.

Save this program as a file with a. py extension, such as Save as num.py, go to the directory where the file is stored, run Python num.py, and you can see the results of the program execution. Here is the result of my execution, for reference.

$ Python num.py

Please enter any number of integers:

Copy the Code code as follows:

12


The number you entered is: 12This numbers is more than 10.

$ Python num.py

Please enter any number of integers:

Copy the Code code as follows:

10


The number you entered is: 10You is SMART.

$ Python num.py

Please enter any number of integers:

Copy the Code code as follows:

9


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

I do not know if you notice that the above code, the beginning of a line:

#! /usr/bin/env python

What does that mean?

This phrase begins with a #, indicating that it is not running 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 are written in/usr/bin python, which indicates that the Python interpreter is inside the/usr/bin. However, if written as/usr/bin/env, it means looking for the Python interpreter through the system search path. Different systems may have different locations for the interpreter, so this approach allows the code to be more portable. Yes, the above is for Unix series operating systems. On the system with Windows, this phrase is not present.

In conditions, the various conditional operation expressions mentioned in the previous section, if True, execute the statement under that condition.

Ternary operator
Ternary operation, is a relatively concise method of assignment in conditional statements, it looks like this:

>>> name = "Qiwsir" if "Laoqi" Else "GitHub" >>> name ' qiwsir ' >>> name = ' Qiwsir ' If "" Else "PYT Hon ">>> name ' Python ' >>> name =" Qiwsir "if" GitHub "Else" >>> name ' Qiwsir '

Sum up: A = Y if X else Z

What do you mean, combined with the previous example, you can see:

    • If X is true, then execute a=y
    • If X is False, execute a=z

Such an example

>>> x = 2>>> y = 8>>> a = "python" If x>y Else "Qiwsir" >>> a ' qiwsir ' >>> b = "Python" if x
 
  
   
  >> b ' python '
 
  
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.