Conditional judgment and looping for the basics of getting started with Python

Source: Internet
Author: User

Python's If statement

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

Age =If age >=:    print'your     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.

(tab is not recommended for the number of spaces that are indented in different operating system platforms and in different applications.)

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:

if age >=:      ... Print ' your age is ' , age ...      Print ' Adult '   isadult

The If-else of Python

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.

issue: Use Idel to compile Python code with line indent capability. So every time I enter           else:not  match any outer indentation level problem resolution: If preceded by >>>3 placeholders, But if it is actually shelf, the first line indent is 0, so before you enter else, use BACKSPACE to indent the else first line to 0. Code:if score<=60:    Print  'Failed'else:    print '  Passed'    Failed

The If-elif-else of Python
if age >=:    print'adult'else:     If age >= 6:        print'teenager'    Else :         Print ' Kid '

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:

ifAge >= 18:    Print 'Adult'Else:    ifAge >= 6:        Print 'teenager'    Else:        ifAge >= 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 >= 18:  print  "  adult  "  elif  age >= 6:  Span style= "COLOR: #0000ff" >print   "  Teenager   " elif  age >= 3:  print   " Span style= "COLOR: #800000" >kid   " else  :  print   '  

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.

Python for Loop

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

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

L = ['Adam'Lisa'Bart']   for in L:    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.

Python's While loop
n = ten= 0 while x < N:    print  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, the while 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.

The break of Python exits the 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 =1 while  True    := sum + 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.

The continue of Python continues to circulate

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, M, N, A, a, * = 0.0= 0 for in L:    = sum +  x    = 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 inch L:     if x <:        continue    = sum + x    = n + 1

Python's multiple loops

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

 for  x in  [  " a  , "  b  , "  c   " ]:  for  y in< /span> [ " 1   ' ,  '  2   ' ,  '  3   '  

x cycles once, Y loops 3 times, so we can print out a full array:

A1
A2
A3
B1
B2
B3
C1
C2
C3

What Python is Dict

We already know that list and tuple can be used to represent sequential collections, for example, the name of the class:

['Adam'Lisa'Bart']

Or the test results list:

[95, 85, 59]

However, to find the corresponding score according to the name, it is inconvenient to use two list to indicate.

If you associate a name with a score, make a similar look-up table:

' Adam ' ==> 'Lisa' ==> 'Bart' ==> 59

Given a name, you can find the score directly.

Python's dict is dedicated to doing this. The lookup table for "name"-"score" is shown in Dict as follows:

D = {    'Adam': +,    'Lisa':     ' Bart ':

We call the name key, and the corresponding result, called Value,dict, is to find value by key.

The curly braces {} indicate that this is a dict, and then follow the Key:value and write them out. The last comma of a key:value can be omitted.

Since Dict is also a collection, the Len () function can calculate the size of any collection:

>>> Len (d)3

Note: A key-value is counted one, so the dict size is 3.

Python's visit to Dict

We have been able to create a dict that represents the correspondence between the name and the score:

D = {    'Adam': +,    'Lisa':     ' Bart ':

So, how to find the corresponding score according to the name?

You can simply use the form of D[key] to find the corresponding value, which is like the list, but the list must return the corresponding element using the index, and Dict uses key:

 >>> print  d[ " adam  "  ]  95>> > print  d[ " paul   " ]traceback (most recent call last): File   " Span style= "COLOR: #800000" >index.py   ", line 11, in  <module> print  d["  paul   " ]keyerror:   " paul   " 

Note: The value of dict is accessed by key, and Dict returns the corresponding value as long as the key exists. If key does not exist, it will directly error: Keyerror.

There are two ways to avoid keyerror:

First, determine whether the key exists, with the in operator:

if ' Paul ' inch d:     print d['Paul'

If ' Paul ' is not present, the IF statement evaluates to False, and the print d[' Paul ' is not executed naturally, thus avoiding the error.

The second is to use the dict itself to provide a get method, when the key does not exist, return to none:

print d.get ('Bart')print d.get ('Paul  ') None

Example:

= {    'Adam': +,    'Lisa':  ,    'Bart':59
D = {    'Adam': 95,    'Lisa': 85,    'Bart': 59}Print 'Adam:', d['Adam']Print 'Lisa:', d['Lisa']Print 'Bart:', d['Bart']

Conditional judgment and looping for the basics of getting started with Python

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.