Fourth: conditions and loops of the Python Foundation

Source: Internet
Author: User

Read Catalogue

I. If statement

1.1 Features

1.2 Syntax

1.2.1: single-branch, single-weight condition judgment

1.2.2: single branch, multiple criteria judgment

1.2.3:if+else

1.2.4: multi-branch If+elif+else

Summary of 1.2.5:IF statements

1.3 Cases

1.4 Three-dimensional expression

Two. while statement

2.1 Features

2.2 Syntax

2.2.1: Basic Syntax

2.2.2: Counting Cycle

2.2.3: Infinite Loop

2.2.4:while and Break,continue,else

Summary of 2.2.5:while statements

2.3 Cases

Three. for statement

3.1 Features

3.2 syntax

3.2.1: Basic Syntax

3.2.2: traversing sequence types

3.2.3: traversing an iterative object or iterator

3.2.4:for counting loops based on range ()

3.2.5:for and Break,continue,else

Summary of 3.2.6:FOR statements

3.3 Cases

Four. Practice

I. If statement


1.1 Features


Computers are also called computers, meaning that computers can react differently to changes in ambient conditions (i.e., expession), like the human brain, which is code Execution.


The IF statement is to control the computer to achieve this function


1.2 Syntax


1.2.1: single-branch, single-weight condition judgment


If expression:


Expr_true_suite


Note: Expession is a true code execution Expr_true_suite


1.2.2: single branch, multiple criteria judgment


If not active or Over_time >= 10:


Print (' Warning:service is dead ')


Warn_tag+=1


1.2.3:if+else


If expression:


Expr_true_suite


Else


Expr_false_suite


1.2.4: multi-branch If+elif+else


If expession1:


Expr1_true_suite


Elif expression2:


Expr2_true_suite


Elif expession3:


Expr3_true_suite


Else


None_of_the_above_suite


Summary of 1.2.5:IF statements


If the expression returns a value of True then it executes its child code block, then the IF statement to this end, otherwise into the next branch judgment, until one of the branches is satisfied, after executing the IF

Expression can introduce an operator: not,and,or,is,is not

Multiple expression for enhanced readability most useful parentheses contain

A consistent representation of if and else indentation level is a pair

Elif and else are optional

An if judge has at most one else but can have multiple elif

else represents the end of if judgment

Expession can be the form of an expression that returns a Boolean value (example x>1,x is not None) or a single Standard object (example x=1;if x:print (' OK '))

All standard objects are available for Boolean testing and can be compared between objects of the same type. Each object inherently has a Boolean True or False Value. A null object, any number with a value of zero, or a Boolean value of None for the null object is False.

The Boolean value of the following object is False




1.3 Cases



#!/usr/bin/env python

#_ *_coding:utf-8_*_


‘‘‘

Prompt to enter user name and password


Verify user name and password

If error, the output user name or password is incorrect

If successful, the output is welcome, xxx!

‘‘‘


Import Getpass


Name=input (' User Name: ')

Passwd=getpass.getpass (' password: ')


If name = = ' Tom ' and passwd = = ' 123 ':

Print (' Welcome ')

Else

Print (' Get out ')



1.4 Three-dimensional expression


Grammar:


Expr_true_suite if expession else expr_false_suite


Case One:


>>> active=1

>>> Print (' service is active ') if active else print (' service is inactive ')

Service is active

Case Two:


>>> x=1

>>> y=2

>>> smaller=x if x < y else y

>>> smaller

1

Two. while statement


2.1 Features


The essence of the while loop is to allow the computer to repeat the same thing (that is, the while loop is a conditional loop, which Includes: 1. condition count cycle, 2 conditional infinite LOOP)


This condition means: conditional expression


The same thing means: the block of code that the while loop body contains


Repeat things such as: from 1 to 10000, ask for all the odd numbers within 1-10000, the service waits for a connection


2.2 Syntax


2.2.1: Basic Syntax


While Expression:


Suite_to_repeat


Annotations: repeat suite_to_repeat until expression is no longer true


2.2.2: Counting Cycle


Count=0

While (count < 9):

Print (' the loop is%s '%count)

Count+=1

2.2.3: Infinite Loop


Count=0

While True:

Print (' the loop is%s '%count)

Count+=1

Tag=true

Count=0

While Tag:

if count = = 9:

Tag=false

Print (' the loop is%s '%count)

Count+=1

2.2.4:while and Break,continue,else



Count=0

While (count < 9):

Count+=1

if count = = 3:

Print (' jump out of this layer, i.e. completely end this one/layer while Loop ')

Break

Print (' the loop is%s '%count)


Count=0

While (count < 9):

Count+=1

if count = = 3:

Print (' out of this loop, the code after this loop continue no longer executes, into the next loop ')

Continue

Print (' the loop is%s '%count)


Count=0

While (count < 9):

Count+=1

if count = = 3:

Print (' out of this loop, the code after this loop continue no longer executes, into the next loop ')

Continue

Print (' the loop is%s '%count)

Else

Print (' loop is not interrupted by break, that is, it will execute the else after code block ')





Count=0

While (count < 9):

Count+=1

if count = = 3:

Print (' out of this loop, the code after this loop continue no longer executes, into the next loop ')

Break

Print (' the loop is%s '%count)

Else

Print (' loop is interrupted by break, that is, not normal, the Else post code block is not executed ')

Summary of 2.2.5:while statements


The condition is true, repeating the code until the condition is no longer true, and if the condition is true, the code executes once and ends

