Python intro conditions loops

  • 2020-04-02 14:18:20
  • OfStack

1. If statements

The if clause in Python looks familiar and consists of three parts: the keyword itself, the conditional expression that determines whether the result is true or false, and the block of code that executes if the expression is true or non-zero.
The syntax of the if statement is as follows:
The if expression:
expr_true_suite
The expr_true_suite block of the if statement is executed only if the Boolean value of the result of the conditional expression is true, otherwise the statement immediately following the block continues to execute.

(1) multiple conditional expressions

A single if statement can implement multiple or negative judgment conditions by using the Boolean operators and, or, and not.


if not warn and (system_load >= 10):
print "WARNING: losing resources"
warn += 1

(2) the code block of a single statement

If a block of code for a compound statement (such as an if clause, a while or a for loop) contains only one line of code, it can be written on the same line as the previous statement:
If make_hard_copy: send_data_to_printer ()

While it may be convenient, it makes the code more difficult to read, so we recommend moving this line of code to the next line and indenting it properly.

2. The else statement

Python provides an else statement that is used with the if statement. If the conditional expression of the if statement results in a Boolean value that is false, the program executes the code behind the else statement.


if expression:
  expr_true_suite
else:
  expr_false_suite if passwd == user.passwd:
    ret_str = "password accepted"
    id = user.id valid = True
else:
    ret_str = "invalid password entered... try again!"
    valid = False

3. Elif (else-if) statement

Elif is Python's elf-if statement that checks for multiple expressions to be true and executes code in a particular block of code when true.


if expression1:
  expr1_true_suite
elif expression2:
  expr2_true_suite
elif expressionN:
  exprN_true_suite
else:
  none_of_the_above_suite

4. Conditional expression (i.e. "ternary operator ")

The syntax for the Python 2.5 integration is determined to be: X if C else Y.


>>> x, y = 4, 3
>>> smaller = x if x < y else y
>>> smaller
3

5. While statement

Python's while is the first loop we encounter in this chapter. In fact, it is a conditional loop. In contrast to the if declaration, if the condition after the if is true, the corresponding block of code is executed once.
The syntax for the while loop is as follows:


while expression:
  suite_to_repeat >>> x=1
>>> while x <=100:
    print x
    x+=10

6. A for statement

Python give us another cycle mechanism is for statement. It provides the most powerful in Python loop structure. It can traverse sequence members, can be used in a list of parsing and generator expressions, it will automatically call iterator next () method to capture StopIteration exception and end loop (all of which are internally). And the for statement in the traditional language, Python's for more like a shell or the foreach loop in the scripting language.

The for loop accesses all the elements in an iterable object (such as a sequence or iterator) and ends the loop after all the entries have been processed.


for iter_var in iterable:
  suite_to_repeat

1. For sequence types


>>> for c in 'names':
    print 'current letter: ', c current letter:  n
current letter:  a
current letter:  m
current letter:  e
current letter:  s

There are three basic methods of iterative sequence:

1. Iteration through sequence items:


>>> namelists = ['henry', 'john', 'steven']
>>> for eachName in namelists:
      print eachName, 'Lim'
   
henry Lim
john Lim
steven Lim

2. Through sequence index iteration:


>>> namelists = ['henry', 'john', 'steven']
>>> for nameindex in range(len(namelists)):
    print 'Liu, ', namelists[nameindex] Liu,  henry
Liu,  john
Liu,  steven

3. Iteration using items and indexes:

The best of both worlds is to use the built-in enumerate() function, which is a new addition to Python 2.3.


>>> namelists = ['henry', 'john', 'steven']
>>> for i, eachLee in enumerate(namelists):
    print "%d %s Lee" % (i+1, eachLee)
   
1 henry Lee
2 john Lee
3 steven Lee

2. For iterator types

The iterator object has a next() method that returns the next item. When all items have been iterated, the iterator raises a StopIteration exception to tell the program to end the loop.

3. Range () built-in function

The built-in function range() turns a for loop like foreach into something you're more familiar with

