python循环

借鉴这位大佬
https://www.jianshu.com/p/2aeee1ed59ec
Python运算符
+, -, *, /
%: 求余数
and:相当于C++的&
*在对列表操作时相当于复制,例如:
g = [0]*3 + [1]*4 + [2]*2 # [0, 0, 0, 1, 1, 1, 1, 2, 2]
**: 幂运算符

Python缩进
同一层次代码缩进量相同,建议跨平台跨编辑器缩进用空格,因为有的编辑器tap=2个空格,有的编辑器tap=4个空格

Python控制流
if & elif & else 条件结构:


 **if结构包括三个关键字:if, elif, else**
pets =['dog', 'cat', 'droid', 'fly']

for pet in pets:
    if pet == 'dog':        # 狗粮
        food = 'steak'     # 牛排
    elif pet == 'cat':      # 猫粮
        food = 'milk'       # 牛奶
    elif pet == 'droid':   # 机器人
        food = 'oil'          # 机油
    elif pet == 'fly':       # 苍蝇
        food = 'sh*t'       # ...
    else:
        pass                  # pass 关键字占位用,什么也不做
    print(food)

 **if表达式中的小技巧**
food = food_for_pet[pet] if pet in food_for_pet else None # 一个if-else常见的行内应用,就是代替三元操作符

意思就是如果pet等于 food_for_pet否则NOne

if -1 < x < 1:  # 等效于 if x > -1 and x < 1:
    print('The absolute value of x is < 1')

if x in ['piano', 'violin', 'drum']:    # 等效于 if x == 'piano' or x == 'violin' or x =='drum':
    print("It's an instrument!")

while 循环结构:

while(条件):
执行语句

具体请看
https://www.runoob.com/python/python-while-loop.html
for 循环结构(常用):



# 遍历列表
a=["aa","bb","cc"]
for i in a:
    print(i)

# 常规循环
for i in range(0,10): # range(0,10)生成0—9这10个数字
    print(i)

# 以上两种循环属于for_each风格,C++11中也开始支持这种for循环方式
# 不过如果还是需要下标呢?比如遍历一个list的时候,希望把对应下标也打印出来
# 这时可以用enumerate
names = ["Rick", "Daryl", "Glenn"]
for i, name in enumerate(names):
    print(i, name)

# 当然你也可以通过下标遍历
words = ["This", "is", "not", "recommended"]
# not pythonic
for i in range(len(words)):
    print(words[i])


break & continue 中断结构:
break 直接全部退出当前循环模块
continue 中断当前循环,继续下一次循环

break & continue 中断结构:

# 
a=["aa","bb","cc"]
for i in a:
    if (i="bb"):
        break
    print(i)
# 
a=["aa","bb","cc"]
for i in a:
    if (i="bb"):
        continue
    print(i)


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值