How to use judgment statements and loops in Python

Source: Internet
Author: User
This article mainly introduces how to use judgment statements and loops in Python. it is the basic knowledge of Python learning. the code is based on Python2.x. For more information, see Condition judgment

A computer can perform a lot of automated tasks because it can perform conditional judgment on its own.

For example, input the user's age and print different content according to The Age. in the Python program, use the if statement:

age = 20if age >= 18:  print 'your age is', age  print 'adult'

According to the indentation rule of Python, if the if statement is True, the two print statements of indentation are executed. Otherwise, nothing is done.

You can also add an else statement to the if statement, which means that if the if statement is False, do not execute the content of the if statement to execute the else statement:

age = 3if age >= 18:  print 'your age is', age  print 'adult'else:  print 'your age is', age  print 'teenager'

Do not write less colons :.

Of course, the above judgment is very rough. elif can be used for more detailed judgment:

age = 3if age >= 18:  print 'adult'elif age >= 6:  print 'teenager'else:  print 'kid'

Elif is short for else if and can have multiple elif statements. Therefore, the complete form of the if statement is:

If
 <条件判断1>
  
:
  <执行1>
   
Elif
   <条件判断2>
    
:
    <执行2>
     
Elif
     <条件判断3>
      
:
      <执行3>
        Else:
       <执行4>
      
     
    
   
  
 

If statement execution has a feature, it is judged from the top down. if it is True in a certain judgment, after executing the statement corresponding to the judgment, the remaining elif and else are ignored, therefore, test and explain why the following program prints teenager:

age = 20if age >= 6:  print 'teenager'elif age >= 18:  print 'adult'else:  print 'kid'

If judgment conditions can also be abbreviated, such as writing:

if x:  print 'True'

If x is a non-zero value, a non-empty string, or a non-empty list, True is returned. otherwise, False is returned.
Loop

Python has two types of loops. one is for... in loop, which iterates each element in list or tuple in sequence. for example:

names = ['Michael', 'Bob', 'Tracy']for name in names:  print name

Execute this code to print each element of names in sequence:

MichaelBobTracy

Therefore, the for x in... loop is to substitute each element into the variable x and then execute the indent block statement.

For example, if we want to calculate the sum of integers 1-10, we can use a sum variable to accumulate:

sum = 0for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:  sum = sum + xprint sum

If you want to calculate the sum of integers from 1 to 100, it is a little difficult to write from 1 to. Fortunately, Python provides a range () function to generate an integer sequence, such as range (5) the generated sequence is an integer less than 5 starting from 0:

>>> range(5)[0, 1, 2, 3, 4]

Range (101) is used to generate an integer sequence between 0 and. the calculation is as follows:

sum = 0for x in range(101):  sum = sum + xprint sum

Run the above code to see if the result is 5050 calculated by Gauss.

The second type of loop is the while loop. as long as the condition is met, the loop continues. if the condition is not met, the loop exits. For example, if we want to calculate the sum of all odd numbers within 100, we can use the while loop:

sum = 0n = 99while n > 0:  sum = sum + n  n = n - 2print sum

The variable n in the loop is continuously reduced until it is changed to-1. the while condition is no longer met and the loop exits.
Further discuss raw_input

Finally, let's look at a problematic condition judgment. Many students use raw_input () to read users' input. in this way, they can input their own input, making the program more interesting:

Birth = raw_input ('Birth: ') if birth <2000: print '00 before 'else: print '00 after'

Enter 1982, but the result shows that after 00, can Python be wrong in such a simple judgment?

Of course it is not a Python issue. print birth under the Python interactive command line to see:

>>> birth'1982'>>> '1982' < 2000False>>> 1982 < 2000True

The reason is found! The original content read from raw_input () is always returned in the form of a string. if you compare the string with an integer, you will not get the expected result. you must first use int () convert the string to the integer we want:

birth = int(raw_input('birth: '))

Run the command again to get the correct result. But what if you enter abc? An error message is displayed:

Traceback (most recent call last): ...ValueError: invalid literal for int() with base 10: 'abc'

When int () finds that a string is not a valid number, an error is reported and the program exits.

How can I check and capture errors during the running period? Subsequent errors and debugging will be discussed.
Summary

Conditional judgment allows computers to make their own choices. Python's if... elif... else is flexible.

Loop is an effective way for computers to repeat tasks. sometimes, if code is written incorrectly, the program will be stuck in an "endless loop", that is, it will always go through the loop. In this case, you can use Ctrl + C to exit the program or force the Python process to end.

Try to write an endless loop program.

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.