Python provides two different methods to call range (). The full syntax requires two or three integer arguments:
Range (start, end, step = 1)
Range () is going to return a list of all k's, so start < = k. < From start to end, k increments step every time. Step cannot be taken as zero, otherwise an error will occur.


>>> range(2, 19, 3)
[2, 5, 8, 11, 14, 17]

If only two parameters are given and the step is omitted, the default value of step is 1.


>>> range(3, 7)
[3, 4, 5, 6]

Range () also has two short syntax formats:
Range (the end)
Range (start, end)

4. Xrange () built-in function

Xrange () is similar to range(), but when you have a large list of ranges, xrange() is probably better because it doesn't create a full copy of the list in memory. Again, as you can imagine, it's much better than range() because it doesn't generate the entire list.

5. Sequence-related built-in functions

Sorted (), the reversed (), enumerate (), zip ()

Sorted () and the zip () returns a sequence (list), and the other two functions reversed () and enumerate () returns an iterator (similar to sequence)

7. Break statement

The break statement in Python can terminate the current loop and jump to the next statement, similar to the traditional break in c. it is commonly used in while and for loops when an external condition is triggered (usually by an if statement check) and you need to exit the loop immediately.

8. The continue statement

The continue statement in Python is not different from the traditional continue statement in other high-level languages, and it can be used in while and for loops.


valid = False
count = 3
while count > 0:
  input = raw_input("enter password")
  # check for valid passwd
  for eachPasswd in passwdList:
    if input == eachPasswd:
      valid = True
      break
    if not valid: # (or valid == 0)
      print "invalid input"
      count -= 1
      continue
    else:
      break

The example USES a combination of while, for, if, break, and continue to validate the user's input. The user has three chances to enter the correct password, if it fails, the valid variable will still be a Boolean false (0), and the necessary actions can be taken to prevent the user from guessing the password.

9. Pass statement

Python provides the pass statement, which doesn't do anything -- NOP,(No OPeration, No OPeration) -- which we borrowed from assembly language.


def foo_func():
    pass
# or
if user_choice == 'do_calc':
    pass else:
    pass

This code structure is useful for development and debugging, because you might want to set the structure first when writing code, but you don't want it to interfere with other code that's already done.

Iterator and iter() function

Iterator is a next () method of the object, rather than through the index to count. When you or a circulation mechanism (for example for statement) to the next item, call iterator next () method can get it. After get all entries, will trigger a StopIteration exception, this does not mean error occurs, just tell the external caller, iteration is complete.

Limitation: cannot move backwards, cannot go back to the beginning, and cannot copy an iterator.

Reversed () built-in function returns a antitone access iterators. Enumerate () built-in function also returns an iterator. The other two new built-in function, any and all () ()

Python also provides an entire itertools module that contains a variety of useful iterators.


>>> tupe=(12,'2',45.45)
>>> i = iter(tupe)
>>> i.next()
12
>>> i.next()
'2'
>>> i.next()
45.45
>>> i.next()
Traceback (most recent call last):
  File "<pyshell#72>", line 1, in <module>
    i.next()
StopIteration

Create iterator

Iter () is called on an object to get its iterator.
Iter (obj)
Iter (func, sentinel)
If you pass a parameter to iter(), it checks whether you're passing a sequence or not, and if so, it's simple: iterate from 0 to the end of the sequence according to the index.

If iter() is passed two arguments, it calls func repeatedly until the next value of the iterator equals sentinel.

Import something as another event

When importing a function from a module


import somemodule

or


from somemodule import somefunction

or

from somemodule import somefunction, anotherfunction, yetanotherfunction

or

from somemodule import *

If both modules have open functions, simply import them in the first way and use the function as follows:

module1.open(...) module2.open(...)

Or: you can add an as clause at the end of a statement, give the 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

What we're doing here is called sequence unpacking -- unpacking a sequence of values into a sequence of variables, which is more visually expressed as:


>>> values=1,2,3
>>> values
(1, 2, 3)
>>> x,y,z=values
>>> x
1
>>> y
2
>>> z
3


Related articles: