[小白系列]Python条件判断、循环以及简单迭代从入门到不放弃,快来看看呀

1.条件判断 if

if 的语法

if 条件 :
    # some code
else:
    # other code

注意点:冒号 缩进 执行顺序

num1, num2 = 3 , 5
if num1 > num2:
    print('第一个数是大于第二个数的')
else:
    print('第一个数小于或等于第二个数')
第一个数小于或等于第二个数

例:判断是否是闰年

year = int(input("输入一个年份: ")) 
if (year % 4) == 0:
    if (year % 100) == 0:
        if (year % 400) == 0:
            print("{0} 是闰年".format(year))   # 整百年能被400整除的是闰年
        else:
            print("{0} 不是闰年".format(year))
    else:
        print("{0} 是闰年".format(year))       # 非整百年能被4整除的为闰年
else:
    print("{0} 不是闰年".format(year))
输入一个年份:  1990


1990 不是闰年


请输入一个年份: 1990


1990不是闰年
# 简化版的代码
year = int(input("请输入一个年份:"))
if (year % 4) == 0 and (year % 100) != 0 or (year % 400) == 0:
    print("{0}是闰年".format(year))
else:
    print("{0}不是闰年".format(year))
请输入一个年份: 1990


1990不是闰年

2.循环

2.1for

语法:

for 变量 in 列表 :
    pass          
ls_3
[1, 3, 12.3, 'apple', 0.001]
for i in ls_3:
    print (i)
1
3
12.3
apple
0.001

2.2 while

语法

当型循环,按条件循环,当什么什么的时候,就怎么怎么样

while 条件 :
    pass # 一般在这里进行某些操作,然后修改条件
i = 0
while i<5 :
    print(i)
    i+=1 # 修改条件
0
1
2
3
4

3.迭代

3.1迭代–range

range方法的完整参数:

range(start, end, step = 1)

如果只给定两个参数,省略step,则step默认值为1.

for i in range(1,10,2):
    print(i)
1
3
5
7
9
list(range(1,10,2))
[1, 3, 5, 7, 9]

3.2迭代–iter

序列化的对象除了使用索引进行迭代之外,还可以使用迭代器iter()来实现。
简单讲,就是说有一个next方法,能一个个取出序列中的每个元素。

ourlist = list(range(10))
it = iter(ourlist)  # 使用列表ourlist生产一个迭代器
print(ourlist)
print(next(it))
print(next(it))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
0
1
next(it)
2
mylist = [123, 'xyz', 45.67]
# 对序列对象生成一个迭代器对象
i = iter(mylist)
# 开始迭代得到元素
next(i)
123
next(i)
'xyz'
next(i)
45.67
next(i)
---------------------------------------------------------------------------

StopIteration                             Traceback (most recent call last)

<ipython-input-111-a883b34d6d8a> in <module>
----> 1 next(i)


StopIteration: 

3.3 迭代–zip

就是压缩的意思,它的语法如下:

zip([iterable, ...]) # iterable 可迭代的 也就是序列对象 比如list tuple 等等

直接含义就是,依次从后面这些对象中分别拿一个元素出来拼成一个元组。它返回的是一个元组

names = ['李雷', '韩梅梅']
ages = [25, 24]

# zip(names, ages)
# list(zip(names, ages))
i = iter(zip(names, ages))
next(i)
('李雷', 25)
dict(zip(names, ages)) # 这是非常常用的小技巧
{'李雷': 25, '韩梅梅': 24}

*操作符与zip函数配合可以实现与zip相反的功能,即将合并的序列拆成多个tuple

发布了42 篇原创文章 · 获赞 28 · 访问量 4961

猜你喜欢

转载自blog.csdn.net/KaelCui/article/details/105421728