Python的基本操作——2.1 控制流

桃扇骨 2021-09-27 04:00 347阅读 0赞

视频教程来自:www.zygx8.com,谢谢!

一、 If 语句

  1. if 条件:
  2. 语句1
  3. elif 条件2
  4. 语句2
  5. else
  6. 语句3

范例:

  1. # if-猜数字
  2. number=66
  3. guess=int(input('Enter an intenger: '))
  4. if guess==number:
  5. print('you are right!')
  6. elif guess<number:
  7. print('the number is higher than that')
  8. else:
  9. print('the number is lower than that')

二、For 语句

  1. # for语句
  2. #1
  3. for i in range(1,10):
  4. print(i)
  5. else:
  6. print('done')
  7. #2
  8. a_list=[1,2,4,5,8]
  9. for i in a_list:
  10. print(i)
  11. #3
  12. a_tuple=(2,3,5,6)
  13. for i in a_tuple:
  14. print(i)
  15. ano_tuple=('a','b','c')
  16. for i in ano_tuple:
  17. print(i)
  18. #4
  19. a_dict={'Tom':11,"May":23}
  20. for ele in a_dict:
  21. print(ele)
  22. print(a_dict[ele])

三、while 语句

  1. # while 语句
  2. number=66
  3. flag=True
  4. while flag:
  5. guess=int(input('Enter an intenger: '))
  6. if guess==number:
  7. print('you are right!')
  8. flag=False
  9. elif guess<number:
  10. print('the number is higher than that')
  11. else:
  12. print('the number is lower than that')
  13. print('done!')

四、range 语句

  1. # range 语句:range(1,10),实际上是从1-9,包括前面不包括后面
  2. # 同猜数字,限定次数时
  3. number=66
  4. chances=3 #3次机会
  5. for i in range(1,chances+1):
  6. guess = int(input('Enter an intenger: '))
  7. if guess == number:
  8. print('you are right!')
  9. flag = False
  10. elif guess < number:
  11. print('the number is higher than that')
  12. print('you still have '+str(chances-i)+' chances')
  13. else:
  14. print('the number is lower than that')
  15. print('you still have ' + str(chances - i) + ' chances')
  16. print('done!')

五、其他

  1. break:跳出整个循环

  2. continue:忽略循环剩下的部分,重新回到for的部分

  3. pass:相当于什么都没有

    pass

    list1=[0,1,2]
    for i in list1:

    1. if not i:
    2. continue
    3. print(i)

    i=0, if生效,执行continue,忽略循环体剩余部分,进入下一次循环i=1

    i=1, if不满足,继续执行print;i=2时一样的道理

    【注意】:python中,布尔型属于int,其实就是1-0

    for i in list1:

    1. if not i:
    2. pass
    3. print(i)

    i=0,if生效,执行pass,pass相当于什么都没有,所以继续执行print

最后我想吐槽一下,为什么我的程序代码乌漆抹黑的???为什么???

70

发表评论

表情:
评论列表 (有 0 条评论,347人围观)

还没有评论,来说两句吧...

相关阅读

    相关 python控制(4)

    Python3 条件控制 Python条件语句是通过一条或多条语句的执行结果(True或者False)来决定执行的代码块。 可以通过下图来简单了解条件语句的执行过程: