yujin2010good
作者yujin2010good·2018-12-24 10:00
系统工程师·大型零售巨头

python学习九--流程控制if for while

字数 8288阅读 968评论 0赞 2

一、条件执行和if语句

if 条件:
elif 条件:
else
流程控制语句从上到下执行

=======================

[root@node01 python]# vi ex04.py     
name =  raw_input('pls input your name:')
#age = int(raw_input('pls input your age:'))
#!/usr/bin/env python
#_*_ coding:utf-8 _*_
name =  raw_input('pls input your name:')
#age = int(raw_input('pls input your age:'))
age = input('pls input your age:')
job = raw_input('pls input your jor:')
salary = raw_input('Salary:')
print type(age)
if age >30:
  msg = 'oldold'
elif age >30:
  msg = 'old'
else:
  msg = 'young'
print  '''
Personal information of %s:
  Name: %s
  Age : %d
  Job : %s
  Salay:%s

%s
''' % (name,name, age,job,salary,msg)
[root@node01 python]# python ex04.py 
pls input your name:wolf
pls input your age:40
pls input your jor:it
Salary:10
<type 'int'>

Personal information of wolf:
  Name: wolf
  Age : 40
  Job : it
  Salay:10
-----------------------
oldold

================================

[root@node01 python]# cat ex04.py 
#!/usr/bin/env python
#_*_ coding:utf-8 _*_
name =  raw_input('pls input your name:')
#age = int(raw_input('pls input your age:'))
age = input('pls input your age:')
job = raw_input('pls input your jor:')
salary = raw_input('Salary:')
print type(age)
if age >30:
  msg = 'oldold'
elif age >30:
  msg = 'old'
#else:                         不要这个也不会出错,只是注意下面是否定义变量
#  msg = 'young'

print  '''
Personal information of %s:
  Name: %s
  Age : %d
  Job : %s
  Salay:%s

%s
''' % (name,name, age,job,salary,msg)
[root@node01 python]# python ex04.py     因为上面有变量,所以下面有个错误。
pls input your name:wolf
pls input your age:20
pls input your jor:it
Salary:10
<type 'int'>
Traceback (most recent call last):
  File "ex04.py", line 27, in <module>
    ''' % (name,name, age,job,salary,msg)
NameError: name 'msg' is not defined

=========================================================

二、for循环

for i in rang(1,100)
[root@node01 python]# vi ex05.py 
#!/usr/bin/env python
#_*_ coding:utf-8 _*_
name =  raw_input('pls input your name:')
#age = int(raw_input('pls input your age:'))
job = raw_input('pls input your jor:')
salary = raw_input('Salary:')
for i in range(3):
  age = input('pls input your age:')
  if age >30:
    print 'think smaller'
  elif age ==29:
    print '\\033[32;1mgood\\033[0m'
    break
  else:
    print 'think bigger'
  print 'you still got %s shots!' % (3 - i)
print  '''
Personal information of %s:
  Name: %s
  Age : %d
  Job : %s
  Salay:%s
