Use of python conditions and loops

  • 2020-04-02 13:14:13
  • OfStack

We have already introduced several basic statements (print, import, assignment), and now we will introduce conditional statements, loop statements.
Print and import for more information
1.1 use comma output
A. Print multiple expressions separated by commas to insert A space between each parameter:


>>> print 'age:',42
age: 42

B. Output text and variable values at the same time, but do not want to use string format:

>>> name = 'Peter'
>>> greeting = 'Hello'
>>> print greeting,',',name
Hello , Peter

The above example will add a space before the comma, we can optimize:

>>> print greeting + ',',name
Hello, Peter

Note that if you put a comma at the end, the following statement is printed on the same line as the previous one:

>>> print 'Hello,',
    print 'world'
Hello,world
 

1.2 import one thing as another
When importing a function from a module, you can use:
Entire module import: import somemodule
Import one of these functions: from somemodule import somefunction
Import several functions: the from somemodule import somefunction, anotherfunction, yetanotherfunction
Import all functions: from somemodule import *
If two modules have functions with the same name, such as the open function, you can provide an alias for the function or module by:

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


Two. Assign magic
Even the humble assignment statement has some special tricks.
2.1 sequence unpacking
Sequence unpacking is unpacking a sequence of values into a sequence of variables.

> > > #' multiple assignments simultaneously '
> > > X, y, z = 1, 2, 3
> > > Print the x, y, z
1 2 3
> > > #' swap 2 or more variables'
> > > X, y = y, x
> > > Print the x, y
2 1
> > > #' when a function or method returns a tuple '
> > > S = {' a ', 1, 'b' : 2, 'c' : 3}
> > > The key, value =   Supachai panitchpakdi opitem ()
> > > Print the key and the value
A 1
As you can see from the last example, it allows a function to return more than one value and package it into tuples, which are then easily accessed through a copy statement.
Note: the number of elements in the unpacked sequence must be exactly the same as the number of variables placed to the left of the assignment coincidence =, otherwise an exception will be thrown.

2.2 chain assignment
Chained assignment is a shortcut to assign the same value to more than one variable.
> > > X is equal to y is equal to 'ss '.

2.3 incremental assignment
Incremental assignments make the code more compact and concise.
For +, -, *, /, % and other standard operators are applicable:

> > > X = 2
> > > X + = 1
> > > X * = 2
> > > x
6
> > > # also works with other data types
> > > F = 'foo'
> > > F + = 'bar'
> > > f
"Foobar"

Three. Statement block: the fun of indentation
  A statement block is a set of statements that are executed once or more when the condition is true. In python, the colon (:) identifies the beginning of a block of statements, each of which is indented. When you go back to the same amount of indentation as a closed block, the current block is over.

Four. Conditions and conditional statements
4.1 this is what Boolean variables do
The following values are treated as False by the interpreter as Boolean expressions:
False None 0 "" () [] {}
Everything else is interpreted as True, including the special value True.

4.2 conditional execution and if statements
If the condition is true, the subsequent statement blocks are executed, or the elif can be added for multiple condition checks. As part of the if, there is an else clause.
Of course, we can use if statements nested within if statements.


num = input ('enter a number? ')
if num > 0:
    if num > 50:
        print"num > 50"
    elif num > 10:
        print "num > 10"
    else:
        print "num > 0"
else:
    print "num <= 0"


4.3 more complex conditions
Now let's go back to the conditions themselves, because those are the really interesting parts of the execution of the conditions.
4.3.1. Comparison operator

 x == y;     x < y;     x > y;      x >= y;      x <= y;
 x != y;      x is y;     x is not y;   x in y;     x not in y;


4.3.2.   Is: identity operator

>>> x = y = [1,2,3]
>>> z = [1,2,3]
>>> x is y
True
>>> x is z
False
>>> x == z
True

Thus, the == operator is used to determine whether two objects are equal, and is is used to determine whether they are the same object.

4.3.3. In: membership operator

name = raw_input("what is your name?")
if 's' in name:
    print 'your name contains the letter s'
else:
    print 'your name does not contain the letter s'
 

