第二章、Python 语法

本文详细介绍了Python的基础语法,包括分支结构(if, elif, else)、循环(for, while)和逻辑运算。通过实例展示了Python与Java在语法上的差异,如if语句的缩进和简洁性。同时,讲解了for循环遍历list、tuple、dictionary和range,以及while循环的使用,包括break、continue和pass的控制流。此外,还涉及了逻辑运算符(and, or)和循环辅助工具(range, enumerate, zip, in, not in)的用法。文章最后提到了列表推导式和一些实用的Python库函数,如shuffle和randint。

本章主要介绍 python基础语法,包括分支语法,循环语法, 以及list相关实用用法

1、对比java语法

简单比较 java和python 关于if小代码段

# 一个语法片段, 如果 a > b ,就赋值 a = 2, b=4, 用java写

"""
// java 版
a = 5
b = 2
if(a > b){
 a = 2;
 b = 4;
}
"""
# python 版本
a = 5
b = 2
if a > b:
    a = 2
    b = 4

"""
区分点
 1. 去掉了 () {}
 2. 去掉了 ';'
 3. 条件判断后面跟了 ':'
 4. python有缩进要求,缩进本身促进代码可阅读性
"""

2、if,elif,和else语法

  • elif (省略se, elseif)
  • 语法如下
"""
if case1:
    perform action1
elif case2:
    perform action2

else:
    perform action3
"""

2.1、示例

# 单个分支
if True:
    print('It was true !')

# 两个分支条件: 将会走到else分支上
x = False
if x:
    print('x was True!')
else:
    print('I will be printed in any case where x is not true')

# 多个分支 : 将会打印 'Welcome to the bank'
loc = 'Bank'
if loc == 'Auto Shop':
    print('Welcome to the Auto Shop!')
elif loc == 'Bank':
    print('Welcome to the bank!')
else:
    print('Where are you?')

# 另一个例子 'Welcome Sammy!'
person = 'Sammy'

if person == 'Sammy':
    print('Welcome Sammy!')
else:
    print("Welcome, what's your name?")

#  将会打印 'Welcome George!'
person = 'George'

if person == 'Sammy':
    print('Welcome Sammy')
elif person == 'George':
    print('Welcome George!')
else:
    print("Welcome, what's your name?")

3、for 循环

  • for 适合实现Iterator接口的对象

  • for 一般用用于集合(list, set, dictionary, tuple) 和字符串,以及range函数

  • 语法: 如下


"""
for item in object:
    statements to do stuff
"""

3.1、遍历list

  • 可以结合分支语句进行组合判断(过滤)
  • 可以reduce一个结果
# 1. 第一个例子 for 循环打印list元素
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

for num in list1:
    print(num)

# 2. 我们在原来例子上加上if判断,过滤 偶数打印
print("---华丽分割线---"*100)
for num in list1:
    if num % 2 == 0:
        print(num)

# 3. 我们在加上else分支

for num in list1:
    if num % 2 == 0:
        print(num)
    else:
        print('Odd number')

# 4. sum求和,累加
list_sum = 0
for num in list1:
    list_sum = list_sum + num
print(f"求和:{list_sum}")

# 5. 我们可以使用简写 +=

list_sum = 0
for num in list1:
    list_sum += num
print(f"求和:{list_sum}")

3.2、遍历Tuple

  • 元组,一组固定元素
# 7. 遍历tuple(元组)
tup = (1,2,3,4,5)
for t in tup:
    print(t)

# 8. 遍历tuple 里面包含tuple
list2 = [(2,4), (6,8),(10,12)]
for tup in list2:
    for item in tup:
        print(item)

print("---华丽分割线---"*100)
for (t1, t2) in list2:
    print(t1)

3.3、遍历dictionary

  • 默认遍历key
d = {'k1':1, 'k2':2, 'k3':3}

for item in d:
    print(item)

# 10. 遍历 items 键值对(key-value)
for k, v in d.items():
    print(f"{k}:{v}")

# 11. keys 存入 list中
list(d.keys())

# 12. 排序
sorted(d.values())

3.4、遍历range

  • 一般用于初始化或者循环指定次数情况使用
  • 需要注意它是从0开始的,也就是前闭后开,
# 以下结果为 0到9, 而不是1到10
for num in range(10):
    print(num)

3.5、遍历字符串

  • 遍历字符串的字符
for letter in 'This is a string.':
    print(letter)

4、while 循环

  • 语法如下
  • 跟java 特别地方有 else方法,完善while的分支情况,比如说不满足条件走的分支,最后进入逻辑
  • 满足条件一直进行循环
"""
语法
while test:
 code statements
else:
 final code statements
"""

  • 示例代码
# 1. 例子 循环执行 , x < 10 就执行里面的语句,
x = 0

while x < 10:
    print('x is currently: ', x)
    print(' x is still less than 10, adding 1 to x')
    x += 1
# else 语句
else:
    print('All Done!')

# 2. break , continue, pass
"""
break: 跳出当前loop 循环
continue : 跳过执行,进行下一次循环
pass : 不做任何事情
"""
x = 0
while x < 10:
    print('x is currently: ',x)
    print(' x is still less than 10, adding 1 to x')
    x += 1
    if x == 3:
        print('Breaking  because  x == 3')
        break
    else:
        print('continuing...')
        continue
