Python for loop and while statements

1.for loop
for recycling syntax:

for 变量 in range(10):
    循环需要执行的代码
else:
    全部循环结束后要执行的代码

(1) 求1~100之和
for(i=1;i<=100;i++)
sum = 0
for i in range(1,101):
#sum = sum +i
sum += i
print(sum)

(2) the odd request from 1 to 100 and
SUM = 0
for I in Range (1,101,2):
SUM = 1 +
Print (SUM)
(. 3) required only even-numbered 1 to 100 and
SUM = 0
for I in Range (2,101,2):
SUM = I +
Print (SUM)

(4) a user to enter a number, the number factorial: 3! =. 3 2 . 1
NUM = int (INPUT ( 'the Num:'))
RES =. 1
for I in Range (. 1, NUM +. 1):
RES = RES * I
(Print 'results% d factorial is:% d' % (num, res))

User login procedure
1. Enter the user name and password
2. determine the user name and password are correct ( 'root name ==', 'passwd =' westos')
3. In order to prevent brute force, landing only three times, if more than three times the chance, an error

I in Range for (. 3): # 0. 1 2
name = INPUT ( 'User name:')
the passwd = INPUT ( 'password:')
IF name == 'the root' and the passwd == 'westos':
Print (' login success ')
out of the entire cycle, will not be behind the implementation of content
BREAK
the else:
Print (' login failed ')
Print (' You have% d remaining chance '% (2-i))
the else:
Print (' landing times over three times, wait 100s landing again ')

Python for loop and while statements

2. BREAK the Continue Exit
BREAK: out of the whole cycle, not recycled content behind
continue: out of this cycle, continue behind the code is not executed,
but still continue the cycle of
exit (): the end of the run program

for i in range(10):
if i == 5:
#break
#continue
exit()
print(i)

print('hello')

#break
Python for loop and while statements
#continue
Python for loop and while statements
exit()
Python for loop and while statements

3.while statement

while 条件满足:
满足条件执行的语句
else:
不满足条件执行的语句

2、 while 死循环
只要满足 while的条件永远为真,就会进入无限循环
while True:
print('!!!!!!!!!!!!')
3.while嵌套

乘法表
row = 1
while row <= 9:
col = 1
while col <=row:
print('%d %d = %d\t' %(row,col,rowcol),end='')
col += 1
print('')
row += 1

\t:在控制台输出一个制表符,协助我们在输出文本的时候在垂直方向保持对齐
print('1 2 3')
print('10 20 30')
print('1\t2\t3')
print('10\t20\t30')
\n:在控制台输出一个换行符
print('hello\nworld')
\:转译
print('what\'s')

乘法表
Python for loop and while statements

cro = 9
while cro > 0 :
col = cro
while col > 0 :
print('%d%d=%d\t' %(cro,col,crocol),end='')
col -=1
print('')
cro -=1

Python for loop and while statements

cro = 9
while cro > 0 :
col = 9
while col > 0 :
if col > cro :
print(' \t' ,end='')
else:
print('%d%d=%d\t' %(cro,col,crocol),end='')
col -=1
print('')
cro -=1
Python for loop and while statements

cro = 1
while cro <= 9 :
col = 9
while col > 0 :
if cro < col :
print(' \t' ,end='')
else:
print('%d%d=%d\t' %(cro,col,crocol),end='')
col -=1
print('')
cro +=1

Python for loop and while statements

Guess you like

Origin blog.51cto.com/12893781/2400950