Python语法

if判断

if 条件:
    如果条件为真执行的语句块
  • 判断条件:数据类型也可以当作判断条件。任何值为0的数字都是假,非0为真;任何空对象都是假,非空为真;关键字None也表示假
if 'th' in 'python':
    print('yes')

if -0.0:
    print('值为0表示False')

if 100:
    print('值非0表示真')

if ' ':
    print('空格也是一个字符,为真')

if '':
    print('长度为0的字符串,为假')

if []:
    print('空列表为假')

if not None:
    print('None为假,取反为真')
  • 三元运算符,也叫条件表达式
a = 10
b = 20
# if a < b:
#     s = a
# else:
#     s = b
# print(s)

s = a if a < b else b   # 它是以上注释部分的简写
print(s)
# 模拟登录脚本
print('plz input your username and password')
user = input('username: ')
passwd = input('password: ')
if user == 'bob' and passwd == '123456':
    print('Login successful!')
else:
    print('Login inorrect!')

扩展if语句

  • 扩展if语句:它是多分支结构,只会执行一个分支
if 条件1:
    条件1为真才执行的语句
elif 条件2:
    条件2为真才执行的语句
elif 条件3:
    条件3为真才执行的语句
... ...
else:
    所有条件都不满足才执行的语句
# 石头剪刀布脚本
import random

computer = random.choice(['石头', '剪刀', '布'])
player = input('请出拳(石头、剪刀、布): ')
print('你出了%s,计算机出了%s' % (player, computer))

if player == '石头':
   if computer == '石头':
       print('平局')
   elif computer == '剪刀':
       print('You Win!!!')
   else:
       print('You Lose!!!')
elif player == '剪刀':
    if computer == '石头':
        print('平局')
    elif computer == '剪刀':
        print('平局')
    else:
        print('You Win!!!')
else:
    if computer == '石头':
        print('You Win!!!')
    elif computer == '剪刀':
        print('You Lose!!!')
    else:
        print('平局')

优化:

import random

computer = random.choice(['石头', '剪刀', '布'])
player = input('请出拳(石头、剪刀、布): ')
print('你出了%s,电脑出了%s' % (player,computer))
if (computer == '石头' and player == '布') or (computer == '剪刀' and player == '石头') or (computer == '布' and player == '剪刀'):
    print('You Win!!!')
elif computer == player:
    print('平局')
else:
    print('You Lose!!!')

再优化:

import random

option = ['石头', '剪刀', '布']
computer = random.choice(option)
player = int(input('''请出拳:
(0)石头
(1)剪刀
(2)布'''))
loses = [['石头', '布'], ['剪刀', '石头'], ['布', '剪刀']]
print('你出了%s,电脑出了%s' % (option[player],computer))

if [option[player], computer] in loses:
    print('\033[31;1mYou Lose!!!\033[0m')
elif computer == player:
    print('\033[32;1m平局\033[0m')
else:
    print('\033[31;1mYou Win!!!\033[0m')
  • 终端颜色
[root@localhost python01] echo -e "OK"
[root@localhost python01] echo -e "\033[31;1mOK\033[0m"  # 红色的OK
[root@localhost python01] echo -e "\033[32;1mOK\033[0m"  # 绿色的OK
# 3x是前景色,4x是背景色
[root@localhost python01] echo -e "\033[32;44;1mOK\033[0m"
[root@localhost python01] echo -e "\033[32;5mOK\033[0m"   # 5m文字闪

循环

  • 一组被重复执行的语句称之为循环体,能否继续重复, 决定循环的终止条件
  • Pythonwhile中的循环有循环和for循环
  • 循环次数未知的情况下,建议采用 while循环
  • 循环次数可以预知的情况下,建议采用for循环

1)while

while 条件:
    条件为真时,执行的语句块

使用while循环优化石头剪刀布脚本为三局两胜:

import random

option = ['石头', '剪刀', '布']
pwin = 0
cwin = 0
loses = [['石头', '布'], ['剪刀', '石头'], ['布', '剪刀']]

while pwin < 2 and cwin < 2:
    computer = random.choice(option)
    player = int(input('''请出拳:
    (0)石头
    (1)剪刀
    (2)布'''))

    print('你出了%s,电脑出了%s' % (option[player],computer))

    if [option[player], computer] in loses:
        print('\033[31;1mYou Lose!!!\033[0m')
        cwin += 1
    elif computer == player:
        print('\033[32;1m平局\033[0m')
    else:
        print('\033[31;1mYou Win!!!\033[0m')
        pwin += 1
else:
    if pwin == 2:
        print('\033[32;1mYou won the game!\033[0m')
    else:
        print('\033[31;1mYou lost the game!\033[0m')

循环语句进阶

break

  • break语句可以结束循环体然后跳转到循环之后得语句
  • 写程序的时候,应尽量避免重复的代码,在这种情况下可以使用whle- break结构

continue

  • 当遇到continue语句时,程序会终止当前循环,并忽略剩余的语句,然后开始下一次循环
  • 如果仍然满足循环条件,循环体内语句继续执行,否则退出循环
# 求1 - 100 中偶数的和
result = 0
i = 0
while i < 100:
    i += 1
    if i % 2:
        continue
    result += i
print(result)

else

  • python中的 while语句也支持else子句
  • else子句只在循环完成后执行
  • break语句也会跳过else块
import random

num = random.randint(1, 100)
i = 5

while i > 0:
    c = int(input('请猜数字(1-100): '))
    if 1 <= c <= 100:
        i -= 1
        if c == num:
            print('猜对了')
            break
        elif c > num:
            print('猜大了,你还有%s次机会' % i)
        else:
            print('猜小了,你还有%s次机会' % i)
    else:
        print('输入有误')
else:
    print('正确数字为:%s' % (num))

2)for循环

for 变量 in 对象:
    语句
  • for循环也有break / else / continue,用法与while一样

range函数

  • 用于产生数字
  • 默认生成一个range对象,取值时它会临时生成一个数字
>>> range(10)
range(0, 10)
>>> for i in range(10):
>>> list(range(10))   # 10是结束数字,结束数字不包含
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(6, 10))  # 起始数字从6开始
[6, 7, 8, 9]
>>> list(range(1, 11, 2))
[1, 3, 5, 7, 9]
>>> list(range(10, 0, -1))
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

列表解析

  • 生成列表的一种方式
>>> [10]
[10]
>>> [5 + 5]   # 将表达式计算结果放到列表中
[10]
>>> [5 + 5 for i in range(1, 11)]  # 5 + 5计算10次,每次结果放到列表>中
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
>>> [5 + i for i in range(1, 11)]  # 表达式可以使用for循环的变量
[6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
# 使用if作为过滤条件,条件为真计算表达式
>>> [5 + i for i in range(1, 11) if i % 2 == 0]
[7, 9, 11, 13, 15]
# 生成192.168.1.0网段所有的IP地址
>>> ['192.168.1.%s' % i for i in range(1, 255)]
>>> ['192.168.1.' + str(i) for i in range(1, 255)]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章