Comparison of strings and sequences
Strings can be compared in character order.
> > > 'alpha' < 'beta'
True,
The characters are arranged in their own order, and the order value of a letter can be looked up using the ord function.
Other sequences can be compared in the same way, but with other types of elements.

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

4.3.5. Boolean operator
The and operator is a so-called Boolean operator that joins two Boolean values and returns true if both are true, or false if both are true. It also has two similar operators, or and not.

number = raw_input("enter a number?")
if number <=10 and number >= 1:
    print "great!"

4.3.6. Assertion
The if statement has a cousin that works like this:

if not condition:
      crash program

This is because instead of letting the program crash later, you can simply let it crash when an error condition occurs. The keyword used in the statement is assert. It ensures that a condition in the program is true for the program to work properly.

>>> age = -1
>>> assert 0 < age < 100
Traceback (most recent call last):
  File "<pyshell#52>", line 1, in <module>
    assert 0 < age < 100
AssertionError
 

  5. Loop
  5.1 the while loop
The while statement is very flexible and allows you to execute a block of code repeatedly in any case that the condition is true.

name = ''
while not name:
    name = raw_input('please enter your name: ')
print 'hello,%s!' % name

  5.2 a for loop
When we want to execute a block of code for each element of a collection (sequence and other iterable objects), we need a for loop.
5.2.1. Loop through dictionary elements
A simple for statement can loop through all the keys of the dictionary, just like a sequence:
D = {' x ': 1, "y" : 2,' z ': 3}
For the key in d:
      The print key, 'corrensponds to' d [key]
5.2.2. Some iteration tools
A. parallel iteration

names = ['a','b','c','d']
ages = [12,23,45,32]
# Loop index iteration 
for i in range(len(names)):
    print names[i],'is',ages[i],'years old.'
# The built-in zip Function iteration 
for name,age in zip(names,ages):
    print name,'is',age,'years old.'

B. Number iteration
Sometimes when you iterate over an object in a sequence, you also get the index of the current object.

#index count 
index = 0
for string in strings:
    if 'xxx' in string:
        string[index] = 'sss'
    index += 1

# The built-in enumerate Function iteration 
for index,string in strings:
    if 'xxx' in string:
        string[index] = 'sss'

C. Flip and sort iterations
() function in any sequence reversed and sorted, or iteration objects, not just modify objects, but turn back or sorted version:

>>> sorted([2,6,3,7])
[2, 3, 6, 7]
>>> list(reversed('hello'))
['o', 'l', 'l', 'e', 'h']

  5.3 break the cycle
Normally the loop will run until the condition is false, or until the sequence element runs out. But sometimes you need to break a loop in advance.
5.3.1. Break
A break statement can be used to end a loop.

for i in range(0,10):
    if i == 5:
        print 'quit'
        break
    print i

5.3.2. Continue
The continue statement closes the current iteration and skips to the beginning of the next loop.

for i in range(0,10):
    if i % 2 == 0:
        continue
    print i

5.3.3. While True/break
For example, do something when the user types a word at the prompt, and end the loop when the user doesn't type the word.

while True:
    word = raw_input('enter a word: ')
    if not word:
        break
    print 'The word is '+ word

6. List derivation -- lightweight loop
List derivation is a way to create a new list from other lists. It works like a for loop:

>>> [x**2 for x in range(10) if x % 3 == 0]
[0, 9, 36, 81]
>>> [(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)
 

  Seven in a threesome
To conclude, let's look at three statements: pass, del, and exec
Pass: does nothing and is used as a placeholder for debugging code.

if a == 'a':
    print 'yes'
elif a == 'b':
    pass
else:
    print 'no'

Del: deletes objects that are no longer in use, i.e., are used for garbage collection.

>>> x = [1,2]
>>> y = x
>>> del x
>>> x
Traceback (most recent call last):
  File "<pyshell#62>", line 1, in <module>
    x
NameError: name 'x' is not defined
>>> y
[1, 2]
 

Del deletes only the name, not the list itself, so in the above example, deleting x does not affect y.
Exec: creates python code dynamically, then executes it as a statement or evaluates it as an expression. However, there is a serious potential security flaw in doing so. If the program executes a part of the string in a piece of content provided by the user as code, the program may lose control of the execution of the code.

>>> exec "print 'hello,world'" 
hello,world


Related articles: