Basic Learning tutorial on condition judgment statements in Python, python statements

Source: Internet
Author: User

Basic Learning tutorial on condition judgment statements in Python, python statements

The if statement is used to test a condition. if the condition is true, we run a statement (called the if-block). Otherwise, we will process another statement (called the else-block ). Else clauses are optional.

Use the if statement:

#!/usr/bin/python# Filename: if.py number = 23guess = 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 hereelif 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 hereprint 'Done'# This last statement is always executed, after the if statement is executed

Output:

$ python if.pyEnter an integer : 50No, it is a little lower than thatDone$ python if.pyEnter an integer : 22No, it is a little higher than thatDone$ python if.pyEnter an integer : 23Congratulations, you guessed it.(but you do not win any prizes!)Done

In this program, we get the number of guesses from the user, and then check whether the number is the one in our hands. We set the variable number to any integer we want. In this example, It is 23. Then, we use the raw_input () function to obtain the number that the user guessed. A function is only a reusable program segment.
We provide a string for the built-in raw_input function, which is printed on the screen and waiting for user input. Once we enter something and press the Enter key, the function returns the input. The raw_input function is a string. We use int to convert the string to an integer 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 into an integer (assuming this string contains a valid integer text ).

Next, we will compare the user's guess with the number we selected. If they are the same, we can print a successful message. Note that we use an indent level to tell which block each statement belongs to in Python. This is why indentation is so important in Python. I hope you can stick to the "One tab per indentation layer" rule. Are you like this?

Note that the if statement contains a colon at the end, which is used to tell Python to follow a statement block.

Then, we will test whether the guess is smaller than our number. If so, we will tell the user that the guess is a little larger. Here we use the elif clause, which combines two associated if else-if else statements into an if-elif-else statement. This makes the program simpler and reduces the number of indentation required.

Both the 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 in an if block, and so on -- this is called a nested if statement.

Remember, the elif and else sections are optional. The simplest and most effective if statement 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, the Statement block is the main block. The program runs 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 running.

Although this is a very simple program, I have pointed out a lot of things you should pay attention to in this simple program. All of these are very straightforward (especially for users with C/C ++ backgrounds ). They will attract your attention at the beginning, but you will be familiar with them and "natural" in the future ".

Next let's look at a code example:

#! /Usr/bin/env python # coding: utf-8print "Please enter any integer number:" number = int (raw_input () # Through raw_input () the number entered is a string # Use int () to convert the string to an integer if number = 10: print "the number you entered is: % d "% number print" You are SMART. "elif number> 10: print" the number you entered is: % d "% number print" This number is more than 10. "elif number <10: print" the number you entered is: % d "% number print" This number is less than 10. "else: print" Are you a human? "

 
Note: We have already used the raw_input () function to obtain user input information on the interface and obtain string-type data.

The above procedures are judged based on the conditions, and different things are done under different conditions. Note that in the condition: number = 10. For ease of reading, it is best to have a space between number and =. Similarly, there is a space later. Here 10 is the int type, and number is also the int type.

Save this program as an extension. for example, save as num. py to the directory where the file is stored and run Python num. py to view the program execution result. The following is my execution result for your reference.

$ Python num.py
Enter any integer:

Copy codeThe Code is as follows:

12


The number you entered is 12 This number is more than 10.
$ Python num.py
Enter any integer:

Copy codeThe Code is as follows:

10


The number you entered is 10You are SMART.
$ Python num.py
Enter any integer:

Copy codeThe Code is as follows:

9


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

I wonder if you have noticed that the code above starts with a line:

#! /usr/bin/env python

What does this mean?

This statement starts with #, 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 write/usr/bin Python, indicating that the Python interpreter is in/usr/bin. However, if it is written as/usr/bin/env, it indicates that the Python interpreter needs to be searched through the system search path. Different systems may have different interpreter locations, so this method makes the code more portable. By the way, the above is for Unix operating systems. For windows systems, this statement does not exist.

In "condition", it is the expressions of various conditional operations mentioned in the previous section. If it is True, the statements under this condition are executed.

Ternary Operators
A Ternary operation is a concise Assignment Method in conditional statements. It 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 sum up, A = Y if X else Z

What does it mean? combined with the previous example, we can see that:

  • If X is true, execute A = Y
  • If X is false, run A = Z.

Example

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

Articles you may be interested in:
  • Simple usage of condition judgment statements in Python
  • Explain the condition judgment statements in Python
  • Example of how to sort tuples and lists by conditions in Python
  • Detailed explanation of condition statements and operator priority in Python
  • How to test the competition conditions for accessing the same data in Python
  • True and False conditions in Python determine instance analysis
  • Conditions and loops for getting started with Python
  • Analysis of conditions and cyclic control instances of Python3
  • Python array filter function example
  • Python dictionary multi-condition sorting method example
  • How to Use python conditions and loops
  • Introduction to Condition Selection and circular statement usage in Python
  • Abbreviation of condition judgment in 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.