While there are counting loops and infinite loops, an infinite loop can be used for a service where the main program has been waiting for the connected state

Break represents jumping out of this layer, continue represents jumping out of this loop

The while loop ends without being interrupted by a break, it executes the Else post code

2.3 Cases



While True:

handle, indata = Wait_for_client_connect ()

Outdata = Process_request (indata)

Ack_result_to_client (handle, Outdata)


Import Getpass


account_dict={' Alex ': ' 123 ', ' Eric ': ' 456 ', ' rain ': ' 789 '}

Count = 0

While Count < 3:

Name=input (' user name: '). strip ()

Passwd=getpass.getpass (' password: ')

If name in Account_dict:

Real_pass=account_dict.get (name)

if passwd = = Real_pass:

Print (' Login Successful ')

Break

Else

Print (' Password input error ')

Count+=1

Continue

Else

Print (' user not present ')

Count+=1

Continue

Else

Print (' try 3 times, please retry later ')

Three. for statement


3.1 Features


The For loop provides the most powerful loop structure in Python (the for loop is an iterative loop mechanism, while the while loop is a conditional loop, and the iteration repeats the same logical operation, and each operation is based on the last Result)


3.2 syntax


3.2.1: Basic Syntax


For Iter_var in Iterable:


Suite_to_repeat


Note: each loop, the Iter_var iteration variable is set to iterate over the current element of an object (sequence, iterator, or other object that supports ITERATIONS) and is provided to the SUITE_TO_REPEAT statement block for Use.


3.2.2: traversing sequence types


name_list=[' Alex ', ' Eric ', ' rain ', ' xxx '


#通过序列项迭代

For I in Name_list:

Print (i)


#通过序列索引迭代

For I in range (len (name_list)):

Print (' index is%s,name%s '% (I,NAME_LIST[I))


#基于enumerate的项和索引

For I,name in enumerate (name_list,2):

Print (' index is%s,name%s '% (i,name))

3.2.3: traversing an iterative object or iterator


Iteration Object: is an object with the next () method, obj.next () executes once, returns a row of content after all the content has been iterated,


The iterator throws a stopiteration exception telling the program that the loop is Over. The For statement internally calls next () and catches the Exception.


The For loop iterates through an iterator or an iterative object and iterates through the sequence of methods and does nothing but internally makes a call to the iterator next () and catches the exception, terminating the loop operation


Many times you simply cannot tell whether a for loop is a sequence object or an iterator


>>> f=open (' a.txt ', ' r ')


For I in F:

Print (i.strip ())

Hello

Everyone

Sb

3.2.4:for counting loops based on range ()


Range () Syntax:


Range (start,end,step=1): Gu Tou regardless of tail


Range (10): default step=1,start=0, generates an iterative object, containing [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Range (1,10): Specify start=1,end=10, default step=1, generate an iterative object, including [1, 2, 3, 4, 5, 6, 7, 8, 9]

Range (1,10,2): Specifies start=1,end=10,step=2, generates an iterative object, containing [1, 3, 5, 7, 9]

>>> List (range (10))

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> for I in range (10):

Print (i)

0

1

2

3

4

5

6

7

8

9


Note: for a count loop based on range (), range () generates an iterative object that describes the for loop essence or an iterative loop


3.2.5:for and Break,continue,else


Same while


Summary of 3.2.6:FOR statements


The For loop is an iterative loop

Can traverse sequence members (strings, lists, tuples)

Can iterate over any iterator object (dictionary, file, etc.)

can be used in list parsing and builder expressions

Break,continue,else usage in for is consistent with while

3.3 Cases


Albums = (' Poe ', ' Gaudi ', ' Freud ', ' Poe2 ')

years = (1976, 1987, 1990, 2003)


#sorted: sorting

For album in sorted (albums):

Print (album)


#reversed: Flip

For album in reversed (albums):

Print (album)


#enumerate:

For I in enumerate (albums):

Print (i)

#zip: Combination

For I in Zip (albums,years):

Print (i)

Four. Practice


first, the element classification


There is a collection of the following values [11,22,33,44,55,66,77,88,99,90 ...], saving all values greater than 66 to the first key in the dictionary, and saving the value less than 66 to the value of the second key.

That is: {' K1 ': All values greater than 66, ' K2 ': all values less than 66}


second, Find

Finds the elements in the list, removes the spaces for each element, and finds all elements that begin with a or a and end with C.


third, the output commodity list, the user enters the serial number, displays the user to select the product

Product Li = ["mobile phone", "computer", "mouse pad", ' yacht ')

four, Shopping Cart

Functional Requirements:


Require users to enter total assets, for Example: 2000

Display the list of items, let the user select the item according to the serial number, add the shopping cart

purchase, if the total amount of goods is greater than the total assets, indicating that the account balance is insufficient, otherwise, the purchase succeeds.

Add: can recharge, a product to remove the shopping cart

goods = [

{"name": "computer", "price": 1999},

{"name": "mouse", "price": 10},

{"name": "yacht", "price": 20},

{"name": "beauty", "price": 998},

]

V. User interaction, showing the choice of three-level linkage between provincial and municipal counties


DIC = {

"hebei": {

"shijiazhuang": ["luquan", "Gaocheng", "yuanshi"],

"handan": ["yongnian", "she county", "ci"],

}

"henan": {

...

}

"shanxi": {

...

}

}


This article from the "wandering wind" blog, reproduced please contact the author!

Fourth: conditions and loops of the Python Foundation

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.