Getting Started with Python (v) Conditional judgment and looping

Source: Internet
Author: User

If statement

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

For example, to enter user age, print different content according to age, in a Python program, you can use the if statement:

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

Note: The indentation rules for Python code. Code with the same indentation is treated as a block of code, with 3, 4 lines of print statements constituting a block of code (but excluding print on line 5th). If the IF statement evaluates to True, the code block is executed.

Indent please strictly follow Python's customary notation:4 spaces, do not use tab, do not Mix tab and space, otherwise it is easy to cause syntax errors due to indentation.

Note : The IF statement is followed by an expression, and then begins with the : representation code block.

If you hit the code in a Python interactive environment, also pay special attention to indentation, and exit indentation requires more than one line of return:

>>> age = 20>>> if age >=:     ... print ' Your age was ',     age ... print ' adult ' ... your age is 20adult

Task

If the score reaches 60 or more, it is considered passed.

Let's say that Bart's score is 75, use the IF statement to determine if passed can be printed:

If-else

When the if statement determines that the result of the expression is True, the IF-contained code block is executed:

If age >=:    print ' adult '

What if we want to judge the age under 18 and print out ' teenager '?

The method is to write another if:

If age <:    print ' teenager '

Or use the NOT operation:

If not age >=:    print ' teenager '

Careful classmates can find that these two conditions are either "or", or meet the condition 1, or meet the condition 2, so you can use an if ... else ... Statements to unify them together:

If age >=:    print ' adult ' else:    print ' teenager ' 

Use if ... else ... Statement, we can execute an if code block or an else code block, depending on the value of the conditional expression, either True or False.

Note: else there is a ":" later.

Task

If the achievement reaches 60 points or above, treats as passed, otherwise treats as failed.

Let's say that Bart's score is 55, use the IF statement to print out passed or failed:

If-elif-else

Sometimes, an if ... else ... It's not enough. For example, according to the age of the division:

Condition 1: Age 18 or above: Adult condition 2:6 years old or above: Teenager Condition 3: Under 6 years of age: Kid

We can use an if age >= 18 to determine whether the condition 1, if not, and then through an if to determine the age >= 6来 to determine whether to meet the condition 2, otherwise, the execution condition 3:

If age >=:    print ' adult 'else:    if >= 6: print '        teenager '    else:        print ' Kid ' /c7> 

To write this out, we get a two-layer nested if ... else ... Statement. There is no problem with this logic, but if you continue to add conditions, such as baby under age 3:

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

This indentation will only get more and more and the code will become more and more ugly.

To avoid nesting structures if ... else ..., we can use the if ... Multiple elif ... else ... Structure, write all the rules at once:

If age >=:    print ' adult 'elif age >= 6:    print ' teenager ' elif age>= 3: print ' Kid ' C9>else:print ' baby '     

Elif means else if. In this way, we write a series of conditional judgments that are very clear in structure.

Special attention: This series of conditional judgment will be judged from top to bottom, if a certain judgment is True, after executing the corresponding code block, the subsequent condition judgment is ignored and no longer executed.

Consider the following code:
Age = 8if Age >= 6:    print ' teenager ' elif age >=:    print ' adult ' else:    print ' Kid '

When age = 8 o'clock, the result is correct, but Age = 20 o'clock, why is adult not printed?

What should I do if I want to fix it? --Interchange conditions

Task

If the result is delimited by fractions:

90 points or more: excellent

80 points or more: good

60 points or more: passed

60 min.: Failed

Write your program to print the results based on the score.

For loop

A list or tuple can represent an ordered set. What if we want to access each element of a list in turn? such as list:

L = [' Adam ', ' Lisa ', ' Bart ']print l[0]print l[1]print l[2]

If the list contains only a few elements, it is OK to write, and if the list contains 10,000 elements, we cannot write 10,000 lines of print.

This is where the loop comes in handy.

The python for Loop can then iterate over each element of the list or tuple in turn:

L = [' Adam ', ' Lisa ', ' Bart '] inL:    Print name

Note: name this variable is defined in the For loop, meaning that each element in the list is taken out, the element is assigned to name, and then the for loop body is executed (that is, the indented block of code).

This makes it very easy to traverse a list or tuple.

Task

After the class exam, the teacher to statistical average results, 4 students are known to list the results are as follows:

L = [75, 92, 59, 68]

Please use the For loop to calculate the average score.

While loop

Another loop that differs from the For loop is the while loop , which does not iterate over the elements of the list or tuple, but rather determines whether the loop ends with an expression.

For example, to print an integer no greater than N from 0:

n = 10x = 0 whilex < N:    print x    x = x + 1 

The while loop first evaluates x < N, if true, executes the block of code for the loop body, otherwise, exits the loop.

In the loop,x = x + 1 causes x to increase and eventually exits the loop because x < N is not true.

Without this statement, thewhile loop always evaluates to True for x < N, it loops indefinitely and becomes a dead loop, so pay special attention to the exit condition of the while loop.

Task

Use the while loop to calculate an odd number of 100 or less.

Break Exit Loop

When using a For loop or while loop, you can use the break statement if you want to exit the loop directly inside the loop .

For example, to calculate integers from 1 to 100, we use while to implement:

sum = 0x = 1 whileTrue:    sum = sum + x    x = x + 1    if x >:        breakprint sum 

At first glance, while True is a dead loop, but in the loop, we also determine that x > 100 pieces are set up, using the break statement to exit the loop, which can also achieve the end of the loop.

Task

Use the while True infinite loop with the break statement to calculate 1 + 2 + 4 + 8 + 16 + ... The first 20 items of the and.

Continue continue circulation

During the loop, you can use break to exit the current loop, and you can use continue to skip the subsequent loop code and continue the next loop.

Let's say we've written the code that calculates the average score using the For loop:

L = [98, M, M, ba, 85]sum = 0.0n = 0 inL:    sum = sum + x    n = n + 1print sum/n

Now the teacher just want to count the average of passing scores, it is necessary to cut off the score of x < 60, then, using continue, can be done when x < 60, do not continue to execute the loop body follow-up code, directly into the next cycle:

For x in L:    if x <:        continue    sum = sum + x    n = n + 1

Task

Transformation of the existing while loop of calculation 0-100, by adding continue statements, so that only odd-numbered and:

sum = 0x = 1while True:    sum = sum + x    x = x + 1    if x >:        breakprint sum

Multiple loops

Inside the loop, you can also nest loops, let's look at an example:

In [' A ', ' B ', ' C ']: in   [' 1 ', ' 2 ', ' 3 ']:        print x + y

X cycles once,y loops 3 times, so we can print out a full array:

A1
A2
A3
B1
B2
B3
C1
C2
C3

Task

For two digits up to 100, use a double loop to print out all 10-digit numbers that are smaller than the single digit number, for example, (2 < 3).



Getting Started with Python (v) Conditional judgment and looping

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.