006-python基础-条件判断与循环

一、条件判断

  场景一、用户登陆验证

_username = 'alex'
_password = 'abc123'
username = input("username:")
#password = getpass.getpass("password:")
password = input("password:")

if _username == username and _password == password:
    print("Welcome user {name} login ...".format(name=username))
    #print("Welcome user %s login ..." % (username))
    #print("Welcome user {0} login ...".format(username))
else:
    print("Invalid username or password!")

   场景二、猜年龄游戏

  在程序里设定好你的年龄,然后启动程序让用户猜测,用户输入后,根据他的输入提示用户输入的是否正确,如果错误,提示是猜大了还是小了

 1 #!/usr/bin/env python
 2 # -*- coding: utf-8 -*-
 3  
 4 my_age = 28
 5  
 6 user_input = int(input("input your guess num:"))
 7  
 8 if user_input == my_age:
 9     print("Congratulations, you got it !")
10 elif user_input < my_age:
11     print("Oops,think bigger!")
12 else:
13     print("think smaller!")

二、for循环

   最简单的循环10次

1 #_*_coding:utf-8_*_
2 __author__ = 'Alex Li'
3  
4  
5 for i in range(10):
6     print("loop:", i )

  需求一:还是上面的程序,但是遇到小于5的循环次数就不走了,直接跳入下一次循环

1 for i in range(10):
2     if i<5:
3         continue #不往下走了,直接进入下一次loop
4     print("loop:", i )

  需求二:还是上面的程序,但是遇到大于5的循环次数就不走了,直接退出

1 for i in range(10):
2     if i>5:
3         break #不往下走了,直接跳出整个loop
4     print("loop:", i )

三、while循环

   有一种循环叫死循环,一经触发,就运行个天荒地老、海枯石烂。

1 count = 0
2 while True:
3     print("你是风儿我是沙,缠缠绵绵到天涯...",count)
4     count +=1

  上面的代码循环100次就退出吧

1 count = 0
2 while True:
3     print("你是风儿我是沙,缠缠绵绵到天涯...",count)
4     count +=1
5     if count == 100:
6         print("去你妈的风和沙,你们这些脱了裤子是人,穿上裤子是鬼的臭男人..")
7         break

  回到上面for 循环的例子,如何实现让用户不断的猜年龄,但只给最多3次机会,再猜不对就退出程序。

 1 #!/usr/bin/env python
 2 # -*- coding: utf-8 -*-
 3  
 4  
 5 my_age = 28
 6  
 7 count = 0
 8 while count < 3:
 9     user_input = int(input("input your guess num:"))
10  
11     if user_input == my_age:
12         print("Congratulations, you got it !")
13         break
14     elif user_input < my_age:
15         print("Oops,think bigger!")
16     else:
17         print("think smaller!")
18     count += 1 #每次loop 计数器+1
19 else:
20     print("猜这么多次都不对,你个笨蛋.")

四、关于break与continue

  break用于退出所有循环。

  注:break只跳出一层循环,如果有两个循环,第二个循环嵌套在第一个循环里面,如果第二个循环break了,第一个循环还是会继续执行的。

1 while True:
2     print("123")
3     break
4     print("456")

  continue用于退出当前循环,继续下一次循环

1 while True:
2     print("123")
3     continue
4     print("456")

五、同级别while、for与else的关系

  在while、for正常循环完所设定的次数,中间没有被break中断的话,就会执行else啦,但如果中间被break了,那else语句就不会被执行了。

  正常循环结束后的情况:

 1 flag_exit = False
 2 while not flag_exit:
 3     print("123")
 4     print("456")
 5     flag_exit = True
 6 else:
 7     print("bye")
 8 
 9 #输出
10 123
11 456
12 bye      # 正常循环结束后,执行else下面的语句。

   break退出情况:

 1 flag_exit = False
 2 while not flag_exit:
 3     print("123")
 4     print("456")
 5     break
 6 else:
 7     print("bye")
 8 
 9 #输出
10 123
11 456

 

原文地址:https://www.cnblogs.com/chhphjcpy/p/6062266.html