007: 基本控制语句 for , while, 和 range 数据类型

Python中的for语句与其它语言for语句略有不同,它是迭代一个序列。

The for statement in Python differs a bit from what you may be used to in C or Pascal. Rather than always iterating over an arithmetic progression of numbers (like in Pascal), or giving the user the ability to define both the iteration step and halting condition (as C), Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence. For example (no pun intended)

for常常与range一起使用,所以也在这里一并了学习。

The range type represents an immutable sequence of numbers and is commonly used for looping a specific number of times in for loops.

1) range(stop)

2) range(startstop[, step])

The arguments to the range constructor must be integers (either built-in int or any object that implements the __index__ special method). If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0. If step is zero, ValueError is raised.

For a positive step, the contents of a range r are determined by the formula r[i] start step*i where >= 0 and r[i] stop.

For a negative step, the contents of the range are still determined by the formula r[i] start step*i, but the constraints are >= 0 and r[i] stop.

A range object will be empty if r[0] does not meet the value constraint. Ranges do support negative indices, but these are interpreted as indexing from the end of the sequence determined by the positive indices.

Ranges containing absolute values larger than sys.maxsize are permitted but some features (such as len()) may raise OverflowError.

while的语法比较简单,直接看例子也就明白了

range_a = range(5)
range_b = range(1,5,2)
range_c = range(-1,-5,-2)

list_a = [1,2,3,4,5]

tuple_a = (6,7,8)

# loop by range
print('range(5):')

for x in range_a:
    print(x)

print('range(1,5,2)')

for x in range_b:
    print(x)    

print('range(-1,-5,-2)')

for x in range_c:
    print(x)        

# loop by list
print('[1,2,3,4,5]')
for x in list_a:
    print(x)    

# loop by tuple
print('(6,7,8)')
for x in tuple_a:
    print(x)        

# continue for loop
print('continue')
for x in list_a:
    if x %2 == 0:
        continue
    print(x)

# break for loop
print('break')
for x in list_a:
    if x %4 == 0:
        break
    print(x)    

# else for loop:
# Loop statements may have an else clause; 
# it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), 
# but not when the loop is terminated by a break statement.

print('prime number:')

for n in range(2,10):
    for x in range(2,n):
        if n % x ==0:
            print(n, 'equals', x, '*', n//x)
            break
    else:
        print(n, 'is a prime number')

# while

print('loop')
loop = 6

while loop >= 1:
    print(loop)        
    loop = loop -1
    
原文地址:https://www.cnblogs.com/jcsz/p/5102384.html