else:
    print('All Done!')

4.1、while 内部的分支语句

  • break: 跳出当前loop 循环
  • continue : 跳过执行,进行下一次循环
  • pass : 不做任何事情

5、逻辑运算

  • 以上 if 和 for 、已经while 都需要条件为true才能继续
  • python 单个逻辑表达式根据java类似,只有两个表达式表达且和或不一样, java ( && 和 || ),而python(and 和 or)
# 比较运算符, 值为True Or False

# 等于 == : True
2==2

# 不等于 != : True
2 != 1

# 大于 > : True
2 > 1

# 小于 < : True

2 < 4

# 大于等于 >= : True

2 >= 2

# 小于等于 <= : True

2 <= 2

# 2. 比较运算表达式
# and 表达式两边都为True,整个表达式为True
# or 表达式两边只要存在一个为True, 整个表达式为True

# 如果用python 表达 1 < 2 < 3 : True
1 < 2 and 2 < 3

# 结果为True
1 == 2 or 2 < 3

6、循环得力的工具

我们可能有如下诉求

  1. 快速生成有规律等差集合
  2. 循环固定次数
  3. 遍历字符串,能够不用定义变量,来知道字符串索引下标
  4. 想要多个list组合按照索引下标相等进行组合输出
  5. 判断某个元素不在或在集合中

6.1、range

  • 可以实现有规则顺序数据集合
# 1. range 函数, 生成 0 到 10数字,前闭后开
range(0, 11)

a = list(range(0, 11))
print(a)

# 2. 设置range的步长,默认是1, 比如我们设置为2 : [0, 2, 4, 6, 8, 10]
a = list(range(0, 11, 2))
print(a)

6.2、enumerate

  • 能将list,变成一个二元元组(索引,值)的list
# 3. enumerate 自动生成一个index(索引下标),避免我们定义变量来记录
index_count = 0

for letter in 'abcde':
    print("At index {} the letter is {}".format(index_count, letter))
    index_count += 1

# vs enumerate
for i, letter in enumerate('abcde'):
    print("At index {} the letter is {}".format(i, letter))
# 我们可以打印 enumerate('abcde') ,其他是一个tuple [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e')]
print(list(enumerate('abcde')))

6.3、zip

  • 按照索引下标合并多个list, 遍历次数以最短list为准
mylist1 = [1,2,3,4,5]
mylist2 = ['a', 'b', 'c', 'd', 'e']
mylist3 = ['11', '22', '33', '44', '55']

print(list(zip(mylist1, mylist2, mylist3)))
for item1, item2, item3 in zip(mylist1, mylist2, mylist3):
    print('For this tuple, first item was {}, and second item was {}, third item was {}'.format(item1, item2, item3))


6.4、in or not in

  • 语法如下
  • if 元素 in 集合: 表示存在执行逻辑
  • if 元素 not in 集合:表示不存在执行逻辑
# in 作为boolean 条件判断
if 'x' in ['x', 'y', 'z']:
    print(f"exist x :True")

# not in 不存在
'x' not in ['x', 'y', 'z']

7、其他

7.1、打散list集合

  • 需要导入shuffle函数
# 导入 shuffle 包, 打散list
from random import shuffle
shuffle(mylist)
print(mylist)

7.2、随机数

  • 比如说随机整数 (需要导入randint)函数
from random import randint
a = randint(0, 100)
print(a)

7.3、控制台输入

  • 可以等待控制输入交互
  • input函数
# 8、input 操作
a = input('Enter something into this box:')
print(a)

8、list 简化语法

  • 基于特定运算或过滤形成新的list
  • 这个方式对应一些简单运算和过滤一行可以搞定
  • 语法: 支持嵌套
  • [目标表达式 for item in 原list集合 if 条件]

示例

# 1. 例子 字符串变成list
lst = [x for x in 'word']
print(lst)

# 2. 平方 range [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
lst = [x**2 for x in range(0,11)]
print(lst)

# 3. 过滤偶数 [0, 2, 4, 6, 8, 10]
lst = [x for x in range(11) if x % 2 == 0]
print(lst)

# 4. 复杂计算摄氏度转华氏度 [32.0, 50.0, 68.18, 94.1]
celsius = [0, 10, 20.1, 34.5]
fahrenheit = [((9/5)*temp + 32) for temp in celsius]
print(fahrenheit)

# 5. list嵌套list [0, 1, 256, 6561, 65536, 390625, 1679616, 5764801, 16777216, 43046721, 100000000]

lst = [x**2 for x in [x**2 for x in [x**2 for x in range(11)]]]
print(lst)

总结

  • for 中接收变量可以多个,比如tuple就是典型情况,根据tuple每组元素情况, 以及dictionary (k,v)
  • python内置一些常用的方法,比如排序sorted(), len(), max(), min()
  • while 一般基于条件判断,不能确定次数

参考文档

https://github.com/Pierian-Data/Complete-Python-3-Bootcamp.git

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值