python之有关循环的那些事儿

Python for和while循环语句的基础知识!小白请看过来,纯干货!!

Reference: Kaggle Notebook Loops! Click me!

1. 循环(Loops)

循环在计算机语言中是指重复运行某些代码。

看看例子就懂啦~

planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
for planet in planets:
	print(planet, end = ' ') #将数列的所有元素打印在同一行中

输出:

Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune

for循环:
1、需要指定变量名(如上述例子的‘planet’);
2、指定需要循环的一组值(如上述例子的‘planets);
3、这两者中间用‘in’去连接,以冒号结尾;如:for planet in planets:

‘in’右侧的对象可以是任何支持迭代的对象,反正只要是可以视为一组事物的对象,都可以遍历。除了数列外,还有遍历tuples。

example_tuples = (2, 3, 4, 5, 9)
product = 1 #乘积的初始值为1
for i in example_tuples:
	product = product * i 
product

输出:

1080

除了可以遍历数值外,还可以遍历字符串:

s = 'steganograpHy is the practicE of conceaLing a file, message, image, or video within another fiLe, message, image, Or video.'
# print all the uppercase letters in s, one at a time
for char in s:
    if char.isupper():#如果是大写字母,则返回True
        print(char, end='')

输出:

HELLO

char.isupper()是一个可以查找大写字母的函数,小写字母则是char.islower()。

2. range()

range()是一个可以返回数字序列的函数。

看个例子就懂了:

for i in range(3):
	print(i, end = ' ')

输出:

0 1 2

3. while循环

除了for循环,还有一种循环叫while循环。while循环是会一直重复执行代码,直到满足某些条件。

i = 0
while i < 10: # 条件i<10
	print(i, end = ' ')
	i += 1 # i = i + 1

输出:

0 1 2 3 4 5 6 7 8 9 

注意:while循环也是利用布尔语句哦,循环会一直继续直到该语句评估为False。

4. 循环在数列中的应用

a. 写法1:

>>> squares = [n**2 for n in range(10)]
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

b. 写法2:

squares = [] # 创新一个数列
for n in range(10):
    squares.append(n**2) # 调用list.append函数
squares

c. 写法3:

planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
# 返回字母长度小于6的元素
short_planets = [planet for planet in planets if len(planet) < 6] 
short_planets

输出:

['Venus', 'Earth', 'Mars']

如果觉得难理解,可以看看下面这个笨蛋写法:

short_planets = [] # 创建新的数列
for planet in planets:
	if len(planet) < 6: # 条件:字母长度小于6
		short_planets.append(planet) # 则将该元素加到数列的最后	

d. 写法4:

loud_short_planets = [planet.upper() + '!' for planet in planets if len(planet) < 6] # 将字母长度小于6的元素揪出来,并转为大写字母,
loud_short_planets

输出:

['VENUS!', 'EARTH!', 'MARS!']

e. 写法5:

>>> [32 for planet in planets]
[32, 32, 32, 32, 32, 32, 32, 32]

等号左边的变量并不是必须的哦,虽然看上去有点奇怪,但还是可以运行的。

f. 写法6:
还可以结合min、max、sum函数。。。

笨重但易理解版:

def count_negatives(nums):
    """Return the number of negative numbers in the given list.
    
    >>> count_negatives([5, -1, -2, 0, 3])
    2
    """
    n_negative = 0 # 相当于一个计数器
    for num in nums:
        if num < 0: #当num<0时
            n_negative = n_negative + 1 # 计数器+1
    return n_negative

简写版1:

def count_negatives(nums):
    return len([num for num in nums if num < 0])

简写版2:

def count_negatives(nums):
    # Reminder: in the "booleans and conditionals" exercises, we learned about a quirk of 
    # Python where it calculates something like True + True + False + True to be equal to 3.
    return sum([num < 0 for num in nums])

简写有利于减少代码长度,但是可读性也很重要哦~

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值