3. 流程控制语句

基于网络课程《Python全栈开发专题》 记录笔记,请支持正版课程

print()命名参数

# print, sep命令参数
print('Ruby', 'Python', 'java', sep=' | ')
# print, end命令参数
print('Hello ', end='')
print('World')

赋值操作

x, y = 10, 20
print(x, y)    # 10 20

# 交换两个变量的值
x, y = y, x
print(x, y)    # 20 10

x += 1
print(x)   # 21

Boolean类型

以下都等效于False:None, 0, "",(), [], {}

print('None =', bool(None))
print('0 =', bool(0))
print('\'\' =', bool(''))
print('() =', bool(()))
print('[] =', bool([]))
print('{} =', bool({}))

Python中,True就是1,False就是0

print('' == False)        # False
print([] == False)        # False
print(bool('') == False)  # True

# 数字0 == False; 1 == True
print(0 == False)         # True
print(1 == True)          # True
print(2 == True)          # False
print(bool(2) == True)    # True
print(12 + True + False)  # 13

条件判断语句: if/else/elif

name = input("Your name:")

if name.startswith("A"):
    print("Your name start with A.")
elif name.startswith("B"):
    print("Your name start with B.")
    if name.endswith("B"):
        print("Mr. BB")
    elif name.endswith("C"):
        print("Mr. BC")
    else:
        print("Mr. Bx")
else:
    print("Your name start with others.")

if - else 单行写法

'''
当if为真,b = a,否则 ""
'''
a = [1,2,3]
b = a if len(a) != 0 else ""
b = [1,2,3]#结果

a = []
b = a if len(a) != 0 else ""
b = ""#结果

比较运算符

is / is not

# is 判断是否为同一个对象
# is not
x = 1
m = 1
z = x
y = (x+1)

print(x is z) # True
print(x is y) # False
print(x is not y) #True

in / not in

x = 5
y = 6
all = [1, 2, 5]

print(x in all)      # True
print(y in all)      # False
print(x not in all)  # True

and / or / not

print(1 == 1 and 1 < 2 or 1 > 2)

断言

value = 20
assert(value < 5)
'''
控制台抛出异常:
Traceback (most recent call last):
  File "H:\PythonWorkSpace\first-python\src\First.py", line 3, in 
    assert(value < 5)
AssertionError
'''

while循环

x = 0
while x <= 10:
    print(x)
    x += 1

for 循环

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for n in nums:
    print(n, end=" ")
names = ['Tom', 'Jerry', 'Kitty']
# 等效: for i in range(0, len(names)):
for i in range(len(names)):
    print(names[i], end=" ")

break & continue

while / for ... else

如果循环中break了,不走else。else代码块仅在循环正常退出时执行。

x = 0
while x <= 3:
    if x == 2:
        print()
        print('do break ...')
        break
    print(x, end=" ")
    x += 1
else:
    print()
    print('no break work:', x); 

exec / eval

一个程序中,多次使用exec(),共享上下文:

exec('i = 1')
exec('i += 1')
exec('print(i)');  # 2

exec()和也程序共享上下文:

x = 5
exec('print(x)') # 5
exec('x += 1')
print(x)  # 6

eval()执行一个表达式,有返回值。exec()没有返回值。

练习:一个简单的Python控制台

codes = ""

while True:
    code = input(">>> ")
    if code == "":
        print('=====', codes, '=====', sep='\n')
        print('输出:', end=' ')
        exec(codes)
        codes = ""
        continue
    codes += code + '\n'
    if codes == "exit()" + '\n':
        print('Bye Bye ...')
        break

练习:输出一个菱形

Python中,数字可以和字符乘!

# 打印菱形

# 打印n个'*', 宽度为width, 居中显示
# def printer(n, width):
#     s, i = "", 0;
#     while i < n:
#         i += 1
#         s += '*'
#     print(format(s, '^' + str(width)))

# 打印菱形
def buildPicture(line):

    maxLine = (line - 1) / 2  # 中间最宽的行
    
    # i 遍历行号
    # x 每行要打印的“*”个数
    i, x = 1, 1
    
    while i <= line:
        
        print(format(x * '*', '^' + str(line)))
        
        if i <= maxLine:
            x += 2
        else:
            x -= 2
        i += 1
    

while True:
    print('---------------------------------------');
    line = int(input('请输入行数(输入0退出):'))
    if line == 0:
        print('Bye Bye!')
        break
    elif not line % 2 :
        print('请输入一个奇数!')
        continue
    buildPicture(line)

练习:Python版九九乘法表

num = [1, 2, 3, 4, 5, 6, 7, 8, 9]

for i in num:
    for j in num:
        if i < j:
            continue
        print(j, i, sep=" * ", end=' = ')
        print(format(i*j, '>2'), end="   ")
    print()
print(format('\u6211\u7231\u5E2D\u59DD\u6850', '=^110'))

你可能感兴趣的:(3. 流程控制语句)