python基础之流程控制(if判断和while、for循环)

程序执行有三种方式:顺序执行、选择执行、循环执行

一、if条件判断

1、语句  

  (1)简单的 if 语句
  (2)if-else 语句
  (3)if-elif-else 结构
  (4)使用多个 elif 代码块if-elif-elif-...-else(elif可以使用多个)
  (5)省略 else 代码块if-elif-elif(else可以省去)
  (6)测试多个条件(简单if语句)

2、注意:

  (1)if 语句可以相互嵌套;

  (2)if嵌套,可以嵌套多层,但是一般嵌套两层就行了,如果嵌套多层的话不便维护代码,若需要嵌套多层,肯定可以用其它方式代替多层嵌套这种方式。

3、实例1:

#if嵌套用法
names = ["李国祥","任彦忠","毕洪态","张立佳"]
password = 123
name = input("请输入您的名字:")
if name in names:
    passwd = int(input("请输入密码:"))
    if passwd == password:
        print("欢迎光临!")
    else:
        print("密码错误,请重新输入!")
elif name == "游客":
    print("欢迎加入!")
else:
    print("请输入正确的用户名!")
print("人生苦短,我学python!") 

4、实例2:猜年龄

#在程序里设定好你的年龄,然后启动程序让用户猜测,用户输入后,根据他的输入提示用户输入的是否正确,如果错误,提示是猜大了还是小了
my_age = 18
guess_age = int(input("请猜测我的年龄:"))
if guess_age == my_age:
    print("恭喜您才对了!奖励大大滴")
elif guess_age <= my_age:
    print("猜小了,人家已经成年了")
else:
    print("猜大了,我有那么老么?")

外层变量,可以被内层代码使用;

内存变量,不应被外层代码使用。

二、while循环

一般情况下,需要多次重复执行的代码,都可以用循环的方式来完成

循环不是必须要使用的,但是为了提高代码的重复使用率,所以有经验的开发者都会采用循环

实例1:1~100的累加求和

#计算1~100的累计和
i = 1
sum = 0
while i <= 100:
   sum = sum + i
   i += 1
print("1~100的累积和为:%d"%sum)

实例2:99乘法表

i = 1
while i <= 9:
    j = 1
    while j <= i:
        print("%d*%d=%d	"%(j,i,i*j),end="")
        j +=1
    print("")
    i +=1

实例3:打印1~100之间的偶数

#输出1-100之间的所有偶数
i = 1
while i <= 100:
    if i%2 == 0:
        print("i==%d"%i)
    i += 1

实例4:猜年龄,只有3次机会

my_age = 18
count = 0
while count < 3:
    guess_age = int(input("请猜测我的年龄:"))
    if guess_age == my_age:
        print("恭喜您才对了!奖励大大滴")
        break
    elif guess_age < my_age:
        print("猜小了,人家已经成年了")
    else:
        print("猜大了,我有那么老么?")
    count += 1
else:
    print("猜这么多次都没才对,你个笨蛋")

实例5:

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

三、for循环

  像while循环一样,for可以完成循环的功能。
  在Python中 for循环可以遍历任何序列的项目,如一个列表、字符串、元组等等。
  for循环的格式:
  for 临时变量 in 列表或者字符串等:
    循环满足条件时执行的代码
  else:
    循环不满足条件时执行的代码

实例1:遍历

name = "python"
for i in name:
    print("----------------------")
    print(i)

实例2:continue、break

continue的作用:用来结束本次循环,紧接着执行下一次的循环

break的作用:用来结束整个循环

for i in range(10):
    if i<5:
        continue #不往下走了,直接进入下一次loop
    print("loop:", i )
------------------------------------------------------------------
loop: 5
loop: 6
loop: 7
loop: 8
loop: 9
for i in range(10):
    if i>5:
        break #不往下走了,直接跳出整个loop
    print("loop:", i )
------------------------------------------------------------------
loop: 0
loop: 1
loop: 2
loop: 3
loop: 4
loop: 5
#pass,continue,break

#continue跳过本次循环进入下一次循环
 count = 0
 while count <= 5 :
     count += 1
     if count == 3:
         continue
     print("Loop", count)

#breck跳出循环体
 count = 0
 while count <= 5 :
     count += 1
     if count == 3:
         break
     print("Loop", count)

# pass用来占位的%s,%d,{}
 count = 0
 while count <= 5 :
     count += 1
     if count == 3:
         pass
     print("Loop", count)

实例3:猜拳游戏

#猜拳游戏
import random
win = 0
lose = 0
ping = 0
while True:
    print('=====欢迎来猜拳=====')
    print('胜:{}   败:{}   平:{}'.format(win, lose, ping))
    print('1.石头   2.剪刀   3.布   4.退出')
    computer = random.choice(['石头','剪刀','布'])
    hum = input('==>:')
    #赢
    if (hum == '1' and computer == '剪刀') or (hum == '2' and computer =='布') or (hum == '3' and computer == '石头'):
        print('挺牛逼!')
        win += 1

    #输
    elif hum == '3' and computer == '剪刀' or hum == '1' and computer =='布' or hum == '2' and computer == '石头':
        print('菜鸡!')
        lose += 1
    #平
    elif hum == '2' and computer == '剪刀' or hum == '3' and computer =='布' or hum == '1' and computer == '石头':
        print('不要走,决战到天亮')
        ping += 1
    elif hum == '4':
        break
    else:
        print('别瞎输入!!')
    print()
    print()
    print()
    print()

实例4:用户登录验证

第一种方法:
#输入用户名和密码,认证成功后显示欢迎信息,输错三次后锁定
user_info = {'任彦忠':'123','ryz':'123','renyz':'ryz'} count = 0 while count < 3: user_name = input("请输入您的用户名:").strip() if user_name in user_info.keys(): twice_count = count while twice_count < 3: pass_word = input("请输入您的密码:").strip() if pass_word == user_info.get(user_name): print("欢迎登陆") exit() else: print("密码错误,请重新输入") twice_count += 1 count = twice_count else: print('请输入正确的用户名!') count += 1 continue else: print("您已经输错三次了,请稍后重试")
第二种方法:
count = 1 # 定义循环的次数,初始值为1 user = 'test' pwd = '123' while True: # 当循环的次数等于4时,结束循环。count的值经过自加1操作后将会依次走1,2,3这三个数的变化,这就是3次了。 if count == 4: print('Too many times!') # 当超过3次了,提示用户超过尝试登陆次数过多了。 break username = input('Please enter your username:').strip() # 去除用户输入时字符串两边的空格 password = input('Please enter your password:').strip() # 去除用户输入的字符串两边的空格 # 如果用户输入的内容有值时进行以下判断 if username or password: # 当判断用户名和密码都正确时结束循环。 if username == user and password == pwd: print('Login successfully!') exit() # 当用户名和密码匹配成功时退出程序 # 当判断用户名或密码不正确时走else下的条件。 else: print('Login failed,you have %s more chances' % (3 - count)) # 如果用户输入的值为None时,则执行以下打印操作。 else: print('Please enter your user name and password before landing') continue # 当用户输入为空时,跳出本次循环,继续执行如下。 # 让每一次循环都进行自加1操作。 count += 1

实例五:多级菜单

#三级菜单,可依次选择进入各子菜单
data = { "北京":{ "昌平":{ "沙河":{"oldboy","test"}, "天通苑":{"链家地产","我爱我家"} }, "朝阳":{ "望京":{"奔驰","陌陌"}, "国贸":{"CICC","HP"}, "东真门":{"Advent","飞信"}, }, "海淀":{ "运维":{"计算机","IP"}, "云计算":{"python","java"}, "工程师":{"技术大牛","管理"}, }, }, "山东":{ "德州":{"1","2"}, "青岛":{"3","4"}, "济南":{}, }, "山西":{ "太原":{}, "大同":{}, "晋中":{}, }, } exit_flag = False while not exit_flag: for i in data: print(i) choice = input("选择进入1>>:") if choice in data: while not exit_flag: for i2 in data[choice]: print(" ",i2) choice2 = input("选择进入2>>:") if choice2 in data[choice]: while not exit_flag: for i3 in data[choice][choice2]: print(" ",i3) choice3 = input("选择进入3>>:") if choice3 in data[choice][choice2]: for i4 in data[choice][choice2][choice3]: print(" ",i4) choice4 = input("最后一层,按b返回>>:") if choice4 == "b": pass elif choice4 == "q": exit_flag = True if choice3 == "b": break elif choice3 == "q": exit_flag = True if choice2 == "b": break elif choice2 == "q": exit_flag = True
原文地址:https://www.cnblogs.com/renyz/p/11511792.html