Tutorials for using judgment statements and loops in Python

Source: Internet
Author: User
Conditional Judgment

Computers can do a lot of automated tasks, because it can make their own conditions to judge.

For example, enter the age of the user, print different content according to age, in a Python program, with an IF statement:

Age = 20if Age >=:  print ' Your-age ', age  print ' adult '

According to Python's indentation rules, if the IF statement evaluates to True, the indented two lines of the print statement are executed, otherwise, nothing is done.

You can also add an else statement to if, meaning that if the If judgment is false, do not execute the IF content, go to the Else execution:

Age = 3if Age >=:  print ' Your-age ', age  print ' adult ' else:  print ' Your-age ', age  print ' Teenag Er

Be careful not to write a colon less:.

Of course, the above judgment is very sketchy, can be used elif to do more detailed judgment:

Age = 3if Age >=:  print ' adult ' elif age >= 6:  print ' teenager ' else:  print ' Kid '

Elif is an abbreviation for else if, there can be more than one elif, so the complete form of the IF statement is:

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

If statement execution has a characteristic, it is to judge from the top, if in a certain judgment is true, the judgment corresponding statement execution, ignore the remaining elif and else, so, please test and explain why the following program printed teenager:

Age = 20if Age >= 6:  print ' teenager ' elif age >=:  print ' adult ' else:  print ' Kid '

If the condition can also be abbreviated, such as writing:

If x:  print ' True '

As long as X is a non-0 value, a nonempty string, a non-empty list, and so on, it evaluates to true, otherwise false.
Cycle

There are two types of Python loops, one is the for...in loop, and each of the elements in the list or tuple is iterated in turn to see an example:

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

Executing this code, each element of the names is printed sequentially:

Michaelbobtracy

So for the X in ... A loop is a statement that puts each element into the variable x and then executes the indented block.

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

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

If you want to calculate the sum of 1-100 integers, writing from 1 to 100 is a bit difficult, but fortunately Python provides a range () function that generates a sequence of integers, such as range (5), which generates a sequence that is less than 0, starting from 5:

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

Range (101) can generate a sequence of 0-100 integers, calculated as follows:

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

Please run the above code on your own, to see if the result is 5050 of the students ' mental arithmetic.

The second loop is the while loop, which, as long as the condition is satisfied, loops continuously, exiting the loop when the condition is not satisfied. For example, we want to calculate the sum of all the odd numbers within 100, which can be implemented with a while loop:

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

The loop internal variable n is continuously self-reducing until it becomes 1, and the while condition is no longer satisfied, and the loop exits.
Another discussion on Raw_input

Finally see a problematic condition to judge. Many students will use Raw_input () to read the user's input, so that they can input, the program runs more interesting:

Birth = Raw_input (' Birth: ') if birth <:  print ' 00 ago ' else:  print ' 00 after '

Input 1982, the results show 00, so simple to judge Python can also be mistaken?

Of course it's not the Python question, print birth under the interactive command line in Python:

>>> birth ' 1982 ' >>> ' 1982 ' < 2000false>>> 1982 < 2000True

Reason to find out! The original read from Raw_input () is always returned as a string, the string and an integer comparison will not get the expected results, you must first use INT () to convert the string to the integer type we want:

birth = Int (raw_input (' Birth: '))

Run again to get the right results. But what if I enter ABC? And you get an error message:

Traceback (most recent): ... Valueerror:invalid literal for int. () with base: ' abc '

The original int () found a string is not a valid number when the error occurs, the program exits.

How do I check and capture the program run-time errors? The subsequent errors and debugs will be covered.
Summary

Conditional judgment allows the computer to make its own choices, and Python's if...elif...else is flexible.

Loops are an effective way to make a computer do repetitive tasks, and sometimes, if the code is written with a problem, it causes the program to fall into a "dead loop", that is, to cycle forever. You can then use CTRL + C to exit the program, or force the end of the Python process.

Please try to write a dead loop program.

  • Related Article

    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.