A tutorial on using judgment statements and loops in Python _python

Source: Internet
Author: User
Tags in python

Conditional judgment

A computer can do a lot of automated tasks because it can make its own conditional judgments.

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

Age =
>=:
  print ' Your The age is ', age
  print ' adult '

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

You can also add an else statement to the IF, meaning that if the If judgment is false, do not perform the contents of if, and then execute the else:

Age = 3
if age >= to
  print ' your ' ', age print '
  adult '
else:
  print ' Your
  ' print ' teenager '

Be careful not to write a colon less:.

Of course, the above judgment is very sketchy, can use Elif to do more detailed judgment:

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

Elif is an abbreviation for else if, there can be multiple elif, so the complete form of an if statement is:

If < condition judgment 1>:
  < execution 1>
elif < conditional judgment 2>:
  < execution 2> Elif
< conditional judgment 3>:
  < execution 3>
Else:
  < executive 4>

If statement execution has a feature, it is judged from the top down, if in a certain judgment is true, the statement corresponding to the sentence after the execution, ignore the remaining elif and else, so please test and explain why the following program prints the teenager:

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

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

If x:
  print ' True '

As long as X is a non-0 numeric, non-empty string, Non-empty list, and so on, it is judged to be true or false.
Loops

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

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

Executing this code prints each element of the names in turn:

Michael
Bob
Tracy

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

Again, for example, we want to compute the sum of 1-10 integers:

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

If you want to calculate the sum of 1-100 integers, it's hard to write from 1 to 100, but luckily Python provides a range () function that generates an integer sequence, such as a range (5) that generates a sequence that is less than 0 starting at 5:

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

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

sum = 0 for
x in range (a):
  sum = sum + x
print sum

Please run the above code, to see if the results are not the same year, Gauss students in mental arithmetic out of 5050.

The second loop is the while loop, which loops as long as the condition is satisfied, and exits the loop if the condition is not satisfied. For example, we want to compute the sum of all odd numbers within 100, which can be implemented using a while loop:

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

Within the loop the variable n is continuously reduced until it becomes-1, no longer satisfies the while condition, and the loop exits.
further discussion on Raw_input

Finally look at 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 before '
else:
  print ' 00 after '

Input 1982, the result is 00, so simple to judge Python can also be mistaken?

Of course it's not a python problem, print birth on the python interactive command line:

>>> birth
' 1982 '
>>> ' 1982 ' <%
False
>>> 1982 <
True

The reason has been found! The content originally read from Raw_input () is always returned as a string, the string and the integer comparison will not get the expected results, you must first use INT () to convert the string to the integer we want:

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

Run again, you can get the correct results. But what if you enter ABC? And you get an error message:

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

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

How do I check and capture the Run-time errors of the program? Later errors and debugging will be mentioned.
Summary

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

A loop is an effective way to make a computer do repetitive tasks, and sometimes, if the code is written with a problem, the program gets stuck in a "dead loop", which is forever recycled. You can then use CTRL + C to exit the program, or to 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.