-----------------------
''' % (name,name, age,job,salary)
[root@node01 python]# python ex05.py 
pls input your name:wolf
pls input your jor:it
Salary:25000
pls input your age:90
think smaller
you still got 3 shots!
pls input your age:20
think bigger
you still got 2 shots!
pls input your age:29
good

Personal information of wolf:
  Name: wolf
  Age : 29
  Job : it
  Salay:25000
-----------------------

====================================

三、while循环

while True:
break
continue

[root@node01 python]# cat while.py 
#!/usr/bin/env python
#_*_ coding:utf-8 _*_
count = 0
while True:
  print 'loop:', count
  count +=1
[root@node01 python]# vi while.py     
#!/usr/bin/env python
#_*_ coding:utf-8 _*_
count = 0
while count < 100000000:
  #print 'loop:', count       这里不打印,很快就显示count值
  count +=1
else:
  print 'loop:', count

#!/usr/bin/env python
#_*_ coding:utf-8 _*_
print_num = input('which loop do you want it to be printed out?')
count = 0
while count < 100000000:
  if count == print_num:
    print 'there you got the number:', count
    choice = raw_input('do you want to continue the loop?(y/n)')
    if choice == 'n':
      break
    else:
      while print_num <= count:
        if print_num <= count:
           print_num = input('which loop do you want it to be printed out?')
        else:
           print u"已经过了,sx!"
  else:
    print 'loop:', count  
  count +=1  
    
else:
  print 'loop:', count  
[root@node01 python]# python while02.py  
which loop do you want it to be printed out?2
loop: 0
loop: 1
there you got the number: 2
do you want to continue the loop?(y/n)y
which loop do you want it to be printed out?1
which loop do you want it to be printed out?2
which loop do you want it to be printed out?3
there you got the number: 3
do you want to continue the loop?(y/n)y
which loop do you want it to be printed out?4
there you got the number: 4
do you want to continue the loop?(y/n)y
which loop do you want it to be printed out?8
loop: 5
loop: 6
loop: 7
there you got the number: 8
do you want to continue the loop?(y/n)n

优化上面的代码

#!/usr/bin/env python
#_*_ coding:utf-8 _*_
import sys

print_num = 0
count = 0
while count < 100000000:
    if count == print_num:
        print 'there you got the number:', count
        while print_num <= count:       
            print_num = input('which loop do you want it to be printed out?')
            if print_num == 0:
                sys.exit('Exit the program!')
          
            if print_num <= count:
                print u"已经过了,sx!"
             
    else:
      print 'loop:', count  
    count +=1     
else:
    print 'loop:', count  

===========================================

练习程序
编写登录接口
输入用户名密码
认证成功后显示欢迎信息
输错三次后锁定

[root@node01 python]# vi user.py     
#!/usr/bin/env python
#_*_ coding:utf-8 _*_
import sys
retry_limit = 3
retry_count = 0
acccount_file = 'accounts.txt'
lock_file = 'account_lock.txt'
while retry_count < retry_limit:
#只要不超过3次就不断循环
    username = raw_input('\\033[32;1mUsername:\\033[0m')
    lock_check = file(lock_file)
    #当用户输入用户名后,打开lock文件,以检查是否此用户已经lock了
    for line in lock_check.readlines():
    #循环LOCK文件
        line = line.split()
        if username == line[0]:
            sys.exit('\\033[32;1mUser %s is locked!:\\033[0m' % usernmae)
            #如果LOCK了就直接退出
    password = raw_input('\\033[32;1mPassword:\\033[0m')
    f = file(acccount_file,'rb')
    #打开帐号文件
    match_flag = False
    #默认为False,如果用户match上了,就设置为True
    for line in f.readlines():
        user,passwd = line.strip('\\n').split()
        #去掉每行多余的\\n并把这一行按空格分成两列,分别赋值为user,passwd两个变量。
        if username == user and password == passwd:
        #判断用户名和密码是否相等
            print 'Match!', username
            match_flag = True
            #相等就把循环外的match_flag变量改为True
            break
            #然后就不用继续循环了,直接跳出,因为已经match上了
    f.close()
    if match_flag == False:
    #如果match_log还为False,代表上面的循环中根本就没有match上用户名和密码,所以需要继续循环。
        print 'User unmatched!'
        retry_count +=1
    else:
        print "Welcome login wolf learning system!"
else:
    print 'your account is locked!'
    f = file(lock_file,'ab')
    f.write(username)
    f.close()

import sys

username = 'alex'
password = 'alex123'
locked = 1 
retry_counter = 0
while retry_counter <3 :
  user = raw_input('Username:').strip()
  if len(user) ==0:
    print '\\033[31;1mUsername cannot be empty!\\033[0m'
    continue
  passwd = raw_input('Password:').strip()
  if len(passwd) == 0:
    print '\\033[31;1mPassword cannot be empty!\\033[0m'
    continue
  #handle the username and passwd empty issue
  #going to the loging verification part
  if locked == 0:#means the user is locekd 
    print 'Your username is locked!'
    sys.exit()
  else:
    if user == username  and passwd == password:
      #means passed the verfification
      sys.exit('Welcome %s login to our system!' % user ) 
    else:
      #retry_counter = retry_counter + 1
      retry_counter += 1 
      print '\\033[31;1mWrong username or password, you have %s more chances!\\033[0m' % (3 - retry_counter  )

===========================================

Python文件的readlines()方法使用readline()读取并返回一个包含行的列表直到EOF。如果可选的sizehint参数存在,则不读取到EOF,它读取总共大约为sizehint大小的字符串(可能在舍入到内部缓冲区大小之后)的整行。仅在遇到EOF时才返回空字符串。

语法
以下是readlines()方法的语法 -
fileObject.readlines( sizehint );

Python参数
sizehint − 这是要从文件读取的字节数。

返回值
此方法返回包含行的列表。

示例
假设’foo.txt‘文件中包含以下行 -

This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line
Shell

以下示例显示了readlines()方法的用法。

#!/usr/bin/python3

# Open a file
fo = open("foo.txt", "r+")
print ("Name of the file: ", fo.name)

line = fo.readlines()
print ("Read Line: %s" % (line))

line = fo.readlines(2)
print ("Read Line: %s" % (line))

# Close opened file
fo.close()
Python

执行上面代码后,将得到以下结果 -

Name of the file: foo.txt
Read Line: ['This is 1st line\n', 'This is 2nd line\n',
'This is 3rd line\n', 'This is 4th line\n', 'This is 5th line\n']
Read Line:

如果觉得我的文章对您有用,请点赞。您的支持将鼓励我继续创作!

2

添加新评论0 条评论

Ctrl+Enter 发表

作者其他文章

相关文章

相关问题

相关资料

X社区推广