Skip to content

Instantly share code, notes, and snippets.

@TianZonglin
Created February 28, 2020 16:19
Show Gist options
  • Save TianZonglin/169ece232e38bb4db7b7b1deb6de560c to your computer and use it in GitHub Desktop.
Save TianZonglin/169ece232e38bb4db7b7b1deb6de560c to your computer and use it in GitHub Desktop.
date: 2017-10-15
categories: Python学习笔记
tags: [Python]
comments: true
title: Python的控制流
---
注:此为慕课网Python(不打广告)视频的观看笔记,只做记录之用,并未勘误。
<!-- more -->
### 使用分支时注意
#### 变量命名规范:
用户名:user_name,按下划线而不是驼峰
#### 条件控制
if else
#### 循环控制
for while break continue
#### 分支控制
没有switch
没有goto
### Python的if控制
#### 判断元素为空:
if not [] :
print('该元素为空')
#### 判断输入用户输入变量是否正确:
account = 'admin'
passwd = 'admin'
print('input:')
i_account = input()
print('input:')
i_passwd = input()
if (i_account == account) and (i_passwd == passwd):
print('success')
else:
print('error')
#### 程序规范问题:
不合法的变量定义:
[pylint] C0103:Invalid constant name "account"
python没有常量机制,但是有默认规范:
常量变量名要:全部大写!(包括串常量和输入值!)
缺失模块定义:
[pylint] C0103:Invalid module name "Untitled-1"
[pylint] C0111:Missing module docstring
每个文件第一行需要进行此代码段的模块说明,使用块注释!
其他错误:
pylint监测
另外,python代码隔离用四个空格或Tab
#### 使用snippet片段快捷的定义各种 python代码段,循环、类、函数等等
if condition:
pass #pass是空语句,占位语句,如果什么都不写,则会报错
else:
pass
这均作为结构体,有变量作用域的问题
嵌套控制
多个if嵌套,封装:提取为函数,具体逻辑封装到函数中
单程控制
if elif else,同一级别完成多个判断(python没有开关控制switch!)
替换switch:
多个elif、使用dict字典
参见python.doc.org//程序设计的F&Q
#### 对于input():
动态型语言,输入类型不可控,且输入后并不报错
接收到的值为字符串,如果需要整形:则需要int()转换
#### if用法实例,判断输入:
ACCOUNT = 'admin'
PASSWD = 'admin'
ACCOUNT1 = input()
PASSWD2 = input()
if (ACCOUNT1 == ACCOUNT) and (PASSWD2 == PASSWD):
print('success')
else:
print('error')
### Python的循环控制
#### while循环:
直到型循环,直到目标之后才结束循环
适合于递归
#### 示例:
CONDITION = True
while CONDITION:
CONDITION = bool(input())
print(1)
else:
print(2)
#### for循环:
适用于序列、集合字典的遍历!
直接取的就是元素,会去掉外层包装
#### 示例:
for x in [1,['a','b'],3,(4,5)]:
if not isinstance(x,int):
for y in x:
print(y)
else:
print(x)
#### 注意:
for-else,while-else循环的最后会执行,一般用不到
#### 循环的跳出
break 跳出循环,终止循环,对于for-else,while-else,不会执行else
continue 跳出当前循环,会执行else
#### 示例:
for x in [1,2,3]:
if x == 2:
continue
print(x)
else:
print('EOF')
#### 注意:
均作用于当前循环,多层循环要多个break
Python的for循环没有类似Java的指定次数的形式
类似for(int i=0;i<10;i++):
for x in range(0,10):
print(x)
类似for(int i=0;i<10;i+=2):步长为2
for x in range(0,10,-2):
print(x,end='-\n')
类似for(int i=10;i>0;i-=2):递减
for x in range(10,0,-2):
print(x,end='\n') #print带参数
独有的特性:
用for打印间隔步长的元素:
a = [1,2,3,4,5,6,7,8]
for x in range(0,len(a),2):
print(a[x],end=' ')
#输出 1 3 5 7
用切片用法取间隔元素:
print(a[0:len(a):2])
#输出 [1, 3, 5, 7]'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment