Python -- conditions, loops, and other statements

Source: Internet
Author: User

I. More information about print and import

Print is also feasible to print multiple expressions, as long as they are separated by commas:

>>> print('Age:' , 42)Age: 42
We can see that a space character is inserted between each parameter. This feature is useful if you want to output both text and variable values without using string formatting.


When importing functions from a module, you can use

import  somemodule

Or

from  somemodule import  somefunction

Or

from somemodule import somefunction, anotherfunction, yetanotherfunction

Or

from somemodule import *

The last version should be used only when you are sure you want to import all functions from a given module. But what should I do if both modules have open functions? You only need to use the first method for import and then use the function as follows:

module1.open(...)module2.open(...)
Another option is to add an as clause at the end of the statement, give a name after the clause, or provide an alias for the entire module:

>>> import math as foobar>>> foobar.sqrt(4)2.0
You can also provide aliases for functions:

>>> from math import sqrt as foobar>>> foobar(4)2.0

For open functions, you can use them as follows:

from module1 import open as open1from module2 import open as open2

Ii. Assignment

1. Sequential unpacking

Multiple assignment operations can be performed simultaneously:

>>> x, y, z = 1, 2, 3>>> print(x, y, z)1 2 3
Use it to exchange two (or more) variables:

>>> x, y = y, x>>> print(x, y, z)2 1 3
In fact, what we do here is the sequence unpacking or the optional replacement package-the sequence of multiple values is unbound and then placed in the sequence of variables. This feature is particularly useful when a function or method returns tuples (or other sequences or optional iteration objects. It allows the function to return more than one value and package it into a metagroup. Then, it can be easily accessed through a value assignment statement.

>>> scoundrel = {'name':'Robin', 'girlfriend':'Marion'}>>> key, value = scoundrel.popitem()>>> key'name'>>> value'Robin'
The number of elements in the sequence to be decompressed must be exactly the same as the number of variables placed on the left of the Value Pair =; otherwise, Python will cause an exception when assigning values:

>>> x, y, z = 1, 2Traceback (most recent call last):  File "
 
  ", line 1, in 
  
   ValueError: need more than 2 values to unpack>>> x, y, z = 1, 2, 3, 4Traceback (most recent call last):  File "
   
    ", line 1, in 
    
     ValueError: too many values to unpack (expected 3)
    
   
  
 
Python 3.0 has another feature: the asterisk operator can be used as in the function parameter list. For example, a, B, * rest = [1, 2, 3, 4] will eventually collect all other parameters into rest after a and B are assigned values.

2. Chain assignment

Chained assignment is a shortcut to assign the same value to multiple variables.

x = y = somefunction() 


3. Incremental assignment

Place the expression operator (in this example +-) on the left side of the value assignment operator = and write it as x + = 1. This method is called Incremental assignment.

>>> x = 2>>> x += 1>>> x *= 2>>> x6
Applicable to other data types:

>>> fnord = 'foo'>>> fnord += 'bar'>>> fnord *= 2>>> fnord'foobarfoobar'

III. Statement Block

A statement block is a group of statements that are executed or executed multiple times when the condition is true (Condition Statement. Place a space before the code to indent the statement to create a statement block.

In Python, the colon (:) is used to mark the beginning of the statement block. Each statement in the block is indented (with the same number of indentations ). When it is rolled back to the same indentation as the closed block, it indicates that the current block has ended.


Iv. Condition and condition statements

1. boolean variable

When the following value is used as a Boolean expression, it will be spoofed by the interpreter (false ):

False None 0 "" () [] {}

In other words, that is, the standard values False and None, all types of numbers 0 (including floating point, long integer, and Other types), empty sequences (such as empty strings, tuples, and lists) and empty dictionaries are false. Everything else is interpreted as True, including the special value True.

Boolean values True and False belong to the boolean type. The bool function can be used to convert other values (like list, str, and tuple.

>>> bool('I think, therefore I am')True>>> bool(42)True>>> bool('')False>>> bool(0)False
Because all values can be used as boolean values, there is almost no need to display and convert them (it can be said that Python will automatically convert these values ).


2. Conditional execution (if/else/elif)

num = input('Enter a number: ')if num > 0:    print('The number is positive')elif num < 0:    print('The number is negative')else:    print('The number is zero')

3. nested code blocks

name = raw_input('What is your name? ')if name.endswith('Gumby'):    if name.startswith('Mr. '):        print('Hello, Mr. Gumby')    elif name.startswith('Mrs. '):        print('Hello, Mrs. Gumby')    else:        print('Hello, Gumby')else:    print('Hello, stranger')


4. More complex items

4.1 comparison Operators

Expression Description
X = y X equals to y
X <y X less than y
X> y X is greater than y
X> = y X greater than or equal to y
X <= y X less than or equal to y
X! = Y X is not equal to y
X is y X and y are the same object.
X is not y X and y are different objects.
X in y X is a member of the y container.
X not in y X is not a member of the y container.
In Python 3.0, incompatible objects are no longer feasible.

In Python, the comparison operation and the assignment operation can be connected. Several operators can be connected for use, for example, 0 <age <100.

4.2 Equal Operators

If you want to know whether two things are equal, you should use the equal operator, that is, two equal signs =:

>>> "foo"=="foo"True>>> "foo"=="bar"False

4.3 is: identity Operator

The is operator determines the same identity rather than equality.

>>> x = y = [1, 2, 3]>>> z = [1, 2, 3]>>> x == yTrue>>> x == zTrue>>> x is yTrue>>> x is zFalse
Use the = Operator to determine whether two objects are equal, and use the is operator to determine whether the two are equal (the same object ).

4.4 in: Membership Operator

4.5 comparison of strings and Sequences

Strings can be sorted alphabetically for comparison.

>>> "alpha" < "beta"True

Other sequences can also be compared in the same way, but the comparison is not a character but other types of elements.

>>> [1, 2] < [2, 1]True

4.6 boolean operator

And, or, and not operators are so-called boolean operators.

5. Assertions

>>> age = 10>>> assert 0 < age < 100>>> age = -1>>> assert 0 < age < 100Traceback (most recent call last):  File "
 
  ", line 1, in 
  
   AssertionError
  
 
If you need to ensure that a certain condition in the program is true for the program to work normally, the assert statement is useful and can be used to set checkpoints in the program.

You can add a string after the condition to explain the assertions:

>>> age = -1>>> assert 0 < age < 100, 'The age must be realistic'Traceback (most recent call last):  File "
 
  ", line 1, in 
  
   AssertionError: The age must be realistic
  
 


V. Loop

5.1 while LOOP

>>> while x <= 100:...     print(x)...     x += 1...

5.2 for Loop

>>> words = ['this', 'is', 'an', 'ex', 'parrot']>>> for word in words:...     print(word)...
Because iterations (another statement of loops) numbers in a certain range are very common, there is a built-in range function range for use:

>>> for number in range(1, 101):...     print(number)...

5.3 looping dictionary elements

A simple for statement can loop all the keys of the dictionary, just like the processing sequence:

>>> d = {'x':1, 'y':2, 'z':3}>>> for key in d:...     print(key, 'corresponds to', d[key])...z corresponds to 3x corresponds to 1y corresponds to 2
D. The items method returns key-value pairs as tuples. A major benefit of the for Loop is that sequential unpacking can be used in a loop:

>>> for key, value in d.items():...     print(key, 'corresponds to', d[key])...
The order of dictionary elements is usually not defined. In other words, keys and values in the dictionary can be processed during iteration, but the processing sequence is uncertain.

5.4 Some iteration tools

A. Parallel Iteration

The program can iterate two sequences at the same time.

>>> names = ['anne', 'beth', 'george', 'damon']>>> ages = [12, 45, 32, 102]>>> for i in range(len(names)):...     print(names[i], 'is', ages[i], 'years old')...
The built-in zip function can be used for parallel iteration, and the two sequences can be "COMPRESSED" together.

>>> for name, age in zip(names, ages):...     print(name, 'is', age, 'years old')...
The zip function can also act on any number of sequences. The most important thing about it is that zip can cope with an unequal sequence: it will stop when the shortest sequence is "used up.

B. Number Iteration

The enumerate function can iterate the index-value pair where the index is provided.

for index, string in enumerate(strings):    if 'xxx' in strings:        strings[index] = '[censored]'

C. Flip and sort Iteration

Reversed and sorted act on any sequence or iteratable object. Instead of modifying the object in the original place, they return the flipped or sorted version:

>>> sorted('Hello, world!')[' ', '!', ',', 'H', 'd', 'e', 'l', 'l', 'l', 'o', 'o', 'r', 'w']>>> list(reversed('Hello, world!'))['!', 'd', 'l', 'r', 'o', 'w', ' ', ',', 'o', 'l', 'l', 'e', 'H']
Although the sorted method returns a list, the reversed method returns a more incredible iteration object.

5.5 skip Loop

A. Break

You can use the break statement to end (exit) the loop.

B. Continue

Continue will end the current iteration and "jump" to the start of the next loop.

C. While True/break Idioms

>>> while True:...     word = input('Please enter a word: ')...     if not word: break...     print('The word was ' + word)...
While True implements a loop that never stops itself. However, you can add conditions to the if statement in the loop. when the conditions are met, the break statement is called.

5.6 else clause in a loop

Add an else clause in the loop-it is executed only when break is not called.

>>> from math import sqrt>>> for n in range(99, 81, -1):...     root = sqrt(n)...     if root == int(root):...             print(n)...             break... else:...     print("Didn't find it")...Didn't find it

6. List Derivation

List comprehension is a method for creating a new list using other lists. It works like a for Loop:

>>> [x*x for x in range(10)][0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
You can add an if part to the list derivation:

>>> [x*x for x in range(10) if x % 3 == 0][0, 9, 36, 81]
You can also add more for statements:

>>> [(x, y) for x in range(3) for y in range(3)][(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
It can also be used together with the if clause, as before:

>>> girls = ['alice', 'bernice', 'clarice']>>> boys = ['chris', 'arnold', 'bob']>>> [b + '+' + g for b in boys for g in girls if b[0]==g[0] ]['chris+clarice', 'arnold+alice', 'bob+bernice']

7. pass, del, and exec

1. Nothing happened

Sometimes, the program does not need to do anything. This is not the case, but once it appears, the pass statement should be released.

2. Delete with del

Using the del statement, it not only removes the reference of an object, but also removes the name itself.

3. execute and evaluate strings using exec and eval

A. Exec

The statement for executing a string is exec.

>>> exec('print("Hello, world!")')Hello, world!
The most useful part of an exec statement is the ability to dynamically create code strings.

B. Eval

Evel (used for "evaluate") is a built-in function similar to exec. The exec statement executes a series of Python statements, and the eval calculates the Python expression (written in string form) and returns the result value.

>>> eval(input("Enter an arithmetic expression: "))Enter an arithmetic expression: 6 + 18 * 242


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.